开始使用免费开始使用

向图中添加一个工具

您的 Wikipedia 工具已经就绪。现在该把它接入聊天机器人的图工作流了!您将修改图中的节点和边,把该工具作为一个额外的节点纳入其中。您会设置图,使聊天机器人能根据用户的查询需要,按需调用该工具。为便于管理工具节点及其相关边,我们已为您导入以下模块。您构建的 wikipedia_tool 也可在您的环境中使用。图构建完成后,系统会以 LangGraph 图示的方式为您可视化。

from langgraph.prebuilt import ToolNode, tools_condition

本练习是课程的一部分

使用 LangChain 设计 Agentic 系统

查看课程

练习说明

  • 使用 .add_node()"chatbot" 节点添加到图中,并关联到 chatbot 函数。
  • 使用 wikipedia_tool 作为 tools 创建一个 ToolNode(),并用 .add_node() 将其以 "tools" 的名称添加到图中。
  • 应用 .add_conditional_edges(),基于 tools_condition"chatbot" 进行路由。
  • 使用 .add_edge()"tools" 连回 "chatbot",将 START 连到 "chatbot",并把 "chatbot" 连到 END,以完成工作流。

交互式实操练习

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

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

# Create a ToolNode to handle tool calls and add it to the graph
tool_node = ____(tools=[____])
graph_builder.____("tools", ____)

# Set up a condition to direct from chatbot to tool or END node
graph_builder.____("____", ____)

# Connect tools back to chatbot and connect START and END nodes
graph_builder.add_edge("____", "____")
graph_builder.add_edge(____, "chatbot")
graph_builder.add_edge("chatbot", ____)

graph = graph_builder.compile()

try:
    display(Image(graph.get_graph().draw_mermaid_png()))

except Exception:
    print("Plot generation failed... falling back to cached asset.")
    display_fallback()
编辑并运行代码