开始使用免费开始使用

添加节点与边

现在您的 StateGraph() 已就绪,是时候把聊天机器人的节点添加到图中了!预构建的 STARTEND 节点直接来自 LangGraph,因此您只需创建一个聊天机器人节点。您还将定义边,以确定从开始到结束的对话走向。添加完节点与边后,编译图以便使用查询来运行它。

本练习是课程的一部分

使用 LangChain 设计 Agentic 系统

查看课程

练习说明

  • 定义 chatbot 函数:对 state 中当前的 "messages" 调用 llm.invoke(),并返回其响应。
  • 使用 .add_node() 向图中添加名为 "chatbot" 的节点,并引用 chatbot 函数。
  • 使用 .add_edge()START 节点连接到 "chatbot" 节点,并将 "chatbot" 连接到 END 节点,以定义对话的边。
  • 使用 .compile() 编译该图,为执行做好准备。

交互式实操练习

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

# Define chatbot function to respond with the model
def chatbot(state: State):
    return {"messages": [llm.____(____["____"])]}

# Add chatbot node to the graph
graph_builder.____("____", ____)

# Define the start and end of the conversation flow
graph_builder.____(____, "____")
graph_builder.____("____", ____)

# Compile the graph to prepare for execution
graph = graph_builder.____()
编辑并运行代码