LangGraph は、ステートフルな LLM アプリケーションを構築するためのフレームワークであり、ReAct(Reasoning and Acting)エージェントの構築に適しています。
ReAct エージェントは、LLM の推論とアクションの実行を組み合わせます。ユーザーの目標を達成するために、観察に基づいて反復的に考え、ツールを使用し、行動し、アプローチを動的に適応させます。「ReAct: Synergizing Reasoning and Acting in Language Models」(2023 年)で導入されたこのパターンは、厳格なワークフローに代わる、人間のような柔軟な問題解決を模倣しようとしています。
LangGraph にはビルド済みの ReAct エージェント(create_react_agent
)が用意されていますが、ReAct の実装をより細かく制御してカスタマイズする必要がある場合に適しています。
LangGraph は、次の 3 つの主要コンポーネントを使用してエージェントをグラフとしてモデル化します。
State
: アプリの現在のスナップショットを表す共有データ構造(通常はTypedDict
またはPydantic BaseModel
)。Nodes
: エージェントのロジックをエンコードします。現在の状態を入力として受け取り、計算や副作用を実行して、更新された状態(LLM 呼び出しやツール呼び出しなど)を返します。Edges
: 現在のState
に基づいて実行する次のNode
を定義します。これにより、条件付きロジックと固定遷移が可能になります。
API キーをまだお持ちでない場合は、Google AI Studio で無料で取得できます。
pip install langgraph langchain-google-genai geopy requests
環境変数 GEMINI_API_KEY
に API キーを設定します。
import os
# Read your API key from the environment variable or set it manually
api_key = os.getenv("GEMINI_API_KEY")
LangGraph を使用して ReAct エージェントを実装する方法について詳しく理解するには、実例を説明します。ツールを使用して指定した場所の現在の天気を調べることを目的としたシンプルなエージェントを作成します。
この天気エージェントの場合、State
は、進行中の会話履歴(メッセージのリストとして)と、状態管理をさらに明確にするために実行されたステップ数のカウンタを保持する必要があります。
LangGraph には、状態内のメッセージリストを更新するための便利なヘルパー関数 add_messages
が用意されています。これはリデューサーとして機能します。つまり、現在のリストと新しいメッセージを受け取り、結合されたリストを返します。メッセージ ID による更新をスマートに処理し、新しい一意のメッセージに対してはデフォルトで「追加のみ」の動作になります。
from typing import Annotated,Sequence, TypedDict
from langchain_core.messages import BaseMessage
from langgraph.graph.message import add_messages # helper function to add messages to the state
class AgentState(TypedDict):
"""The state of the agent."""
messages: Annotated[Sequence[BaseMessage], add_messages]
number_of_steps: int
次に、天気ツールを定義します。
from langchain_core.tools import tool
from geopy.geocoders import Nominatim
from pydantic import BaseModel, Field
import requests
geolocator = Nominatim(user_agent="weather-app")
class SearchInput(BaseModel):
location:str = Field(description="The city and state, e.g., San Francisco")
date:str = Field(description="the forecasting date for when to get the weather format (yyyy-mm-dd)")
@tool("get_weather_forecast", args_schema=SearchInput, return_direct=True)
def get_weather_forecast(location: str, date: str):
"""Retrieves the weather using Open-Meteo API for a given location (city) and a date (yyyy-mm-dd). Returns a list dictionary with the time and temperature for each hour."""
location = geolocator.geocode(location)
if location:
try:
response = requests.get(f"https://api.open-meteo.com/v1/forecast?latitude={location.latitude}&longitude={location.longitude}&hourly=temperature_2m&start_date={date}&end_date={date}")
data = response.json()
return {time: temp for time, temp in zip(data["hourly"]["time"], data["hourly"]["temperature_2m"])}
except Exception as e:
return {"error": str(e)}
else:
return {"error": "Location not found"}
tools = [get_weather_forecast]
次に、モデルを初期化して、ツールをモデルにバインドします。
from datetime import datetime
from langchain_google_genai import ChatGoogleGenerativeAI
# Create LLM class
llm = ChatGoogleGenerativeAI(
model= "gemini-2.5-pro-preview-06-05",
temperature=1.0,
max_retries=2,
google_api_key=api_key,
)
# Bind tools to the model
model = llm.bind_tools([get_weather_forecast])
# Test the model with tools
res=model.invoke(f"What is the weather in Berlin on {datetime.today()}?")
print(res)
エージェントを実行する前の最後のステップは、ノードとエッジを定義することです。この例では、2 つのノードと 1 つのエッジがあります。- ツールメソッドを実行する call_tool
ノード。LangGraph には、このための ToolNode という事前ビルド済みノードがあります。- model_with_tools
を使用してモデルを呼び出す call_model
ノード。- ツールとモデルのどちらを呼び出すかを決定する should_continue
エッジ。
ノードとエッジの数は固定されていません。グラフには、ノードをいくつでもエッジをいくつでも追加できます。たとえば、ツールまたはモデルを呼び出す前に、構造化出力を追加するノードを追加したり、自己検証/リフレクション ノードを追加してモデル出力をチェックしたりできます。
from langchain_core.messages import ToolMessage
from langchain_core.runnables import RunnableConfig
tools_by_name = {tool.name: tool for tool in tools}
# Define our tool node
def call_tool(state: AgentState):
outputs = []
# Iterate over the tool calls in the last message
for tool_call in state["messages"][-1].tool_calls:
# Get the tool by name
tool_result = tools_by_name[tool_call["name"]].invoke(tool_call["args"])
outputs.append(
ToolMessage(
content=tool_result,
name=tool_call["name"],
tool_call_id=tool_call["id"],
)
)
return {"messages": outputs}
def call_model(
state: AgentState,
config: RunnableConfig,
):
# Invoke the model with the system prompt and the messages
response = model.invoke(state["messages"], config)
# We return a list, because this will get added to the existing messages state using the add_messages reducer
return {"messages": [response]}
# Define the conditional edge that determines whether to continue or not
def should_continue(state: AgentState):
messages = state["messages"]
# If the last message is not a tool call, then we finish
if not messages[-1].tool_calls:
return "end"
# default to continue
return "continue"
これで、エージェントを構築するためのすべてのコンポーネントが揃いました。これらを組み合わせてみましょう。
from langgraph.graph import StateGraph, END
# Define a new graph with our state
workflow = StateGraph(AgentState)
# 1. Add our nodes
workflow.add_node("llm", call_model)
workflow.add_node("tools", call_tool)
# 2. Set the entrypoint as `agent`, this is the first node called
workflow.set_entry_point("llm")
# 3. Add a conditional edge after the `llm` node is called.
workflow.add_conditional_edges(
# Edge is used after the `llm` node is called.
"llm",
# The function that will determine which node is called next.
should_continue,
# Mapping for where to go next, keys are strings from the function return, and the values are other nodes.
# END is a special node marking that the graph is finish.
{
# If `tools`, then we call the tool node.
"continue": "tools",
# Otherwise we finish.
"end": END,
},
)
# 4. Add a normal edge after `tools` is called, `llm` node is called next.
workflow.add_edge("tools", "llm")
# Now we can compile and visualize our graph
graph = workflow.compile()
グラフは draw_mermaid_png
メソッドを使用して可視化できます。
from IPython.display import Image, display
display(Image(graph.get_graph().draw_mermaid_png()))
次に、エージェントを実行します。
from datetime import datetime
# Create our initial message dictionary
inputs = {"messages": [("user", f"What is the weather in Berlin on {datetime.today()}?")]}
# call our graph with streaming to see the steps
for state in graph.stream(inputs, stream_mode="values"):
last_message = state["messages"][-1]
last_message.pretty_print()
会話を続け、別の都市の天気を尋ねたり、天気を比較したりできます。
state["messages"].append(("user", "Would it be in Munich warmer?"))
for state in graph.stream(state, stream_mode="values"):
last_message = state["messages"][-1]
last_message.pretty_print()