クイックスタートはゼロから完全に機能する AI エージェントを数分で構築できるようにガイドします。単純なものから始めて、段階的に洗練されたエージェントを構築していきます。
LangChain v1.0 は OpenAI, Anthropic, Google 等によるエージェントを 10 行以下のコードで構築し始めることができます。
LangChain 1.0 alpha : Get started – クイックスタート
作成 : クラスキャット・セールスインフォメーション
作成日時 : 09/20/2025
バージョン : 1.0.0a5
* 本記事は docs.langchain.com の以下のページを独自に翻訳した上で、補足説明を加えてまとめ直しています。スニペットはできる限り日本語を使用しています :
* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。
◆ お問合せ : 下記までお願いします。
- クラスキャット セールス・インフォメーション
- sales-info@classcat.com
- ClassCatJP
LangChain 1.0 alpha : Get started – クイックスタート
クイックスタートはゼロから完全に機能する AI エージェントを数分で構築できるようにガイドします。単純なものから始めて、段階的に洗練されたエージェントを構築していきます。
基本的なエージェントの構築
エージェントの基本から始めましょう – 質問に回答し、ツールを使用できる単純なエージェントを作成します。以下の特徴を持つエージェントを作成します :
- 言語モデル (Claude 3.7 Sonnet)
- 単純なツール (weather 関数)
- 基本的なプロンプト
- メッセージによりそれを呼び出す (invoke) 機能
from langchain.agents import create_agent
def get_weather(city: str) -> str:
"""Get weather for a given city."""
return f"{city} では常に晴れています!"
agent = create_agent(
model="anthropic:claude-3-7-sonnet-latest",
tools=[get_weather],
prompt="You are a helpful assistant",
)
# Run the agent
agent.invoke(
{"messages": [{"role": "user", "content": "大阪の天気は?"}]}
)
実世界のエージェントの構築
それではより実践的なものを作成しましょう。本番環境で使用する主要コンセプトを実演する、天気予報エージェントを構築してみましょう :
- より良いエージェント動作のための 詳細なシステムプロンプト
- 外部データと統合する 実世界のツール
- 一貫性のある応答のための モデル構成設定
- 予測可能な結果のための 構造化出力
- チャットのようなインタラクションのための 会話メモリ
- これらすべてをまとめて完全に機能するエージェントを作成します。
各ステップを段階的に見ていきましょう :
- システムプロンプトの定義
システムプロンプトは、エージェントのパーソナリティと指示です。具体的かつ実行可能にしましょう :
system_prompt = """あなたは、ダジャレを多用する、熟練した天気予報士です。 あなたは 2 つのツールを利用できます : - get_weather_for_location: これを利用して、特定の位置の天気を取得します。 - get_user_location: これを利用して、ユーザの位置を取得します。 ユーザが天気について質問する場合、必ず位置情報を確認してください。質問から、ユーザがどこにいてもという意図とわかる場合は、get_user_location ツールを使用してユーザの位置を特定してください。"""
- ツールの作成
ツール はエージェントが呼び出すことができる関数です。ツールは十分なドキュメント化が必要です。多くの場合、ツールは外部システムへの接続が必要で、そのためにはランタイムの構成設定に依存します。ここで get_user_location ツールが正確にそれを行う方法に注意してください :
from langchain_core.tools import tool def get_weather_for_location(city: str) -> str: # (1)! """Get weather for a given city.""" return f"{city} では常に晴れています!" from langchain_core.runnables import RunnableConfig USER_LOCATION = { "1": "東京", "2": "大阪" } @tool def get_user_location(config: RunnableConfig) -> str: """Retrieve user information based on user ID.""" user_id = config["context"].get("user_id") return USER_LOCATION[user_id]
- モデルの構成設定
ユースケースに適したパラメータで言語モデルをセットアップします :
from langchain.chat_models import init_chat_model model = init_chat_model( "anthropic:claude-3-7-sonnet-latest", temperature=0 )
- レスポンス形式の定義
構造化出力はエージェントが予測できる形式でデータを返すことを保証します。ここでは、Python の DataClass 辞書を使用します。
from dataclasses import dataclass @dataclass class WeatherResponse: conditions: str punny_response: str
- メモリの追加
エージェントが会話履歴を記憶するように有効化します :
from langgraph.checkpoint.memory import InMemorySaver checkpointer = InMemorySaver()
- Bring it all together
最後にすべてのコンポーネントでエージェントを構成しましょう :
agent = create_agent( model=model, prompt=system_prompt, tools=[get_user_location, get_weather_for_location], response_format=WeatherResponse, checkpointer=checkpointer ) config = {"configurable": {"thread_id": "1"}} context = {"user_id": "1"} response = agent.invoke( {"messages": [{"role": "user", "content": "外の天気はどうですか?"}]}, config=config, context=context ) response['structured_response'] response = agent.invoke( {"messages": [{"role": "user", "content": "ありがとう!"}]}, config=config, context=context ) response['structured_response']
※ 参考 (訳註) : 現時点 (1.0.0a5) の上記のコードは config と context の扱いがそのままでは動作しませんので、少し修正を加えて動作するようにしたコードが以下です :
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from langchain_core.tools import tool
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.runtime import get_runtime
from dataclasses import dataclass
# Context schema を定義
@dataclass
class Context:
user_id: str
model = init_chat_model(
"anthropic:claude-3-7-sonnet-latest",
temperature=0
)
system_prompt = """あなたは、ダジャレを多用する、熟練した天気予報士です。
あなたは 2 つのツールを利用できます :
- get_weather_for_location: これを利用して、特定の位置の天気を取得します。
- get_user_location: これを利用して、ユーザの位置を取得します。
ユーザが天気について質問する場合、必ず位置情報を確認してください。
質問から、ユーザがどこにいてもという意図とわかる場合は、get_user_location ツールを使用してユーザの位置を特定してください。
"""
USER_LOCATION = {
"1": "京都",
"2": "大阪"
}
@tool
def get_user_location() -> str:
"""Retrieve user information based on user ID."""
runtime = get_runtime(Context)
user_id = runtime.context.user_id
return USER_LOCATION[user_id]
@tool
def get_weather_for_location(city: str) -> str:
"""Get weather for a given city."""
return f"{city} は常に晴れています!"
@dataclass
class WeatherResponse:
conditions: str
punny_response: str
checkpointer = InMemorySaver()
agent = create_agent(
model=model,
prompt=system_prompt,
tools=[get_user_location, get_weather_for_location],
response_format=WeatherResponse,
checkpointer=checkpointer,
context_schema=Context
)
response = agent.invoke(
{"messages": [{"role": "user", "content": "外の天気はどうですか?"}]},
config={"configurable": {"thread_id": "1"}},
context={"user_id": "1"} # type: ignore
)
print(response['structured_response'])
response = agent.invoke(
{"messages": [{"role": "user", "content": "天気は?"}]},
config={"configurable": {"thread_id": "1"}},
context={"user_id": "2"} # type: ignore
)
print(response['structured_response'])
出力例
WeatherResponse(conditions='晴れ', punny_response='京都は晴れていて、「京(きょう)晴れ(ばれ)」になっていますね!お出かけ日和です!') WeatherResponse(conditions='晴れ', punny_response='大阪は晴れていて、「大阪(おおさか)晴れ(ばれ)」の絶好のお天気です!太陽が「笑い」かけていますよ!')
以上