定义一个让聊天机器人停止的函数
现在聊天机器人的状态已经设置好,您需要构建一些函数来管理整个聊天机器人图中的工作流。首先,您将编写一个 should_continue() 函数,用于检查 state 中聊天机器人最后一条消息是否包含工具调用。state 已为您加载好。如果没有工具调用,聊天机器人就会停止。如果调用了工具,聊天机器人将继续执行下一步任务。为管理消息,已为您导入以下模块。
from langgraph.graph import MessagesState, START, END
本练习是课程的一部分
使用 LangChain 设计 Agentic 系统
练习说明
- 使用
MessagesState指定state参数的输入类型。 - 使用
"messages"从state中获取最后一条消息以检查是否有工具调用。 - 检查最后一条消息是否包含
tool_calls,若为真则将返回值指定为"tools"。 - 当不存在
tool_calls时,将返回值指定为END以结束对话。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Use MessagesState to define the state of the function
def should_continue(state: ____):
# Get the last message from the state
last_message = ____["____"][____]
# Check if the last message includes tool calls
if ____.____:
return "____"
# End the conversation if no tool calls are present
return ____