エージェントが効果的に機能するためにはメッセージのリスト以上のものを必要とする場合が多いです。つまりコンテキストが必要です。コンテキストは、メッセージリスト外の任意のデータを含み、エージェントの動作やツールの実行を形作ることができます。
LangGraph : Prebuilt エージェント : コンテキスト
作成 : クラスキャット・セールスインフォメーション
作成日時 : 06/13/2025
* 本記事は langchain-ai.github.io の以下のページを独自に翻訳した上で、補足説明を加えてまとめ直しています :
* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。
◆ お問合せ : 下記までお願いします。
- クラスキャット セールス・インフォメーション
- sales-info@classcat.com
- ClassCatJP
LangGraph : Get started : Prebuilt エージェント : コンテキスト
エージェントが効果的に機能するためにはメッセージのリスト以上のものを必要とする場合が多いです。コンテキストが必要です。
コンテキストは、メッセージリスト外の任意のデータを含み、エージェントの動作やツールの実行を形作ることができます。これは以下のようなものです :
- user_id や API 認証情報のような、実行時に渡される情報。
- マルチステップの推論過程中に更新される内部状態。
- 以前のインタラクションから得られた永続的メモリかファクト (事実)。
LangGraph はコンテキストを提供するために 3 つ の主要な方法を提供します :
タイプ | 説明 | Mutable? | ライフタイム |
---|---|---|---|
Config | 実行開始時に渡されるデータ | ❌ | 実行毎 (per run) |
State | 実行時に変更可能な動的データ | ✅ | 実行毎か会話毎 |
長期メモリ (Store) | 会話間で共有できるデータ | ✅ | 会話全体 |
以下のためにコンテキストを使用できます :
- モデルが見るシステムプロンプトの調整
- ツールに必要な入力を供給する
- 進行中の会話中にファクトを追跡する
ランタイム・コンテキストの提供
実行時にデータをエージェントに注入する必要がある場合にこれを使用します。
Config (静的コンテキスト)
Config はユーザ・メタデータや API キーのような immutable データ用です。実行中に変化しない値を持つ場合に使用します。
この目的で予約されている “configurable” という名前のキーを使用して設定を指定します :
agent.invoke(
{"messages": [{"role": "user", "content": "hi!"}]},
config={"configurable": {"user_id": "user_123"}}
)
State (mutable コンテキスト)
State は実行中に短期メモリとして機能します。ツールや LLM 出力に由来する値のような、実行中に変化する可能性のある動的データを保持します。
class CustomState(AgentState):
user_name: str
agent = create_react_agent(
# Other agent parameters...
state_schema=CustomState,
)
agent.invoke({
"messages": "hi!",
"user_name": "Jane"
})
長期メモリ (cross-conversation コンテキスト)
会話やセッションにまたがるコンテキストについては、LangGraph は store 経由で 長期メモリ にアクセスすることを可能にします。これは、永続的なファクト (e.g. ユーザ・プロファイル、優先設定、過去のインタラクション) を読み取ったり更新するために使用できます。For more, see the Memory guide.
コンテキストによるプロンプトのカスタマイズ
プロンプトはエージェントが動作する方法を定義します。ランタイム・コンテキストを組み込むには、エージェントのステートや config に基づいてプロンプトを動的に生成できます。
一般的なユースケースは :
- パーソナライゼーション
- ロール (役割) or 目標のカスタマイズ
- 条件付き動作 (e.g., ユーザが管理者)
Using config
from langchain_core.messages import AnyMessage
from langchain_core.runnables import RunnableConfig
from langgraph.prebuilt import create_react_agent
from langgraph.prebuilt.chat_agent_executor import AgentState
def prompt(
state: AgentState,
config: RunnableConfig,
) -> list[AnyMessage]:
user_name = config["configurable"].get("user_name")
system_msg = f"You are a helpful assistant. User's name is {user_name}"
return [{"role": "system", "content": system_msg}] + state["messages"]
agent = create_react_agent(
model="anthropic:claude-3-7-sonnet-latest",
tools=[get_weather],
prompt=prompt
)
agent.invoke(
...,
config={"configurable": {"user_name": "John Smith"}}
)
Using state
from langchain_core.messages import AnyMessage
from langchain_core.runnables import RunnableConfig
from langgraph.prebuilt import create_react_agent
from langgraph.prebuilt.chat_agent_executor import AgentState
class CustomState(AgentState):
user_name: str
def prompt(
state: CustomState
) -> list[AnyMessage]:
user_name = state["user_name"]
system_msg = f"You are a helpful assistant. User's name is {user_name}"
return [{"role": "system", "content": system_msg}] + state["messages"]
agent = create_react_agent(
model="anthropic:claude-3-7-sonnet-latest",
tools=[...],
state_schema=CustomState,
prompt=prompt
)
agent.invoke({
"messages": "hi!",
"user_name": "John Smith"
})
ツールのコンテキストへのアクセス
ツールは特別なパラメータ・アノテーションを通してコンテキストにアクセスできます。
- config へのアクセスには RunnableConfig を使用。
- エージェント状態に対しては Annotated[StateSchema, InjectedState] を使用。
Using config
def get_user_info(
config: RunnableConfig,
) -> str:
"""Look up user info."""
user_id = config["configurable"].get("user_id")
return "User is John Smith" if user_id == "user_123" else "Unknown user"
agent = create_react_agent(
model="anthropic:claude-3-7-sonnet-latest",
tools=[get_user_info],
)
agent.invoke(
{"messages": [{"role": "user", "content": "look up user information"}]},
config={"configurable": {"user_id": "user_123"}}
)
Using state
from typing import Annotated
from langgraph.prebuilt import InjectedState
class CustomState(AgentState):
user_id: str
def get_user_info(
state: Annotated[CustomState, InjectedState]
) -> str:
"""Look up user info."""
user_id = state["user_id"]
return "User is John Smith" if user_id == "user_123" else "Unknown user"
agent = create_react_agent(
model="anthropic:claude-3-7-sonnet-latest",
tools=[get_user_info],
state_schema=CustomState,
)
agent.invoke({
"messages": "look up user information",
"user_id": "user_123"
})
以上