チャットボットに外部ツールを追加する

LangChainで設計するエージェント型システム

Dilini K. Sumanapala, PhD

Founder & AI Engineer, Genverv, Ltd.

LangGraph で外部ツールを使う

  中央に「API」と書かれたマイクロチップのグラフィックがあるデスクトップモニター。

     

  • チャットボット向け API ツール

     
    • ニュース
    • データベース
    • ソーシャルメディア
    • など
LangChainで設計するエージェント型システム

Wikipedia ツールを追加する

本の上に座って読書する人々。

  ウィキペディアのアイコン。

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]
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 がツール呼び出しを判断

LangChainで設計するエージェント型システム

他の API ツール

  中央に「API」と書かれたマイクロチップのグラフィックがあるデスクトップモニター。

   

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)

チャットボットノード。

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)

チャットボットとツールのノード。

LangChainで設計するエージェント型システム

ツールノードを追加する

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



条件付きエッジを示す点線で、END とツールのノードに接続されたチャットボット。

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)

上部に START、チャットボットがツールと END に接続された完全な図。

LangChainで設計するエージェント型システム

Passons à la pratique !

LangChainで設計するエージェント型システム

Preparing Video For Download...