单纯从消息交互的角度来看待Agent中的model节点,可以看出它旨在利用AIMessage提供两种类型的响应:
- 在需要调用一个或者多个工具情况下,利用
ToolCall返回针对工具调用意图的描述; - 做出最终的答复。
我们可以利用一个假的模型组件来验证这一点。在前面演示的实例中,我们使用的是ChatOpenAI作为Agent的模型组件,接下来我们将它替换成如下这个FakeModel。它继承自BaseChatModel,并且实现了和重写了三个必要的成员(关于BaseChatModel的详细介绍,可以参考我的文章“Completion模型和Chat模型”)。
from typing import Any,Callable, Sequence, override
import builtins
from langchain.agents import create_agent
from langchain_core.language_models import BaseChatModel,LanguageModelInput
from langchain_core.messages import BaseMessage, AIMessage, HumanMessage, ToolMessage, ToolCall
from langchain_core.callbacks import CallbackManagerForLLMRun
from langchain_core.outputs.chat_result import ChatResult, ChatGeneration
from langchain_core.tools import BaseTool
from langchain_core.runnables import Runnable
class FakeModel(BaseChatModel):
def _generate(
self,
messages: list[BaseMessage],
stop: list[str] | None = None,
run_manager: CallbackManagerForLLMRun | None = None,
**kwargs: Any,
) -> ChatResult:
if[message for message in messages if isinstance(message, ToolMessage)]:
generation = ChatGeneration(message=AIMessage("It's sunny in Suzhou right now!"))
return ChatResult(generations=[generation], llm_output={})
tool_call: ToolCall = {
"name": "get_weather",
"args": {"city": "Suzhou"},
"id": "tool_call_001",
}
ai_message = AIMessage(content="", tool_calls=[tool_call])
generation = ChatGeneration(message=ai_message)
return ChatResult(generations=[generation], llm_output={})
@property
def _llm_type(self) -> str:
return "fake"
@override
def bind_tools(
self,
tools: Sequence[builtins.dict[str, Any] | type | Callable | BaseTool],
*,
tool_choice: str | None = None,
**kwargs: Any,
) -> Runnable[LanguageModelInput, AIMessage]:
return self
def get_weather(city: str) -> str:
"""Get weather for a given city."""
return f"It's always sunny in {city}!"
agent = create_agent(
model= FakeModel(),
tools=[get_weather],
system_prompt="You are a helpful assistant",
)
message = HumanMessage(content="What is the weather like in Suzhou?")
result = agent.invoke(input= {"messages": [message]})
for message in result["messages"]:
message.pretty_print()
实现的_llm_type属性旨在返回语言模型的类型。当我们指定工具创建Agent的时候,工具列表会通过调用bind_tools方法绑定到模型上,所以我们需要重写此方法。FakeModel自然没有推理能力,它实现的_generate方法只能按照假定的流程生成返回的ChatResult对象:
- 对于第一次调用,它将创建一个
TooCall对象来描述针对get_weather工具的调用,并封装到返回的AIMessage中,最终利用此消息生成ChatGeneration对象创建返回的ChatResult。 - 对于第二次调用(最后一条消息为
ToolMessage),生成的AIMessage直接包含最终的答复。
我们调用Agent的invoke方法,并从结果中提取消息历史,依然可以得到与前面实例类似的结果。
================================ Human Message =================================
What is the weather like in Suzhou?
================================== Ai Message ==================================
Tool Calls:
get_weather (tool_call_001)
Call ID: tool_call_001
Args:
city: Suzhou
================================= Tool Message =================================
Name: get_weather
It's always sunny in Suzhou!
================================== Ai Message ==================================
It's sunny in Suzhou right now!
1647

被折叠的 条评论
为什么被折叠?



