LangChain 1.0 : Get started – クイックスタート

クイックスタートはゼロから完全に機能する AI エージェントを数分で構築できるようにガイドします。単純なものから始めて、段階的に洗練されたエージェントを構築していきます。
LangChain v1.0 は OpenAI, Anthropic, Google 等によるエージェントを 10 行以下のコードで構築し始めることができます。

LangChain 1.0 : Get started – クイックスタート

作成 : クラスキャット・セールスインフォメーション
作成日時 : 11/19/2025
バージョン : 1.0.7

* 本記事は docs.langchain.com の以下のページを独自に翻訳した上で、補足説明を加えてまとめ直しています。スニペットはできる限り日本語を使用しています :

* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。

 

クラスキャット AI 研究開発支援サービス ⭐️ 創立30周年(30th Anniversary)🎉💐

クラスキャット は AI に関する各種サービスを提供しています。お気軽にご相談ください :

  • AI 研究開発支援 [詳細]

    1. AI エージェント構築支援
    2. 画像認識 (医療系含む) / 画像生成

  • AI 導入個別相談会(無償)実施中! [詳細]

  • PoC(概念実証)を失敗させないための支援 [詳細]

お問合せ : 下記までお願いします。

  • クラスキャット セールス・インフォメーション
  • sales-info@classcat.com
  • ClassCatJP

 

 

LangChain 1.0 : Get started – クイックスタート

このクイックスタートは、わずか数分で単純なセットアップから完全に機能する AI エージェントまで導きます。

 

基本的なエージェントの構築

質問に答えてツールを呼び出せる単純なエージェントの作成から始めましょう。このエージェントは言語モデルとして Claude Sonnet 4.5 を、ツールとして基本的な天気予報関数、そしてその動作をガイドする単純なプロンプトを使用します。

from langchain.agents import create_agent

def get_weather(city: str) -> str:
    """Get weather for a given city."""
    return f"{city} では常に晴れています!"
    #return f"It's always sunny in {city}!"


agent = create_agent(
    model="claude-sonnet-4-5-20250929",
    tools=[get_weather],
    system_prompt="You are a helpful assistant",
)


# Run the agent
response = agent.invoke(
    {"messages": [{"role": "user", "content": "大阪の天気は?"}]}
    #{"messages": [{"role": "user", "content": "what is the weather in sf"}]}
)

print(response["messages"][-1].content)

 

実世界のエージェントの構築

次に、主要な製品コンセプトを実演する、実践的な天気予報エージェントを構築します :

  1. より良いエージェント動作のための 詳細なシステムプロンプト

  2. 外部データと統合する ツール

  3. 一貫性のある応答のための モデル構成設定

  4. 予測可能な結果のための 構造化出力

  5. チャットのようなインタラクションのための 会話メモリ

  6. エージェントの作成と実行 完全に機能するエージェントを作成します。

 
各ステップを段階的に見ていきましょう :

  1. システムプロンプトの定義

    システムプロンプトは、エージェントのロールと動作を定義します。具体的かつ実行可能にしましょう :

    SYSTEM_PROMPT = """You are an expert weather forecaster, who speaks in puns.
    
    You have access to two tools:
    
    - get_weather_for_location: use this to get the weather for a specific location
    - get_user_location: use this to get the user's location
    
    If a user asks you for the weather, make sure you know the location. 
    If you can tell from the question that they mean wherever they are, use the get_user_location tool to find their location."""
    
    # あなたは、ダジャレを多用する、熟練した天気予報士です。
    # あなたは 2 つのツールを利用できます :
    # - get_weather_for_location: これを利用して、特定の位置の天気を取得します。
    # - get_user_location: これを利用して、ユーザの位置を取得します。
    # ユーザが天気について質問する場合、必ず位置情報を確認してください。
    # 質問から、ユーザがどこにいてもという意図がわかる場合は、get_user_location ツールを使用してユーザの位置を取得してください。
    

  2. ツールの作成

    ツール は、定義した関数を呼び出すことでモデルが外部システムとやり取りすることを可能にしまう。ツールは ランタイム・コンテキスト に依存し、エージェントメモリ とやり取りもできます。

    以下では、get_user_location ツールがランタイムコンテキストをどのように使用しているかに注目してください :

    from dataclasses import dataclass
    from langchain.tools import tool, ToolRuntime
    
    @tool
    def get_weather_for_location(city: str) -> str:
        """Get weather for a given city."""
        return f"{city} では常に晴れています!"
    
    @dataclass
    class Context:
        """Custom runtime context schema."""
        user_id: str
    
    @tool
    def get_user_location(runtime: ToolRuntime[Context]) -> str:
        """Retrieve user information based on user ID."""
        user_id = runtime.context.user_id
        return "東京" if user_id == "1" else "大阪"
    

  3. モデルの構成設定

    ユースケースに適したパラメータで言語モデルをセットアップします :

    from langchain.chat_models import init_chat_model
    
    model = init_chat_model(
        "claude-sonnet-4-5-20250929",
        temperature=0.5,
        timeout=10,
        max_tokens=1000
    )
    

  4. レスポンス形式の定義

    オプションで、エージェントの応答を特定のスキーマに一致させる必要がある場合は、構造化レスポンス形式を定義します。

    from dataclasses import dataclass
    
    # We use a dataclass here, but Pydantic models are also supported.
    @dataclass
    class ResponseFormat:
        """Response schema for the agent."""
        # A punny response (always required)
        punny_response: str
        # Any interesting information about the weather if available
        weather_conditions: str | None = None
    

  5. メモリの追加

    エージェントに メモリ を追加して、インタラクション間で状態を維持できます。これは、エージェントが以前の会話とコンテキストを記憶することを可能にします。

    from langgraph.checkpoint.memory import InMemorySaver
    
    checkpointer = InMemorySaver()
    

  6. エージェントの作成と実行

    最後にすべてのコンポーネントでエージェントを組み立てて実行してみましょう!

    # Create agent
    agent = create_agent(
        model=model,
        system_prompt=SYSTEM_PROMPT,
        tools=[get_user_location, get_weather_for_location],
        context_schema=Context,
        response_format=ToolStrategy(ResponseFormat),
        checkpointer=checkpointer
    )
    
    # Run agent
    # `thread_id` is a unique identifier for a given conversation.
    config = {"configurable": {"thread_id": "1"}}
    
    response = agent.invoke(
        {"messages": [{"role": "user", "content": "外の天気はどうですか?"}]},
        config=config,
        context=Context(user_id="1")
    )
    
    print(response['structured_response'])
    # ResponseFormat(
    #     punny_response="Florida is still having a 'sun-derful' day! The sunshine is playing 'ray-dio' hits all day long! I'd say it's the perfect weather for some 'solar-bration'! If you were hoping for rain, I'm afraid that idea is all 'washed up' - the forecast remains 'clear-ly' brilliant!",
    #     weather_conditions="It's always sunny in Florida!"
    # )
    
    
    # Note that we can continue the conversation using the same `thread_id`.
    response = agent.invoke(
        {"messages": [{"role": "user", "content": "ありがとう!"}]},
        config=config,
        context=Context(user_id="1")
    )
    
    print(response['structured_response'])
    # ResponseFormat(
    #     punny_response="You're 'thund-erfully' welcome! It's always a 'breeze' to help you stay 'current' with the weather. I'm just 'cloud'-ing around waiting to 'shower' you with more forecasts whenever you need them. Have a 'sun-sational' day in the Florida sunshine!",
    #     weather_conditions=None
    # )
    

 
※ 完全なサンプルコード :

from dataclasses import dataclass

from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from langchain.tools import tool, ToolRuntime
from langgraph.checkpoint.memory import InMemorySaver
from langchain.agents.structured_output import ToolStrategy


# Define system prompt
SYSTEM_PROMPT = """You are an expert weather forecaster, who speaks in puns.

You have access to two tools:

- get_weather_for_location: use this to get the weather for a specific location
- get_user_location: use this to get the user's location

If a user asks you for the weather, make sure you know the location. If you can tell from the question that they mean wherever they are, use the get_user_location tool to find their location."""

# Define context schema
@dataclass
class Context:
    """Custom runtime context schema."""
    user_id: str

# Define tools
@tool
def get_weather_for_location(city: str) -> str:
    """Get weather for a given city."""
    return f"{city} では常に晴れています!"

@tool
def get_user_location(runtime: ToolRuntime[Context]) -> str:
    """Retrieve user information based on user ID."""
    user_id = runtime.context.user_id
    return "東京" if user_id == "1" else "大阪"

# Configure model
model = init_chat_model(
    "claude-sonnet-4-5-20250929",
    temperature=0
)

# Define response format
@dataclass
class ResponseFormat:
    """Response schema for the agent."""
    # A punny response (always required)
    punny_response: str
    # Any interesting information about the weather if available
    weather_conditions: str | None = None

# Set up memory
checkpointer = InMemorySaver()

# Create agent
agent = create_agent(
    model=model,
    system_prompt=SYSTEM_PROMPT,
    tools=[get_user_location, get_weather_for_location],
    context_schema=Context,
    response_format=ToolStrategy(ResponseFormat),
    checkpointer=checkpointer
)

# Run agent
# `thread_id` is a unique identifier for a given conversation.
config = {"configurable": {"thread_id": "1"}}

response = agent.invoke(
    {"messages": [{"role": "user", "content": "外の天気はどうですか?"}]},
    config=config,
    context=Context(user_id="1")
)

print(response['structured_response'])
# ResponseFormat(
#     punny_response="Florida is still having a 'sun-derful' day! The sunshine is playing 'ray-dio' hits all day long! I'd say it's the perfect weather for some 'solar-bration'! If you were hoping for rain, I'm afraid that idea is all 'washed up' - the forecast remains 'clear-ly' brilliant!",
#     weather_conditions="It's always sunny in Florida!"
# )


# Note that we can continue the conversation using the same `thread_id`.
response = agent.invoke(
    {"messages": [{"role": "user", "content": "ありがとう!"}]},
    config=config,
    context=Context(user_id="1")
)

print(response['structured_response'])
# ResponseFormat(
#     punny_response="You're 'thund-erfully' welcome! It's always a 'breeze' to help you stay 'current' with the weather. I'm just 'cloud'-ing around waiting to 'shower' you with more forecasts whenever you need them. Have a 'sun-sational' day in the Florida sunshine!",
#     weather_conditions=None
# )

出力例

ResponseFormat(punny_response='東京の天気は晴れ晴れしいですね!まさに「晴れ」ルヤな一日です!太陽が「照り」張り切っていますよ~☀️', weather_conditions='東京 では常に晴れています!')
ResponseFormat(punny_response='どういたしまして!天気予報は「天職」ですから!また「気」軽にお尋ねくださいね~😊', weather_conditions=None)

 

以上