[LangChain智能体本质论-02]从消息交互角度审视模型组件在Agent中的作用

Python3.8

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

单纯从消息交互的角度来看待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!

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值