Skip to content

Commit

Permalink
fix: add llm_convert_to_CodeInterpreterIntermediateResult for brain.py
Browse files Browse the repository at this point in the history
  • Loading branch information
nobu007 committed Sep 2, 2024
1 parent 1ce9957 commit c1d2bd9
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 16 deletions.
44 changes: 37 additions & 7 deletions src/codeinterpreterapi/brain/brain.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from langchain_core.prompts import PromptTemplate
import random
import traceback
from typing import Any, Dict, List, Optional, Union
Expand Down Expand Up @@ -164,10 +165,11 @@ def _set_output_llm_result(
elif isinstance(result, CodeInterpreterPlanList):
plan_list: CodeInterpreterPlanList = result
output.context = str(plan_list)
else:
output.context = str(result)
output.log = f"type={type(result)}"
return output

# convert by llm
print(f"brain _set_output_llm_result type(output)={type(output)}")
output = self.llm_convert_to_CodeInterpreterIntermediateResult(output)
return output

def __call__(self, input: Input) -> Output:
Expand Down Expand Up @@ -224,6 +226,36 @@ def use_agent(self, new_agent: AgentName):
print("CodeInterpreterBrain use_agent=", new_agent)
self.current_agent = new_agent

def llm_convert_to_CodeInterpreterIntermediateResult(
self,
output_str: str,
) -> CodeInterpreterIntermediateResult:
prompt_template = """
出力されたoutput_dictの内容をCodeInterpreterIntermediateResultクラスに詰め替えてください。
inputで示された作業目的を考慮して重要な情報から可能な限り詰めてください。
不要な情報や重複する情報はdropしてください。
取得できなかった変数はデフォルト値のままにしてください。
## output_dict(str)
{output_str}
"""

prompt = PromptTemplate(
input_variables=["final_goal", "agent_scratchpad", "crew_output"], template=prompt_template
)

structured_llm = self.ci_params.llm.with_structured_output(
schema=CodeInterpreterIntermediateResult, include_raw=False
)
runnable = prompt | structured_llm

last_input = {}
last_input["output_str"] = output_str
print("llm_convert_to_CodeInterpreterIntermediateResult(brain) last_input=", last_input)
output = runnable.invoke(input=last_input)
print("llm_convert_to_CodeInterpreterIntermediateResult(brain) output=", output)
return output


def test():
settings.WORK_DIR = "/tmp"
Expand All @@ -232,7 +264,7 @@ def test():
brain = CodeInterpreterBrain(ci_params)
is_hard_test = False

if True:
if False:
# try1: agent_executor
print("try1: agent_executor")
brain.use_agent(AgentName.AGENT_EXECUTOR)
Expand All @@ -253,10 +285,8 @@ def test():
}
result = brain.invoke(input_dict)
print("result=", result)
assert "python" == result.tool
assert "test output" in result.tool_input

if False:
if True:
# try3: supervisor
print("try3: supervisor")
sample = "ステップバイステップで2*5+2を計算して。"
Expand Down
14 changes: 8 additions & 6 deletions src/codeinterpreterapi/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,11 +126,13 @@ class CodeInterpreterIntermediateResult(BaseModel):
description="エージェントの思考プロセスを表す文字列のリスト(最新の思考および根拠を理解するために必要な情報のみが入っている)",
)
context: str = Field(description="llmやagentからの回答本文")
code: str = Field(default="", description="プログラムのソースコード")
code: str = Field(
default="", description="プログラムのソースコード(コード自体への説明や不要な改行などを入れないこと)"
)
log: str = Field(default="", description="コードの実行結果やテスト結果などのlog")
language: str = Field(default="", description="llmやagentからの回答本文")
language: str = Field(default="", description="pythonやjavaなどのプログラム言語")
confidence: float = Field(default=0.95, description="現在の回答の信頼度[0.0~1.0], 1.0が最も信頼できる")
target_confidence: float = Field(default=0.95, description="目標とする信頼度")
target_confidence: float = Field(default=0.95, description="処理完了の目標信頼度、これ以上なら完了する")
# metadata: Dict[str, Any] = Field(default_factory=dict, description="追加のメタデータを格納する辞書")
iteration_count: int = Field(default=0, description="現在の反復回数")
max_iterations: int = Field(default=10, description="最大反復回数")
Expand All @@ -140,9 +142,9 @@ def __str__(self) -> str:

def __repr__(self) -> str:
return f"""CodeInterpreterIntermediateResult(
thoughts={self.thoughts},
context={self.context},
code={self.code},
thoughts={self.thoughts}
context={self.context}
code={self.code}
log={self.log}
confidence={self.confidence})"""

Expand Down
6 changes: 3 additions & 3 deletions src/codeinterpreterapi/utils/multi_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def _process_crew_output(input_crew_output: CrewOutput) -> str:
return last_task_output.raw

@staticmethod
def to_CodeInterpreterIntermediateResult(input_dict: Dict) -> CodeInterpreterIntermediateResult:
def to_CodeInterpreterIntermediateResult(input_dict: Dict) -> Union[CodeInterpreterIntermediateResult, str]:
"""汎用的なレスポンス処理(配列には未対応)"""
output = CodeInterpreterIntermediateResult(context="")
is_empty = True
Expand All @@ -93,9 +93,9 @@ def to_CodeInterpreterIntermediateResult(input_dict: Dict) -> CodeInterpreterInt
setattr(output, output_attribute, value)
is_empty = False

# 取れない場合はstr経由で変換する
# 取れない場合はstr経由で返して後で変換する
if is_empty:
output.context = str(input_dict)
return str(input_dict)

return output

Expand Down

0 comments on commit c1d2bd9

Please sign in to comment.