読み方のヒント
矢印ボタン(または ← → キー)でページを移動できます。
RAGの練習ファイルの FakeLLM に、chat_with_tools を足しました。tool_replies に入れた返事を、順に返します。
def chat_with_tools(self, messages: list[dict], tools: list[dict]) -> dict:
if self.fail:
raise LLMError("偽のLLMの失敗")
self.calls.append(list(messages))
return self.tool_replies.pop(0)
def tool_call(name: str, **arguments) -> dict:
"""道具を1つ呼ぶ、LLMの返事。"""
return {"role": "assistant", "content": "", "tool_calls": [{"function": {"name": name, "arguments": arguments}}]}
def say(text: str) -> dict:
"""道具を呼ばずに文章で答える、LLMの返事。"""
return {"role": "assistant", "content": text}
calls には、呼ばれたときの messages の写しを残します。テストでは、2回目の呼び出しで、道具の結果が tool のメッセージとして渡されたかを確かめます。
def test_tool_result_goes_back_to_llm(ctx, fake_llm):
fake_llm.tool_replies += [tool_call("find_products", keyword="カレーパン"), say("カレーパンは今日は売り切れです。")]
result = run_agent(fake_llm, ctx, "カレーパンはありますか")
assert result.answer == "カレーパンは今日は売り切れです。"
assert [step.tool for step in result.steps] == ["find_products"]
[products] = tool_messages(fake_llm.calls[1])
assert products["products"][0]["remaining_today"] == 0
偽のLLMが決めるのは、LLMの返事だけです。find_products は本物の関数がテスト用のDBを調べるため、残りの数が0であることは、DBのデータから確かめられます。
20 / 22