LangGraph 0.5 でドキュメント構成が大幅に変更されましたので、再翻訳しながら Google Colab ベースで動作するようにまとめ直します。モデルは可能な限り最新版を利用し、プロンプトは日本語を使用します。
このガイドは、LangGraph の事前構築済み、再利用可能なコンポーネントをセットアップして使用する方法を示します。
LangGraph 0.5 on Colab : Get started : クイックスタート
作成 : クラスキャット・セールスインフォメーション
作成日時 : 06/28/2025
* 本記事は langchain-ai.github.io の以下のページを独自に翻訳した上でまとめ直し、補足説明を加えています :
* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。
◆ お問合せ : 下記までお願いします。
- クラスキャット セールス・インフォメーション
- sales-info@classcat.com
- ClassCatJP
LangGraph 0.5 on Colab : Get started : クイックスタート
このガイドは、エージェント型システムを素早く確実に構築することを支援するように設計された、LangGraph の 事前構築済み、再利用可能な コンポーネントをセットアップして使用する方法を示します。
前提条件
このチュートリアルを始める前に、以下を持っていることを確認してください :
- Anthropic API キー
1. 依存関係のインストール
まだインストールしていないなら、LangGraph と LangChain をインストールしてください :
%%capture --no-stderr
%pip install -U --quiet langgraph "langchain[anthropic]"
Note : エージェントが モデル を呼び出せるように、LangChain をインストールします。
API キーも設定しておきます :
import getpass
import os
def _set_env(key: str):
if key not in os.environ:
os.environ[key] = getpass.getpass(f"{key}:")
_set_env("ANTHROPIC_API_KEY")
2. エージェントの作成
エージェントを作成するには、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"{city} では常に晴れです!"
# params
# model: エージェントが使用する言語モデル。
# tools: モデルが使用するツールのリスト。
# prompt: エージェントが使用する言語モデルへのシステムプロンプト。
agent = create_react_agent(
model="anthropic:claude-4-sonnet-20250514",
tools=[get_weather],
prompt="You are a helpful assistant"
)
# エージェントの実行
agent.invoke(
{"messages": [{"role": "user", "content": "東京の天気は?"}]}
)
{'messages': [HumanMessage(content='東京の天気は?', additional_kwargs={}, response_metadata={}, id='4f37d388-1a4b-492b-9f56-aaa5f6eaf2e1'), AIMessage(content=[{'text': '東京の天気を調べますね。', 'type': 'text'}, {'id': 'toolu_01PtAmpFrLBrqNqhn4tHMGLv', 'input': {'city': '東京'}, 'name': 'get_weather', 'type': 'tool_use'}], additional_kwargs={}, response_metadata={'id': 'msg_0135UEitNungKJAqrA1PoUzV', 'model': 'claude-sonnet-4-20250514', 'stop_reason': 'tool_use', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 388, 'output_tokens': 67, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-sonnet-4-20250514'}, id='run--d53dccd4-5ccd-4dde-86b5-6153f5f460e2-0', tool_calls=[{'name': 'get_weather', 'args': {'city': '東京'}, 'id': 'toolu_01PtAmpFrLBrqNqhn4tHMGLv', 'type': 'tool_call'}], usage_metadata={'input_tokens': 388, 'output_tokens': 67, 'total_tokens': 455, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}}), ToolMessage(content='東京 では常に晴れです!', name='get_weather', id='3185bef9-2845-4dcf-9c2d-b67dc84a7eb1', tool_call_id='toolu_01PtAmpFrLBrqNqhn4tHMGLv'), AIMessage(content='東京の天気は晴れです!いつも晴れているようですね。', additional_kwargs={}, response_metadata={'id': 'msg_015vqPdzfSkeTmkAF1KLWn7y', 'model': 'claude-sonnet-4-20250514', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 477, 'output_tokens': 25, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-sonnet-4-20250514'}, id='run--f0c58a08-edf8-43be-b59c-05251049a874-0', usage_metadata={'input_tokens': 477, 'output_tokens': 25, 'total_tokens': 502, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}})]}
3. LLM の設定
temperature のような、特定のパラメータを使用して LLM を設定するには、init_chat_model を使用します :
from langgraph.prebuilt import create_react_agent
from langchain.chat_models import init_chat_model
def get_weather(city: str) -> str:
"""Get weather for a given city."""
return f"{city} では今日も雨です!"
model = init_chat_model(
"anthropic:claude-4-sonnet-20250514",
temperature=0
)
agent = create_react_agent(
model=model,
tools=[get_weather],
prompt="You are a helpful assistant"
)
agent.invoke(
{"messages": [{"role": "user", "content": "横浜の天気は?"}]}
)
{'messages': [HumanMessage(content='横浜の天気は?', additional_kwargs={}, response_metadata={}, id='b0938f2f-76b9-49f7-968f-269a31bbe739'), AIMessage(content=[{'text': '横浜の天気をお調べします。', 'type': 'text'}, {'id': 'toolu_01N6WpEcXMBBr7ztkP5Chhyp', 'input': {'city': '横浜'}, 'name': 'get_weather', 'type': 'tool_use'}], additional_kwargs={}, response_metadata={'id': 'msg_017DWUqj3rQh3nYuinwrUYGK', 'model': 'claude-sonnet-4-20250514', 'stop_reason': 'tool_use', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 389, 'output_tokens': 69, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-sonnet-4-20250514'}, id='run--b7ae21b1-d34c-41b8-9124-9803ac1a054b-0', tool_calls=[{'name': 'get_weather', 'args': {'city': '横浜'}, 'id': 'toolu_01N6WpEcXMBBr7ztkP5Chhyp', 'type': 'tool_call'}], usage_metadata={'input_tokens': 389, 'output_tokens': 69, 'total_tokens': 458, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}}), ToolMessage(content='横浜 では今日も雨です!', name='get_weather', id='0ae833cf-c564-4a5e-a809-2c7209a4c6df', tool_call_id='toolu_01N6WpEcXMBBr7ztkP5Chhyp'), AIMessage(content='横浜の天気は雨です。今日も雨が降っているようですね。外出される際は傘をお忘れなく!', additional_kwargs={}, response_metadata={'id': 'msg_0174BJ6n996WvUG2FZDuWb8f', 'model': 'claude-sonnet-4-20250514', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 481, 'output_tokens': 42, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-sonnet-4-20250514'}, id='run--06df4c90-aa87-4367-842a-049ffeed1d52-0', usage_metadata={'input_tokens': 481, 'output_tokens': 42, 'total_tokens': 523, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}})]}
For more information on how to configure LLMs, see Models.
4. カスタムプロンプトの追加
プロンプトは LLM に動作する方法を指示します。以下のタイプのプロンプトの一つを追加します :
- Static (静的) : 文字列はシステムメッセージとして解釈されます。
- Dynamic (動的) : 入力や設定に基づいて、実行時に生成されるメッセージのリスト。
静的プロンプト
固定プロンプト文字列やメッセージのリストを定義します :
agent = create_react_agent(
model="anthropic:claude-4-sonnet-20250514",
tools=[get_weather],
# A static prompt that never changes
prompt="天気についての質問には絶対に答えないでください。"
)
agent.invoke(
{"messages": [{"role": "user", "content": "横浜の天気は?"}]}
)
{'messages': [HumanMessage(content='横浜の天気は?', additional_kwargs={}, response_metadata={}, id='454c03da-c764-4da7-b9e7-bee88dab1b8f'), AIMessage(content='申し訳ございませんが、天気についてのご質問にはお答えできません。他に何かお手伝いできることがございましたら、お気軽にお声かけください。', additional_kwargs={}, response_metadata={'id': 'msg_01EKc95MuejCZTMij6Fqr75z', 'model': 'claude-sonnet-4-20250514', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 401, 'output_tokens': 58, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-sonnet-4-20250514'}, id='run--311ec9a2-88ee-4581-a43f-d845a0d88412-0', usage_metadata={'input_tokens': 401, 'output_tokens': 58, 'total_tokens': 459, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}})]}
動的プロンプト
エージェントの状態と設定に基づいて、メッセージ・リストを返す関数を定義します :
from langchain_core.messages import AnyMessage
from langchain_core.runnables import RunnableConfig
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. Address the user as {user_name}."
return [{"role": "system", "content": system_msg}] + state["messages"]
agent = create_react_agent(
model="anthropic:claude-4-sonnet-20250514",
tools=[get_weather],
prompt=prompt
)
agent.invoke(
{"messages": [{"role": "user", "content": "横浜の天気は?"}]},
config={"configurable": {"user_name": "山田太郎"}}
)
{'messages': [HumanMessage(content='横浜の天気は?', additional_kwargs={}, response_metadata={}, id='b0d4debd-9f47-419a-b6f1-3c7504872bbf'), AIMessage(content=[{'text': '山田太郎さん、横浜の天気をお調べいたします。', 'type': 'text'}, {'id': 'toolu_01NDATmBLFjLMZMPMJrSz9ck', 'input': {'city': '横浜'}, 'name': 'get_weather', 'type': 'tool_use'}], additional_kwargs={}, response_metadata={'id': 'msg_01Sh8i5STA9dhHnbX4xGRLF8', 'model': 'claude-sonnet-4-20250514', 'stop_reason': 'tool_use', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 401, 'output_tokens': 79, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-sonnet-4-20250514'}, id='run--74cb5a15-8c82-468d-a795-b216375b70dd-0', tool_calls=[{'name': 'get_weather', 'args': {'city': '横浜'}, 'id': 'toolu_01NDATmBLFjLMZMPMJrSz9ck', 'type': 'tool_call'}], usage_metadata={'input_tokens': 401, 'output_tokens': 79, 'total_tokens': 480, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}}), ToolMessage(content='横浜 では今日も雨です!', name='get_weather', id='4aee17a8-cd80-49ec-bc73-3bfc6db2aa46', tool_call_id='toolu_01NDATmBLFjLMZMPMJrSz9ck'), AIMessage(content='山田太郎さん、横浜の天気をお調べしました。今日も雨が降っているようですね。外出される際は傘をお忘れなくお持ちください。', additional_kwargs={}, response_metadata={'id': 'msg_01J1bugvaDyvb8LJoKEmkfKj', 'model': 'claude-sonnet-4-20250514', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 503, 'output_tokens': 57, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-sonnet-4-20250514'}, id='run--b64691ef-7203-47db-b3a8-bf2bd9ece49e-0', usage_metadata={'input_tokens': 503, 'output_tokens': 57, 'total_tokens': 560, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}})]}
For more information, see Context.
5. メモリの追加
エージェントとの複数ターンの会話を可能にするには、エージェントを作成するときにチェックポインターを提供することで永続性 (persistence) を有効にする必要があります。実行時には、thread_id – 会話 (セッション) 用の一意な識別子 – を含む config を提供する必要があります :
def get_weather(city: str) -> str:
"""Get weather for a given city."""
return f"{city} は曇りです!"
from langgraph.checkpoint.memory import InMemorySaver
checkpointer = InMemorySaver()
# params
# checkpointer: チェックポインターは、エージェントがツール呼び出しループのステップ毎の状態をストアすることを可能にします。
# これは短期メモリと human-in-the-loop 機能を可能にします。
agent = create_react_agent(
model="anthropic:claude-4-sonnet-20250514",
tools=[get_weather],
checkpointer=checkpointer
)
# エージェントの実行
config = {"configurable": {"thread_id": "1"}}
# params
# config: 将来的なエージェント呼び出しで同じ会話を再開できるように、thread_id を含む configuration を渡します。
tokyo_response = agent.invoke(
{"messages": [{"role": "user", "content": "東京の天気は?"}]},
config
)
osaka_response = agent.invoke(
{"messages": [{"role": "user", "content": "大阪についてはどうでしょう?"}]},
config
)
osaka_response['messages']
[HumanMessage(content='東京の天気は?', additional_kwargs={}, response_metadata={}, id='c6a78d03-4571-47c2-8451-dcc4930d9cc6'), AIMessage(content=[{'text': '東京の天気をお調べします。', 'type': 'text'}, {'id': 'toolu_01XVsBkRy8xd4FST6KNJV287', 'input': {'city': '東京'}, 'name': 'get_weather', 'type': 'tool_use'}], additional_kwargs={}, response_metadata={'id': 'msg_016GFmS3m54y4UtxjrA8B42z', 'model': 'claude-sonnet-4-20250514', 'stop_reason': 'tool_use', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 382, 'output_tokens': 67, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-sonnet-4-20250514'}, id='run--24cc3a05-d622-4a5f-8052-6f7db23f1ed3-0', tool_calls=[{'name': 'get_weather', 'args': {'city': '東京'}, 'id': 'toolu_01XVsBkRy8xd4FST6KNJV287', 'type': 'tool_call'}], usage_metadata={'input_tokens': 382, 'output_tokens': 67, 'total_tokens': 449, 'input_token_details': {'cache_creation': 0, 'cache_read': 0}}), ToolMessage(content='東京 は曇りです!', name='get_weather', id='e2cf6147-1c46-4ecd-8c13-50be0ace6cc4', tool_call_id='toolu_01XVsBkRy8xd4FST6KNJV287'), AIMessage(content='東京の天気は曇りです!', additional_kwargs={}, response_metadata={'id': 'msg_01BfBaaTGXB6ztr5uoNsrdsf', 'model': 'claude-sonnet-4-20250514', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 469, 'output_tokens': 14, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-sonnet-4-20250514'}, id='run--eaeff326-265f-46b0-9300-bef58fef2511-0', usage_metadata={'input_tokens': 469, 'output_tokens': 14, 'total_tokens': 483, 'input_token_details': {'cache_creation': 0, 'cache_read': 0}}), HumanMessage(content='大阪についてはどうでしょう?', additional_kwargs={}, response_metadata={}, id='198fad33-9c9a-4069-bbc7-f5932680e153'), AIMessage(content=[{'text': '大阪の天気もお調べします。', 'type': 'text'}, {'id': 'toolu_01CKARP9sSACfUyWFiBJNvsK', 'input': {'city': '大阪'}, 'name': 'get_weather', 'type': 'tool_use'}], additional_kwargs={}, response_metadata={'id': 'msg_01TrfvQctSBewsHvRRGVrhSK', 'model': 'claude-sonnet-4-20250514', 'stop_reason': 'tool_use', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 500, 'output_tokens': 69, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-sonnet-4-20250514'}, id='run--f77df9f2-3b57-43ec-8711-12c40fc0c057-0', tool_calls=[{'name': 'get_weather', 'args': {'city': '大阪'}, 'id': 'toolu_01CKARP9sSACfUyWFiBJNvsK', 'type': 'tool_call'}], usage_metadata={'input_tokens': 500, 'output_tokens': 69, 'total_tokens': 569, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}}), ToolMessage(content='大阪 は曇りです!', name='get_weather', id='64e0b8a6-f4ea-434c-aa87-d8cf49562cc7', tool_call_id='toolu_01CKARP9sSACfUyWFiBJNvsK'), AIMessage(content='大阪の天気も曇りです!', additional_kwargs={}, response_metadata={'id': 'msg_018aeXYcBD2VYuCAK5wsfaWH', 'model': 'claude-sonnet-4-20250514', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 590, 'output_tokens': 15, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-sonnet-4-20250514'}, id='run--5ea134a8-50d9-4a00-a3c9-b156f4fc50c5-0', usage_metadata={'input_tokens': 590, 'output_tokens': 15, 'total_tokens': 605, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}})]
チェックポインターを有効にすると、それは提供されたチェックポインター・データベース (or InMemorySaver を使用している場合は in memory) にステップ毎にエージェントの状態をストアします。
上記の例では、エージェントが同じ thread_id で 2 度目に呼び出されると、最初の会話からの元のメッセージ履歴が、新しいユーザ入力とともに自動的に含まれることに注意してください。
For more information, see Memory.
6. 構造化出力の設定
スキーマに準拠した構造化レスポンスを生成するには、response_format パラメータを使用します。スキーマは Pydantic モデルか TypedDict を使用して定義できます。結果は structured_response フィールド経由でアクセスできます。
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-4-sonnet-20250514",
tools=[get_weather],
response_format=WeatherResponse
)
response = agent.invoke(
{"messages": [{"role": "user", "content": "東京の天気はどうでしょう?"}]}
)
response["structured_response"]
WeatherResponse(conditions='曇り')
Note : LLM post-processing : Structured output requires an additional call to the LLM to format the response according to the schema.
以上