エージェント型システムを素早く確実に構築することを支援するように設計された、LangGraph の事前構築済み、再利用可能なコンポーネントをセットアップして使用する方法を示します。
LangGraph : Get started : クイックスタート
作成 : クラスキャット・セールスインフォメーション
作成日時 : 05/20/2025
* 本記事は langchain-ai.github.io の以下のページを独自に翻訳した上でまとめ直し、補足説明を加えています :
* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。
◆ お問合せ : 下記までお願いします。
- クラスキャット セールス・インフォメーション
- sales-info@classcat.com
- ClassCatJP
LangGraph : Get started : クイックスタート
このガイドは、エージェント型システムを素早く確実に構築することを支援するように設計された、LangGraph の事前構築済み、再利用可能なコンポーネントをセットアップして使用する方法を示します。
前提条件
このチュートリアルを始める前に、以下を持っていることを確認してください :
- Anthropic API キー
1. 依存関係のインストール
まだインストールしていないなら、LangGraph と LangChain をインストールしてください :
pip install -U langgraph "langchain[anthropic]"
Note : LangChain is installed so the agent can call the model.
2. エージェントの作成
エージェントを作成するには、create_react_agent を使用します :
API リファレンス: create_react_agent
from langgraph.prebuilt import create_react_agent
# エージェントが使用するツールの定義。ツールは普通の Python 関数として定義できます。
def get_weather(city: str) -> str:
"""Get weather for a given city."""
return f"It's always sunny in {city}!"
# params
# model: エージェントが使用する言語モデル。
# tools: モデルが使用するツールのリスト。
# prompt: エージェントが使用する言語モデルへのシステムプロンプト。
agent = create_react_agent(
model="anthropic:claude-3-7-sonnet-latest",
tools=[get_weather],
prompt="You are a helpful assistant"
)
# エージェントの実行
agent.invoke(
{"messages": [{"role": "user", "content": "what is the weather in sf"}]}
)
3. LLM の設定
temperature のような、特定のパラメータを使用して LLM を設定するには、init_chat_model を使用します :
API リファレンス: init_chat_model | create_react_agent
from langchain.chat_models import init_chat_model
from langgraph.prebuilt import create_react_agent
model = init_chat_model(
"anthropic:claude-3-7-sonnet-latest",
temperature=0
)
agent = create_react_agent(
model=model,
tools=[get_weather],
)
For more information on how to configure LLMs, see Models.
4. カスタムプロンプトの追加
プロンプトは LLM に動作する方法を指示します。プロンプトの以下のタイプの一つを追加します :
- Static : 文字列はシステムメッセージとして解釈されます。
- Dynamic : 入力や設定に基づいて、実行時に生成されるメッセージのリスト。
静的プロンプト
固定プロンプト文字列やメッセージのリストを定義します :
from langgraph.prebuilt import create_react_agent
agent = create_react_agent(
model="anthropic:claude-3-7-sonnet-latest",
tools=[get_weather],
# A static prompt that never changes
prompt="Never answer questions about the weather."
)
agent.invoke(
{"messages": [{"role": "user", "content": "what is the weather in sf"}]}
)
動的プロンプト
エージェントの状態と設定に基づいて、メッセージ・リストを返す関数を定義します :
from langchain_core.messages import AnyMessage
from langchain_core.runnables import RunnableConfig
from langgraph.prebuilt.chat_agent_executor import AgentState
from langgraph.prebuilt import create_react_agent
def prompt(state: AgentState, config: RunnableConfig) -> list[AnyMessage]:
user_name = config["configurable"].get("user_name")
system_msg = f"You are a helpful assistant. Address the user as {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(
{"messages": [{"role": "user", "content": "what is the weather in sf"}]},
config={"configurable": {"user_name": "John Smith"}}
)
For more information, see Context.
5. メモリの追加
エージェントとの複数ターンの会話を可能にするには、エージェントを作成するときにチェックポインターを提供することで永続性 (persistence) を有効にする必要があります。実行時には、thread_id – 会話 (セッション) 用の一意な識別子 – を含む config を提供する必要があります :
API リファレンス: create_react_agent | InMemorySaver
from langgraph.prebuilt import create_react_agent
from langgraph.checkpoint.memory import InMemorySaver
checkpointer = InMemorySaver()
# params
# checkpointer: チェックポインターは、エージェントがツール呼び出しループのステップ毎の状態をストアすることを可能にします。
# これは短期メモリと人間参加型 (human-in-the-loop) 機能を可能にします。
agent = create_react_agent(
model="anthropic:claude-3-7-sonnet-latest",
tools=[get_weather],
checkpointer=checkpointer
)
# エージェントの実行
config = {"configurable": {"thread_id": "1"}}
# params
# config: 将来的なエージェント呼び出しで同じ会話を再開できるように、thread_id を含む configuration を渡します。
sf_response = agent.invoke(
{"messages": [{"role": "user", "content": "what is the weather in sf"}]},
config
)
ny_response = agent.invoke(
{"messages": [{"role": "user", "content": "what about new york?"}]},
config
)
チェックポインターを有効にすると、それは提供されたチェックポインター・データベース (or InMemorySaver を使用している場合はメモリ) にステップ毎にエージェントの状態をストアします。
上記の例では、エージェントが同じ thread_id で 2 度目に呼び出されると、最初の会話からの元のメッセージ履歴が、新しいユーザ入力とともに自動的に含まれることに注意してください。
For more information, see Memory.
6. 構造化出力の設定
スキーマに準拠した構造化レスポンスを生成するには、response_format パラメータを使用します。スキーマは Pydantic モデルか TypedDict を使用して定義できます。結果は structured_response フィールド経由でアクセスできます。
API リファレンス: create_react_agent
from pydantic import BaseModel
from langgraph.prebuilt import create_react_agent
class WeatherResponse(BaseModel):
conditions: str
# params
# response_format: response_format が指定されている場合、エージェントループの最後に separate ステップが追加されます :
# エージェントメッセージ履歴が構造化出力とともに LLM に渡されて構造化レスポンスを生成します。
# システムプロンプトをこの LLM に提供するには、タプル (prompt, schema), e.g., response_format=(prompt, WeatherResponse) を使用します。
agent = create_react_agent(
model="anthropic:claude-3-7-sonnet-latest",
tools=[get_weather],
response_format=WeatherResponse
)
response = agent.invoke(
{"messages": [{"role": "user", "content": "what is the weather in sf"}]}
)
response["structured_response"]
Note : LLM post-processing : Structured output requires an additional call to the LLM to format the response according to the schema.
以上