为聊天机器人添加外部工具

使用 LangChain 设计 Agentic 系统

Dilini K. Sumanapala, PhD

Founder & AI Engineer, Genverv, Ltd.

用 LangGraph 集成外部工具

  桌面显示器中央有微芯片图案,内写"API"。

     

  • 聊天机器人的 API 工具

     
    • 新闻
    • 数据库
    • 社交媒体
    • 等等
使用 LangChain 设计 Agentic 系统

添加 Wikipedia 工具

人们坐在大书上阅读。

  Wikipedia 图标。

使用 LangChain 设计 Agentic 系统

添加 Wikipedia 工具

# Modules for building a Wikipedia tool
from langchain_community.utilities import WikipediaAPIWrapper
from langchain_community.tools import WikipediaQueryRun


# Initialize Wikipedia API wrapper to fetch top 1 result api_wrapper = WikipediaAPIWrapper(top_k_results=1)
# Create a Wikipedia query tool using the API wrapper wikipedia_tool = WikipediaQueryRun(api_wrapper=api_wrapper)
tools = [wikipedia_tool]
使用 LangChain 设计 Agentic 系统

添加 Wikipedia 工具

# Bind the Wikipedia tool to 
# the language model
llm_with_tools = llm.bind_tools(tools)


# Modify chatbot function to # respond with Wikipedia def chatbot(state: State): return {"messages": [llm_with_tools.invoke( state["messages"])]}

   

  • 绑定工具

 

  • 更新聊天机器人节点

  • 启用 Wikipedia

  • 由 LLM 决定是否调工具

使用 LangChain 设计 Agentic 系统

其他 API 工具

  桌面显示器中央有微芯片图案,内写"API"。

   

使用 LangChain 设计 Agentic 系统

添加工具节点

# Modules for adding tool conditions 
# and nodes
from langgraph.prebuilt import 
ToolNode, tools_condition


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

聊天机器人节点。

使用 LangChain 设计 Agentic 系统

添加工具节点

# Modules for adding tool conditions 
# and nodes
from langgraph.prebuilt import 
ToolNode, tools_condition

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


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

聊天机器人与工具节点。

使用 LangChain 设计 Agentic 系统

添加工具节点

# Set up a condition to direct from chatbot 
# to tool or end node
graph_builder.add_conditional_edges(
             "chatbot", tools_condition)



聊天机器人与 END 和工具节点,以虚线表示条件边连接。

使用 LangChain 设计 Agentic 系统

添加工具节点

# Set up a condition to direct from chatbot 
# to tool or end node
graph_builder.add_conditional_edges(
             "chatbot", tools_condition)



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

完整聊天机器人图:聊天机器人节点连接工具与 END 节点,顶部有 START 节点。

使用 LangChain 设计 Agentic 系统

Passons à la pratique !

使用 LangChain 设计 Agentic 系统

Preparing Video For Download...