forked from shroominic/codeinterpreter-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: add MarkdownFileCallbackHandler
- Loading branch information
Showing
8 changed files
with
164 additions
and
88 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
import datetime | ||
import os | ||
from typing import Any, Dict, List | ||
|
||
from langchain.callbacks import FileCallbackHandler | ||
from langchain.schema import AgentAction, AgentFinish, LLMResult | ||
|
||
|
||
class MarkdownFileCallbackHandler(FileCallbackHandler): | ||
def __init__(self, filename: str = "langchain_log.md"): | ||
if os.path.isfile(filename): | ||
os.remove(filename) | ||
super().__init__(filename, "a") | ||
self.step_count = 0 | ||
|
||
def on_llm_start(self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any) -> None: | ||
self.step_count += 1 | ||
self._write_to_file(f"## Step {self.step_count}: LLM Start\n\n") | ||
self._write_to_file(f"**Timestamp:** {self._get_timestamp()}\n\n") | ||
self._write_to_file("**Prompts:**\n\n") | ||
for i, prompt in enumerate(prompts, 1): | ||
self._write_to_file(f"```\nPrompt {i}:\n{prompt}\n```\n\n") | ||
|
||
def on_llm_end(self, response: LLMResult, **kwargs: Any) -> None: | ||
self._write_to_file("**LLM Response:**\n\n") | ||
for generation in response.generations[0]: | ||
self._write_to_file(f"```\n{generation.text}\n```\n\n") | ||
self._write_to_file("---\n\n") | ||
|
||
def on_chain_start(self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any) -> None: | ||
self.step_count += 1 | ||
chain_name = serialized.get("name", "Unknown Chain") | ||
self._write_to_file(f"## Step {self.step_count}: Chain Start - {chain_name}\n\n") | ||
self._write_to_file(f"**Timestamp:** {self._get_timestamp()}\n\n") | ||
self._write_to_file("**Inputs:**\n\n") | ||
self._write_to_file(f"```\n{inputs}\n```\n\n") | ||
|
||
def on_chain_end(self, outputs: Dict[str, Any], **kwargs: Any) -> None: | ||
self._write_to_file("**Outputs:**\n\n") | ||
self._write_to_file(f"```\n{outputs}\n```\n\n") | ||
self._write_to_file("---\n\n") | ||
|
||
def on_agent_action(self, action: AgentAction, **kwargs: Any) -> Any: | ||
self.step_count += 1 | ||
self._write_to_file(f"## Step {self.step_count}: Agent Action\n\n") | ||
self._write_to_file(f"**Timestamp:** {self._get_timestamp()}\n\n") | ||
self._write_to_file(f"**Tool:** {action.tool}\n\n") | ||
self._write_to_file("**Tool Input:**\n\n") | ||
self._write_to_file(f"```\n{action.tool_input}\n```\n\n") | ||
|
||
def on_agent_finish(self, finish: AgentFinish, **kwargs: Any) -> None: | ||
self._write_to_file("## Agent Finish\n\n") | ||
self._write_to_file(f"**Timestamp:** {self._get_timestamp()}\n\n") | ||
self._write_to_file("**Output:**\n\n") | ||
self._write_to_file(f"```\n{finish.return_values}\n```\n\n") | ||
self._write_to_file("---\n\n") | ||
|
||
def _write_to_file(self, text: str) -> None: | ||
self.file.write(text) | ||
self.file.flush() | ||
|
||
def _get_timestamp(self) -> str: | ||
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
import sys | ||
from copy import deepcopy | ||
from typing import Any, Dict, List, Union | ||
|
||
|
||
def get_current_function_name(depth: int = 1) -> str: | ||
return sys._getframe(depth).f_code.co_name | ||
|
||
|
||
def show_callback_info(name: str, tag: str, data: Any) -> None: | ||
current_function_name = get_current_function_name(2) | ||
print("show_callback_info current_function_name=", current_function_name, name) | ||
print(f"{tag}=", trim_data(data)) | ||
|
||
|
||
def trim_data(data: Union[Any, List[Any], Dict[str, Any]]) -> str: | ||
""" | ||
dataの構造をデバッグ表示用に短縮する関数 | ||
:data: 対象データ | ||
""" | ||
data_copy = deepcopy(data) | ||
return trim_data_iter("", data_copy) | ||
|
||
|
||
def trim_data_iter(indent: str, data: Union[Any, List[Any], Dict[str, Any]]) -> str: | ||
""" | ||
dataの構造をデバッグ表示用に短縮する関数 | ||
:param data: 対象データ | ||
""" | ||
indent_next = indent + " " | ||
if isinstance(data, dict): | ||
return trim_data_dict(indent_next, data) | ||
elif isinstance(data, list): | ||
return trim_data_array(indent_next, data) | ||
else: | ||
return trim_data_other(indent, data) | ||
|
||
|
||
def trim_data_dict(indent: str, data: Dict[str, Any]) -> str: | ||
""" | ||
dataの構造をデバッグ表示用に短縮する関数 | ||
:param indent: インデント文字列 | ||
:param data: 対象データ | ||
""" | ||
new_data_list = [] | ||
for k, v in data.items(): | ||
new_data_list.append(f"{indent}dict[{k}]: " + trim_data_iter(indent, v)) | ||
return "\n".join(new_data_list) | ||
|
||
|
||
def trim_data_array(indent: str, data: List[Any]) -> str: | ||
""" | ||
dataの構造をデバッグ表示用に短縮する関数 | ||
:param indent: インデント文字列 | ||
:param data: 対象データ | ||
""" | ||
new_data_list = [] | ||
for i, item in enumerate(data): | ||
print(f"{indent}array[{str(i)}]: ") | ||
new_data_list.append(trim_data_iter(indent, item)) | ||
return "\n".join(new_data_list) | ||
|
||
|
||
def trim_data_other(indent: str, data: Any) -> str: | ||
""" | ||
dataの構造をデバッグ表示用に短縮する関数 | ||
:param indent: インデント文字列 | ||
:param data: 対象データ | ||
""" | ||
stype = str(type(data)) | ||
s = str(data) | ||
return f"{indent}type={stype}, data={s[:80]}" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters