开始使用免费开始使用

创建一个函数来返回 LLM 响应

您的聊天机器人现在已经集成了许多工具。当问题与已添加的任何工具都无关时,直接调用 LLM 仍然很有用。您现在将定义一个函数,用于检查对话中的最后一条消息是否包含潜在的工具调用。如果没有,聊天机器人将直接使用 LLM 返回答案。为同时处理用户的提问和机器人的回复,以下模块已为您导入,用于处理不同类型的消息。

from langchain_core.messages import AIMessage, HumanMessage

本练习是课程的一部分

使用 LangChain 设计 Agentic 系统

查看课程

练习说明

  • 使用 "messages"state 中获取最后一条消息。
  • 编写条件语句,检查 last_message 是否为 AIMessage,且该消息包含 tool_calls
  • 若条件满足,从 last_messagetool_calls 中取出第一个 "response",并将其放入 AIMessagecontent 字段中返回。
  • 若条件不满足,对 model_with_tools 调用 .invoke() 生成响应,传入来自 state["messages"] 的完整对话历史。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Extract the last message from the history
def call_model(state: MessagesState):
    ____ = ____["____"][____]

    # If the last message has tool calls, return the tool's response
    if isinstance(____, ____) and ____.____:
        
        # Return only the messages from the tool call
        return {"messages": [____(content=____.____[0]["____"])]}
    
    # Otherwise, proceed with a regular LLM response
    return {"messages": [____.____(____["____"])]}
编辑并运行代码