為聊天機器人加入外部工具

Designing Agentic Systems with LangChain

Dilini K. Sumanapala, PhD

Founder & AI Engineer, Genverv, Ltd.

結合 LangGraph 的外部工具

  中央為微晶片圖案,內寫「API」的桌上型螢幕。

     

  • 聊天機器人的 API 工具

     
    • 新聞
    • 資料庫
    • 社群媒體
    • 其他
Designing Agentic Systems with LangChain

加入 Wikipedia 工具

坐在大書本上閱讀的人們。

  Wikipedia 圖示。

Designing Agentic Systems with LangChain

加入 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]
Designing Agentic Systems with LangChain

加入 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 決定呼叫工具

Designing Agentic Systems with LangChain

其他 API 工具

  中央為微晶片圖案,內寫「API」的桌上型螢幕。

   

Designing Agentic Systems with LangChain

加入工具節點

# 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)

聊天機器人節點。

Designing Agentic Systems with LangChain

加入工具節點

# 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)

聊天機器人與工具節點。

Designing Agentic Systems with LangChain

加入工具節點

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



聊天機器人連到 END 與工具節點,以虛線表示條件邊。

Designing Agentic Systems with LangChain

加入工具節點

# 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 節點。

Designing Agentic Systems with LangChain

一起來練習吧!

Designing Agentic Systems with LangChain

Preparing Video For Download...