Skip to content

ClasCat® AI Research

クラスキャット – 生成 AI, AI エージェント, MCP

Menu
  • ホーム
    • ClassCat® AI Research ホーム
    • クラスキャット・ホーム
  • OpenAI API
    • OpenAI Python ライブラリ 1.x : 概要
    • OpenAI ブログ
      • GPT の紹介
      • GPT ストアの紹介
      • ChatGPT Team の紹介
    • OpenAI platform 1.x
      • Get Started : イントロダクション
      • Get Started : クイックスタート (Python)
      • Get Started : クイックスタート (Node.js)
      • Get Started : モデル
      • 機能 : 埋め込み
      • 機能 : 埋め込み (ユースケース)
      • ChatGPT : アクション – イントロダクション
      • ChatGPT : アクション – Getting started
      • ChatGPT : アクション – アクション認証
    • OpenAI ヘルプ : ChatGPT
      • ChatGPTとは何ですか?
      • ChatGPT は真実を語っていますか?
      • GPT の作成
      • GPT FAQ
      • GPT vs アシスタント
      • GPT ビルダー
    • OpenAI ヘルプ : ChatGPT > メモリ
      • FAQ
    • OpenAI ヘルプ : GPT ストア
      • 貴方の GPT をフィーチャーする
    • OpenAI Python ライブラリ 0.27 : 概要
    • OpenAI platform
      • Get Started : イントロダクション
      • Get Started : クイックスタート
      • Get Started : モデル
      • ガイド : GPT モデル
      • ガイド : 画像生成 (DALL·E)
      • ガイド : GPT-3.5 Turbo 対応 微調整
      • ガイド : 微調整 1.イントロダクション
      • ガイド : 微調整 2. データセットの準備 / ケーススタディ
      • ガイド : 埋め込み
      • ガイド : 音声テキスト変換
      • ガイド : モデレーション
      • ChatGPT プラグイン : イントロダクション
    • OpenAI Cookbook
      • 概要
      • API 使用方法 : レート制限の操作
      • API 使用方法 : tiktoken でトークンを数える方法
      • GPT : ChatGPT モデルへの入力をフォーマットする方法
      • GPT : 補完をストリームする方法
      • GPT : 大規模言語モデルを扱う方法
      • 埋め込み : 埋め込みの取得
      • GPT-3 の微調整 : 分類サンプルの微調整
      • DALL-E : DALL·E で 画像を生成して編集する方法
      • DALL·E と Segment Anything で動的マスクを作成する方法
      • Whisper プロンプティング・ガイド
  • Gemini API
    • Tutorials : クイックスタート with Python (1) テキスト-to-テキスト生成
    • (2) マルチモーダル入力 / 日本語チャット
    • (3) 埋め込みの使用
    • (4) 高度なユースケース
    • クイックスタート with Node.js
    • クイックスタート with Dart or Flutter (1) 日本語動作確認
    • Gemma
      • 概要 (README)
      • Tutorials : サンプリング
      • Tutorials : KerasNLP による Getting Started
  • Keras 3
    • 新しいマルチバックエンド Keras
    • Keras 3 について
    • Getting Started : エンジニアのための Keras 入門
    • Google Colab 上のインストールと Stable Diffusion デモ
    • コンピュータビジョン – ゼロからの画像分類
    • コンピュータビジョン – 単純な MNIST convnet
    • コンピュータビジョン – EfficientNet を使用した微調整による画像分類
    • コンピュータビジョン – Vision Transformer による画像分類
    • コンピュータビジョン – 最新の MLPモデルによる画像分類
    • コンピュータビジョン – コンパクトな畳込み Transformer
    • Keras Core
      • Keras Core 0.1
        • 新しいマルチバックエンド Keras (README)
        • Keras for TensorFlow, JAX, & PyTorch
        • 開発者ガイド : Getting started with Keras Core
        • 開発者ガイド : 関数型 API
        • 開発者ガイド : シーケンシャル・モデル
        • 開発者ガイド : サブクラス化で新しい層とモデルを作成する
        • 開発者ガイド : 独自のコールバックを書く
      • Keras Core 0.1.1 & 0.1.2 : リリースノート
      • 開発者ガイド
      • Code examples
      • Keras Stable Diffusion
        • 概要
        • 基本的な使い方 (テキスト-to-画像 / 画像-to-画像変換)
        • 混合精度のパフォーマンス
        • インペインティングの簡易アプリケーション
        • (参考) KerasCV – Stable Diffusion を使用した高性能画像生成
  • TensorFlow
    • TF 2 : 初級チュートリアル
    • TF 2 : 上級チュートリアル
    • TF 2 : ガイド
    • TF 1 : チュートリアル
    • TF 1 : ガイド
  • その他
    • 🦜️🔗 LangChain ドキュメント / ユースケース
    • Stable Diffusion WebUI
      • Google Colab で Stable Diffusion WebUI 入門
      • HuggingFace モデル / VAE の導入
      • LoRA の利用
    • Diffusion Models / 拡散モデル
  • クラスキャット
    • 会社案内
    • お問合せ
    • Facebook
    • ClassCat® Blog
Menu

LangGraph on Colab : マルチエージェント・スーパーバイザー

Posted on 06/25/2025 by Masashi Okumura

LangGraph のグラフを Colab 上で実行してみます。スーパーバイザーは、専門のエージェント群が中心的なスーパーバイザー・エージェントにより調整される、マルチエージェント・アーキテクチャです。スーパーバイザー・エージェントはすべての通信フローとタスク委任を制御し、現在のコンテキストとタスク要件に基づいてどのエージェントを呼び出すか決定します。

LangGraph on Colab : チュートリアル : マルチエージェント・スーパーバイザー

作成 : クラスキャット・セールスインフォメーション
作成日時 : 06/25/2025

* 本記事は langchain-ai.github.io の以下のページを独自に翻訳した上で、補足説明を加えてまとめ直しています :

  • tutorials/multi_agent/agent_supervisor.ipynb – Multi-agent supervisor

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

 

クラスキャット 人工知能 研究開発支援サービス ⭐️ リニューアルしました 😉

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

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

  • 人工知能研究開発支援 [詳細]
    1. 自社特有情報を含むチャットボット構築支援
    2. 画像認識 (医療系含む) / 画像生成

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

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

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

 

 

LangGraph on Colab : チュートリアル : マルチエージェント・スーパーバイザー

スーパーバイザー は、専門のエージェント群 が中心的な スーパーバイザー・エージェント により調整される、マルチエージェント・アーキテクチャです。スーパーバイザー・エージェントはすべての通信フローとタスク委任を制御し、現在のコンテキストとタスク要件に基づいてどのエージェントを呼び出すか決定します。

このチュートリアルでは、研究と数学のエキスパートの 2 つのエージェントを備えたスーパーバイザー・システムを構築します。チュートリアルの最後までに :

  • 専門の研究と数学エージェントを構築する
  • 事前構築済みの langgraph-supervisor により、それらをオーケストレーションするためのスーパーバイザーを構築する
  • スーパーバイザーをゼロから構築する
  • 高度なタスク委任を実装する

 

セットアップ

まず、必要なパッケージをインストールして API キーを設定しましょう。

%%capture --no-stderr
%pip install -U langgraph langgraph-supervisor langchain-tavily "langchain[openai]"
import getpass
import os


def _set_if_undefined(var: str):
    if not os.environ.get(var):
        os.environ[var] = getpass.getpass(f"Please provide your {var}")


_set_if_undefined("OPENAI_API_KEY")
_set_if_undefined("TAVILY_API_KEY")

 

1. ワーカー・エージェントの作成

まず、専門のワーカーエージェント – Research (研究) エージェントと数学エージェントを作成しましょう :

  • Research エージェントは Tavily API を使用して web 検索ツールにアクセスします。
  • 数学エージェントは単純な数学ツール (add, multiply, divide) にアクセスできます。

 

Research エージェント

web 検索については、langchain-tavily からの TavilySearch ツールを使用します :

from langchain_tavily import TavilySearch

web_search = TavilySearch(max_results=3)
web_search_results = web_search.invoke("who is the mayor of NYC?")

print(web_search_results["results"][0]["content"])
Find events, attractions, deals, and more at nyctourism.com Skip Main Navigation Menu The Official Website of the City of New York Text Size Powered by Translate SearchSearch Primary Navigation The official website of NYC Home NYC Resources NYC311 Office of the Mayor Events Connect Jobs Search Office of the Mayor | Mayor's Bio | City of New York Secondary Navigation MayorBiographyNewsOfficials Eric L. Adams 110th Mayor of New York City Mayor Eric Adams has served the people of New York City as an NYPD officer, State Senator, Brooklyn Borough President, and now as the 110th Mayor of the City of New York. Mayor Eric Adams has served the people of New York City as an NYPD officer, State Senator, Brooklyn Borough President, and now as the 110th Mayor of the City of New York. He gave voice to a diverse coalition of working families in all five boroughs and is leading the fight to bring back New York City’s economy, reduce inequality, improve public safety, and build a stronger, healthier city that delivers for all New Yorkers. As the representative of one of the nation’s largest counties, Eric fought tirelessly to grow the local economy, invest in schools, reduce inequality, improve public safety, and advocate for smart policies and better government that delivers for all New Yorkers.

個々のワーカーエージェントを作成するために、LangGraph の事前構築済み エージェント を使用します。

from langgraph.prebuilt import create_react_agent

research_agent = create_react_agent(
    model="openai:gpt-4.1",
    tools=[web_search],
    prompt=(
        "You are a research agent.\n\n"
        "INSTRUCTIONS:\n"
        "- Assist ONLY with research-related tasks, DO NOT do any math\n"
        "- After you're done with your tasks, respond to the supervisor directly\n"
        "- Respond ONLY with the results of your work, do NOT include ANY other text."
    ),
    name="research_agent",
)

エージェントを実行して 期待通りに動作するか検証しましょう。

Note : We’ll use pretty_print_messages helper to render the streamed agent outputs nicely

from langchain_core.messages import convert_to_messages


def pretty_print_message(message, indent=False):
    pretty_message = message.pretty_repr(html=True)
    if not indent:
        print(pretty_message)
        return

    indented = "\n".join("\t" + c for c in pretty_message.split("\n"))
    print(indented)


def pretty_print_messages(update, last_message=False):
    is_subgraph = False
    if isinstance(update, tuple):
        ns, update = update
        # skip parent graph updates in the printouts
        if len(ns) == 0:
            return

        graph_id = ns[-1].split(":")[0]
        print(f"Update from subgraph {graph_id}:")
        print("\n")
        is_subgraph = True

    for node_name, node_update in update.items():
        update_label = f"Update from node {node_name}:"
        if is_subgraph:
            update_label = "\t" + update_label

        print(update_label)
        print("\n")

        messages = convert_to_messages(node_update["messages"])
        if last_message:
            messages = messages[-1:]

        for m in messages:
            pretty_print_message(m, indent=is_subgraph)
        print("\n")
for chunk in research_agent.stream(
    {"messages": [{"role": "user", "content": "who is the mayor of NYC?"}]}
):
    pretty_print_messages(chunk)
Update from node agent:


================================== Ai Message ==================================
Name: research_agent
Tool Calls:
  tavily_search (call_U748rQhQXT36sjhbkYLSXQtJ)
 Call ID: call_U748rQhQXT36sjhbkYLSXQtJ
  Args:
    query: current mayor of New York City
    search_depth: basic


Update from node tools:


================================= Tool Message =================================
Name: tavily_search

{"query": "current mayor of New York City", "follow_up_questions": null, "answer": null, "images": [], "results": [{"title": "List of mayors of New York City - Wikipedia", "url": "https://en.wikipedia.org/wiki/List_of_mayors_of_New_York_City", "content": "The mayor of New York City is the chief executive of the Government of New York City, as stipulated by New York City's charter.The current officeholder, the 110th in the sequence of regular mayors, is Eric Adams, a member of the Democratic Party.. During the Dutch colonial period from 1624 to 1664, New Amsterdam was governed by the Director of New Netherland.", "score": 0.9039154, "raw_content": null}, {"title": "Office of the Mayor | Mayor's Bio | City of New York - NYC.gov", "url": "https://www.nyc.gov/office-of-the-mayor/bio.page", "content": "Mayor Eric Adams has served the people of New York City as an NYPD officer, State Senator, Brooklyn Borough President, and now as the 110th Mayor of the City of New York. He gave voice to a diverse coalition of working families in all five boroughs and is leading the fight to bring back New York City's economy, reduce inequality, improve", "score": 0.8405867, "raw_content": null}, {"title": "Eric Adams - Wikipedia", "url": "https://en.wikipedia.org/wiki/Eric_Adams", "content": "Eric Leroy Adams (born September 1, 1960) is an American politician and former police officer who has served as the 110th mayor of New York City since 2022. Adams was an officer in the New York City Transit Police and then the New York City Police Department (NYPD) for more than 20 years, retiring at the rank of captain.He served in the New York State Senate from 2006 to 2013, representing the", "score": 0.77731717, "raw_content": null}], "response_time": 1.81}


Update from node agent:


================================== Ai Message ==================================
Name: research_agent

The current mayor of New York City is Eric Adams.

 

数学エージェント

数学エージェント・ツールについては、vanilla Python 関数を使用します :

def add(a: float, b: float):
    """Add two numbers."""
    return a + b


def multiply(a: float, b: float):
    """Multiply two numbers."""
    return a * b


def divide(a: float, b: float):
    """Divide two numbers."""
    return a / b


math_agent = create_react_agent(
    model="openai:gpt-4.1",
    tools=[add, multiply, divide],
    prompt=(
        "You are a math agent.\n\n"
        "INSTRUCTIONS:\n"
        "- Assist ONLY with math-related tasks\n"
        "- After you're done with your tasks, respond to the supervisor directly\n"
        "- Respond ONLY with the results of your work, do NOT include ANY other text."
    ),
    name="math_agent",
)

数学エージェントを実行しましょう :

for chunk in math_agent.stream(
    {"messages": [{"role": "user", "content": "what's (3 + 5) x 7"}]}
):
    pretty_print_messages(chunk)
Update from node agent:


================================== Ai Message ==================================
Name: math_agent
Tool Calls:
  add (call_p6OVLDHB4LyCNCxPOZzWR15v)
 Call ID: call_p6OVLDHB4LyCNCxPOZzWR15v
  Args:
    a: 3
    b: 5


Update from node tools:


================================= Tool Message =================================
Name: add

8.0


Update from node agent:


================================== Ai Message ==================================
Name: math_agent
Tool Calls:
  multiply (call_EoaWHMLFZAX4AkajQCtZvbli)
 Call ID: call_EoaWHMLFZAX4AkajQCtZvbli
  Args:
    a: 8
    b: 7


Update from node tools:


================================= Tool Message =================================
Name: multiply

56.0


Update from node agent:


================================== Ai Message ==================================
Name: math_agent

56

 

2. langgraph-supervisor でスーパーバイザーを作成する

マルチエージェント・システムを実装するため、事前構築済み langgraph-supervisor ライブラリから create_supervisor を使用します :

from langgraph_supervisor import create_supervisor
from langchain.chat_models import init_chat_model

supervisor = create_supervisor(
    model=init_chat_model("openai:gpt-4.1"),
    agents=[research_agent, math_agent],
    prompt=(
        "You are a supervisor managing two agents:\n"
        "- a research agent. Assign research-related tasks to this agent\n"
        "- a math agent. Assign math-related tasks to this agent\n"
        "Assign work to one agent at a time, do not call agents in parallel.\n"
        "Do not do any work yourself."
    ),
    add_handoff_back_messages=True,
    output_mode="full_history",
).compile()
from IPython.display import display, Image

display(Image(supervisor.get_graph().draw_mermaid_png()))

 
それでは、両方のエージェントを必要とするクエリーで実行しましょう :

  • research エージェントは必要な GDP 情報を検索します

  • 数学エージェントは、リクエストに応じて NY 州の GDP のパーセンテージを計算するために除算を実行します
for chunk in supervisor.stream(
    {
        "messages": [
            {
                "role": "user",
                "content": "find US and New York state GDP in 2024. what % of US GDP was New York state?",
            }
        ]
    },
):
    pretty_print_messages(chunk, last_message=True)

final_message_history = chunk["supervisor"]["messages"]
Update from node supervisor:


================================= Tool Message =================================
Name: transfer_to_research_agent

Successfully transferred to research_agent


Update from node research_agent:


================================= Tool Message =================================
Name: transfer_back_to_supervisor

Successfully transferred back to supervisor


Update from node supervisor:


================================= Tool Message =================================
Name: transfer_to_math_agent

Successfully transferred to math_agent


Update from node math_agent:


================================= Tool Message =================================
Name: transfer_back_to_supervisor

Successfully transferred back to supervisor


Update from node supervisor:


================================== Ai Message ==================================
Name: supervisor

In 2024, the US GDP was $29.18 trillion and New York State's GDP was $2.297 trillion. New York State accounted for approximately 7.87% of the total US GDP in 2024.

 

3. スーパーバイザーをゼロから作成する

次に、同じマルチエージェント・システムをゼロから実装してみましょう。以下が必要です :

  • スーパーバイザーが個々のエージェントと 通信する 方法をセットアップする

  • スーパーバイザーエージェント の作成

  • スーパーバイザーエージェントとワーカーエージェントを単一のマルチエージェント・グラフに 組み込む

 

エージェント通信のセットアップ

スーパーバイザー・エージェントがワーカー・エージェントと通信する方法を定義する必要があります。マルチエージェント・アーキテクチャでこれを実装する一般的な方法は ハンドオフ を使用することで、そこでは一つのエージェントが制御を別のエージェントにハンドオフします (引き継ぎます)。ハンドオフは以下を指定することが可能です :

  • destination : 転送先 (transfer to) のエージェント

  • payload : そのエージェントに渡す情報

ハンドオフツール 経由でハンドオフを実装し、これらのツールをスーパーバイザー・エージェントに渡します : スーパーバイザーがこれらのツールを呼び出す場合、それは制御をワーカー・エージェントに渡し、完全なメッセージ履歴をそのエージェントに渡します。

from typing import Annotated
from langchain_core.tools import tool, InjectedToolCallId
from langgraph.prebuilt import InjectedState
from langgraph.graph import StateGraph, START, MessagesState
from langgraph.types import Command


def create_handoff_tool(*, agent_name: str, description: str | None = None):
    name = f"transfer_to_{agent_name}"
    description = description or f"Ask {agent_name} for help."

    @tool(name, description=description)
    def handoff_tool(
        state: Annotated[MessagesState, InjectedState],
        tool_call_id: Annotated[str, InjectedToolCallId],
    ) -> Command:
        tool_message = {
            "role": "tool",
            "content": f"Successfully transferred to {agent_name}",
            "name": name,
            "tool_call_id": tool_call_id,
        }
        # highlight-next-line
        return Command(
            # highlight-next-line
            goto=agent_name,  # (1)!
            # highlight-next-line
            update={**state, "messages": state["messages"] + [tool_message]},  # (2)!
            # highlight-next-line
            graph=Command.PARENT,  # (3)!
        )

    return handoff_tool


# Handoffs
assign_to_research_agent = create_handoff_tool(
    agent_name="research_agent",
    description="Assign task to a researcher agent.",
)

assign_to_math_agent = create_handoff_tool(
    agent_name="math_agent",
    description="Assign task to a math agent.",
)

Note

  1. Name of the agent or node to hand off to.
  2. Take the agent’s messages and add them to the parent’s state as part of the handoff. The next agent will see the parent state.
  3. Indicate to LangGraph that we need to navigate to agent node in a parent multi-agent graph.

 

スーパーバイザー・エージェントの作成

次に、先ほど定義したハンドオフ・ツールを備えたスーパーバイザーエージェントを作成しましょう。事前構築済み create_react_agent を使用します :

supervisor_agent = create_react_agent(
    model="openai:gpt-4.1",
    tools=[assign_to_research_agent, assign_to_math_agent],
    prompt=(
        "You are a supervisor managing two agents:\n"
        "- a research agent. Assign research-related tasks to this agent\n"
        "- a math agent. Assign math-related tasks to this agent\n"
        "Assign work to one agent at a time, do not call agents in parallel.\n"
        "Do not do any work yourself."
    ),
    name="supervisor",
)

 

マルチエージェント・グラフの作成

これらすべてをまとめて、マルチエージェント・システム全体のグラフを作成しましょう。スーパーバイザーと個々のエージェントを サブグラフ ノードとして追加します。

from langgraph.graph import END

# Define the multi-agent supervisor graph
supervisor = (
    StateGraph(MessagesState)
    # NOTE: `destinations` is only needed for visualization and doesn't affect runtime behavior
    .add_node(supervisor_agent, destinations=("research_agent", "math_agent", END))
    .add_node(research_agent)
    .add_node(math_agent)
    .add_edge(START, "supervisor")
    # always return back to the supervisor
    .add_edge("research_agent", "supervisor")
    .add_edge("math_agent", "supervisor")
    .compile()
)

ワーカーエージェントからスーパバイザーへの明示的な エッジ を追加したことに注意してください – これは、制御をスーパーバイザーに返すことが保証されていることを意味します。エージェントがユーザに直接応答することを望む場合 (i.e., システムをルーターにしたい場合)、これらのエッジを削除できます。

from IPython.display import display, Image

display(Image(supervisor.get_graph().draw_mermaid_png()))

With the multi-agent graph created, let’s now run it!

for chunk in supervisor.stream(
    {
        "messages": [
            {
                "role": "user",
                "content": "find US and New York state GDP in 2024. what % of US GDP was New York state?",
            }
        ]
    },
):
    pretty_print_messages(chunk, last_message=True)

final_message_history = chunk["supervisor"]["messages"]
Update from node supervisor:


================================= Tool Message =================================
Name: transfer_to_research_agent

Successfully transferred to research_agent


Update from node research_agent:


================================== Ai Message ==================================
Name: research_agent

- US GDP in 2024 is projected to be about $28.18 trillion USD (Statista; CBO projection).
- New York State's nominal GDP for 2024 is estimated at approximately $2.16 trillion USD (various economic reports).
- New York State's share of US GDP in 2024 is roughly 7.7%.

Sources:
- https://www.statista.com/statistics/216985/forecast-of-us-gross-domestic-product/
- https://nyassembly.gov/Reports/WAM/2025economic_revenue/2025_report.pdf?v=1740533306


Update from node supervisor:


================================= Tool Message =================================
Name: transfer_to_math_agent

Successfully transferred to math_agent


Update from node math_agent:


================================== Ai Message ==================================
Name: math_agent

US GDP in 2024: $28.18 trillion
New York State GDP in 2024: $2.16 trillion
Percentage of US GDP from New York State: 7.67%


Update from node supervisor:


================================== Ai Message ==================================
Name: supervisor

Here are your results:

- 2024 US GDP (projected): $28.18 trillion USD
- 2024 New York State GDP (estimated): $2.16 trillion USD
- New York State's share of US GDP: approximately 7.7%

If you need the calculation steps or sources, let me know!

Let’s examine the full resulting message history:

for message in final_message_history:
    message.pretty_print()
================================ Human Message =================================

find US and New York state GDP in 2024. what % of US GDP was New York state?
================================== Ai Message ==================================
Name: supervisor
Tool Calls:
  transfer_to_research_agent (call_qxk9abrxWYQT6a9hPNpXiuM0)
 Call ID: call_qxk9abrxWYQT6a9hPNpXiuM0
  Args:
================================= Tool Message =================================
Name: transfer_to_research_agent

Successfully transferred to research_agent
================================== Ai Message ==================================
Name: research_agent
Tool Calls:
  tavily_search (call_A3cVm1BXDD8dYv6uLwO132gg)
 Call ID: call_A3cVm1BXDD8dYv6uLwO132gg
  Args:
    query: US GDP 2024
    search_depth: advanced
  tavily_search (call_77JyoUYwGDXlRNKOwvQFUUYJ)
 Call ID: call_77JyoUYwGDXlRNKOwvQFUUYJ
  Args:
    query: New York state GDP 2024
    search_depth: advanced
================================= Tool Message =================================
Name: tavily_search

{"query": "US GDP 2024", "follow_up_questions": null, "answer": null, "images": [], "results": [{"url": "https://tradingeconomics.com/united-states/gdp-growth", "title": "United States GDP Growth Rate - Trading Economics", "content": "The US economy expanded an annualized 2.4% in Q4 2024, slightly higher than 2.3% in the previous estimates, primarily reflecting a downward revision to imports. Exports fell slightly less (-0.2% vs -0.5%) and imports declined more than initially anticipated (-1.9% vs -1.2%), leaving the contribution from net trade positive at 0.26 pp (vs 0.12 pp). Government expenditure also rose more (3.1% vs 2.9%) and fixed investment contracted less (-1.1% vs -1.4%), due to equipment (-8.7% vs -9%) while [...] The Gross Domestic Product (GDP) in the United States expanded 2.40 percent in the fourth quarter of 2024 over the previous quarter. GDP Growth Rate in the United States averaged 3.21 percent from 1947 until 2024, reaching an all time high of 35.20 percent in the third quarter of 2020 and a record low of -28.10 percent in the second quarter of 2020. This page provides the latest reported value for - United States GDP Growth Rate - plus previous releases, historical high and low, short-term [...] The Gross Domestic Product (GDP) in the United States expanded 2.40 percent in the fourth quarter of 2024 over the previous quarter. GDP Growth Rate in the United States is expected to be 0.90 percent by the end of this quarter, according to Trading Economics global macro models and analysts expectations. In the long-term, the United States GDP Growth Rate is projected to trend around 2.00 percent in 2026, according to our econometric models.\n%\n3Y5Y10YMAX\nExport API\nOK\nLoading...", "score": 0.9071234, "raw_content": null}, {"url": "https://www.bea.gov/data/gdp/gross-domestic-product", "title": "Gross Domestic Product | U.S. Bureau of Economic Analysis (BEA)", "content": "Real gross domestic product (GDP) increased at an annual rate of 2.4 percent in the fourth quarter of 2024 (October, November, and December), according to the third estimate released by the U.S. Bureau of Economic Analysis. In the third quarter, real GDP increased 3.1 percent. The increase in real GDP in the fourth quarter primarily reflected increases in consumer spending and government spending that were partly offset by a decrease in investment. Imports, which are a subtraction in the", "score": 0.9008183, "raw_content": null}, {"url": "https://www.nerdwallet.com/article/finance/gdp-report", "title": "GDP Report: Final Estimate Shows Growth Increased 2.4% in Q4 2024", "content": "NerdWallet's content is fact-checked for accuracy, timeliness and relevance. It undergoes a thorough review process involving writers and editors to ensure the information is as clear and complete as possible.\n\nAnna Helhoski\n\nRick VanderKnyff\n\nUpdated on April 7\n\nReal gross domestic product increased by an annual rate of 2.4% in the fourth quarter of 2024, according to the third estimate report released on March 27 by the Bureau of Economic Analysis. [...] The third estimate also showed that in 2024, the U.S. GDP grew 2.8% compared to a 2.9% increase in 2023.\n\nQ1 2025 GDP forecasts are negative\n\nA forecasting tool published by the Atlanta Federal Reserve shows negative growth for the first quarter of 2025; it expects gross domestic product (GDP) to contract by rate of -2.8%, according to data released on March 28. If the forecast is correct, it would be the first quarter where GDP declined since the first and second quarters of 2022. [...] GDP could be the next concern: On March 3, a forecasting tool published by the Atlanta Federal Reserve showed that GDP could contract by a rate of -2.8% in the first quarter of 2025. If GDP does indeed decline, it would be the first time since the first and second quarters of 2022.\n\nIn 2024, the U.S. GDP grew 2.8% compared to a 2.9% increase in 2023, according to a second estimate of real gross domestic product from the Bureau of Economic Analysis, released Feb. 27.", "score": 0.89053273, "raw_content": null}], "response_time": 1.78}
================================= Tool Message =================================
Name: tavily_search

{"query": "New York state GDP 2024", "follow_up_questions": null, "answer": null, "images": [], "results": [{"url": "https://en.wikipedia.org/wiki/Economy_of_New_York_(state)", "title": "Economy of New York (state) - Wikipedia", "content": "Jump to content\nMain menu\nSearch\nDonate\nCreate account\nLog in\nPersonal tools\nToggle the table of contents\nEconomy of New York (state)\n1 language\nArticle\nTalk\nRead\nEdit\nView history\nTools\nFrom Wikipedia, the free encyclopedia\nThis article is about the overall economy of New York State. For the economy of New York City, see Economy of New York City.\nEconomy of New York\nNew York City, the economic capital of New York (state)\nStatistics\nGDP $2.3 trillion (2024)[1]\nGDP per capita  $117,332 (2024)[2] [...] The economy of the State of New York is reflected in its gross state product in 2024 of $2.284 trillion, ranking third in size behind the larger states of California and Texas. If New York State were an independent nation, it would rank as the 10th largest economy in the world by nominal GDP. However, in 2019, the multi-state, New York City-centered metropolitan statistical area produced a gross metropolitan product (GMP) of $US2.0 trillion, ranking first nationally by a wide margin and would [...] Population below poverty line   13.6%[3]\nGini coefficient    0.5157 ± 0.0029 (2023)[4]\nLabour force    9,645,984 (2023)[5]\nUnemployment    4.4% (August 2024)[6]\nPublic finances\nRevenues    $63.5 billion[7]\nExpenses    $54.6 billion[8]", "score": 0.9511106, "raw_content": null}, {"url": "https://en.wikipedia.org/wiki/List_of_U.S._states_and_territories_by_GDP", "title": "List of U.S. states and territories by GDP - Wikipedia", "content": "GDP per capita also varied widely throughout the United States in 2024, with New York ($117,332), Massachusetts ($110,561), and Washington (state) ($108,468) recording the three highest GDP per capita figures in the U.S., while Mississippi ($53,061), Arkansas ($60,276), and West Virginia ($60,783) recorded the three lowest GDP per capita figures in the U.S. The District of Columbia, though, recorded a GDP per capita figure far higher than any U.S. state in 2024 at $263,220. [...] Overall, in the calendar year 2024, the United States' Nominal GDP at Current Prices totaled at $29.017 trillion, as compared to $25.744 trillion in 2022.\nThe three U.S. states with the highest GDPs were California ($4.080 trillion), Texas ($2.695 trillion), and New York ($2.284 trillion). The three U.S. states with the lowest GDPs were Vermont ($45.4 billion), Wyoming ($53.0 billion), and Alaska ($69.8 billion).", "score": 0.8947989, "raw_content": null}, {"url": "https://edc.nyc/sites/default/files/2025-01/NYCEDC-State-of-the-NYC-Economy-2024-v3.pdf", "title": "[PDF] State of the New York City Economy - NYCEDC", "content": "for talent faced a limited supply. STATE OF THE NEW YORK CITY ECONOMY 2024 / 21 STATE OF THE NEW YORK CITY ECONOMY 2024 / 22 After losing nearly a million jobs during the COVID-19 pandemic, New York City is now at record-high levels of private and total employment. The city’s gross city product (GCP) stands at $1.18 trillion as of 2023.24 While legacy sectors such as Finance and Insurance have continued to play a vital part in the city’s economic successes, emerging sectors like Tech, the Green [...] STATE OF THE NEW YORK CITY ECONOMY 2024 / 11 New York City’s economy is the largest in the nation, with $2 trillion in gross metropolitan product (GMP) for the metro area, representing 9% of the total US economy. As such, the city’s economy is closely intertwined with the broader national economic landscape, and US macroeconomic conditions play a significant role in shaping the economic backdrop for the city. National interest rates, inflation, gross domestic product (GDP), and employment [...] 1 Macro Trends STATE OF THE NEW YORK CITY ECONOMY 2024 / 12 Output Has Grown Faster in NYC than Nationally Since 2022 Actual and Projected US Real GDP and NYC Real GCP Growth Rates 2019 2020 2021 2022 2023 2024* 2025* NYC 2.6% -4.2% 5.5% 2.6% 2.8% 3.6% 1.9% US 2.5% -2.2% 5.8% 1.9% 2.5% 2.5% 1.4% Source: NYC OMB and US Bureau of Economic Analysis. Projections for 2024 and and 2025 from NYC OMB.", "score": 0.85797083, "raw_content": null}], "response_time": 0.63}
================================== Ai Message ==================================
Name: research_agent

- US GDP in 2024: $29.017 trillion (nominal, current prices)
- New York state GDP in 2024: $2.284 trillion
- New York state's share of US GDP in 2024: 7.87%
================================== Ai Message ==================================
Name: supervisor
Tool Calls:
  transfer_to_math_agent (call_m5ICqaoAtRXHWb8BI3638dJL)
 Call ID: call_m5ICqaoAtRXHWb8BI3638dJL
  Args:
================================= Tool Message =================================
Name: transfer_to_math_agent

Successfully transferred to math_agent
================================== Ai Message ==================================
Name: math_agent
Tool Calls:
  divide (call_Sf7nvyvEgIaoDlaioPmkCdqz)
 Call ID: call_Sf7nvyvEgIaoDlaioPmkCdqz
  Args:
    a: 2.284
    b: 29.017
================================= Tool Message =================================
Name: divide

0.07871247889168417
================================== Ai Message ==================================
Name: math_agent

US GDP in 2024: $29.017 trillion
New York state GDP in 2024: $2.284 trillion
New York state's share of US GDP: 7.87%
================================== Ai Message ==================================
Name: supervisor

US GDP in 2024 was $29.017 trillion. New York state GDP in 2024 was $2.284 trillion. New York state's GDP was about 7.87% of the US GDP.

 

4. 委任タスクの作成

ここまで、個々のエージェントは 完全なメッセージ履歴を解釈する ことに依存してタスクを決定してきました。代替のアプローチとして、スーパーバイザーに タスクを明示的に策定を委ねます。handoff_tool 関数に task_description パラメータを追加することでそれを行なうことができます。

from langgraph.types import Send


def create_task_description_handoff_tool(
    *, agent_name: str, description: str | None = None
):
    name = f"transfer_to_{agent_name}"
    description = description or f"Ask {agent_name} for help."

    @tool(name, description=description)
    def handoff_tool(
        # this is populated by the supervisor LLM
        task_description: Annotated[
            str,
            "Description of what the next agent should do, including all of the relevant context.",
        ],
        # these parameters are ignored by the LLM
        state: Annotated[MessagesState, InjectedState],
    ) -> Command:
        task_description_message = {"role": "user", "content": task_description}
        agent_input = {**state, "messages": [task_description_message]}
        return Command(
            # highlight-next-line
            goto=[Send(agent_name, agent_input)],
            graph=Command.PARENT,
        )

    return handoff_tool


assign_to_research_agent_with_description = create_task_description_handoff_tool(
    agent_name="research_agent",
    description="Assign task to a researcher agent.",
)

assign_to_math_agent_with_description = create_task_description_handoff_tool(
    agent_name="math_agent",
    description="Assign task to a math agent.",
)

supervisor_agent_with_description = create_react_agent(
    model="openai:gpt-4.1",
    tools=[
        assign_to_research_agent_with_description,
        assign_to_math_agent_with_description,
    ],
    prompt=(
        "You are a supervisor managing two agents:\n"
        "- a research agent. Assign research-related tasks to this assistant\n"
        "- a math agent. Assign math-related tasks to this assistant\n"
        "Assign work to one agent at a time, do not call agents in parallel.\n"
        "Do not do any work yourself."
    ),
    name="supervisor",
)

supervisor_with_description = (
    StateGraph(MessagesState)
    .add_node(
        supervisor_agent_with_description, destinations=("research_agent", "math_agent")
    )
    .add_node(research_agent)
    .add_node(math_agent)
    .add_edge(START, "supervisor")
    .add_edge("research_agent", "supervisor")
    .add_edge("math_agent", "supervisor")
    .compile()
)

Let’s now running it with the same input query:

for chunk in supervisor_with_description.stream(
    {
        "messages": [
            {
                "role": "user",
                "content": "find US and New York state GDP in 2024. what % of US GDP was New York state?",
            }
        ]
    },
    subgraphs=True,
):
    pretty_print_messages(chunk, last_message=True)
Update from subgraph supervisor:


	Update from node agent:


	================================== Ai Message ==================================
	Name: supervisor
	Tool Calls:
	  transfer_to_research_agent (call_tk8q8py8qK6MQz6Kj6mijKua)
	 Call ID: call_tk8q8py8qK6MQz6Kj6mijKua
	  Args:
	    task_description: Find the 2024 GDP (Gross Domestic Product) for both the United States and New York state, using the most up-to-date and reputable sources available. Provide both GDP values and cite the data sources.


Update from subgraph research_agent:


	Update from node agent:


	================================== Ai Message ==================================
	Name: research_agent
	Tool Calls:
	  tavily_search (call_KqvhSvOIhAvXNsT6BOwbPlRB)
	 Call ID: call_KqvhSvOIhAvXNsT6BOwbPlRB
	  Args:
	    query: 2024 United States GDP value from a reputable source
	    search_depth: advanced
	  tavily_search (call_kbbAWBc9KwCWKHmM5v04H88t)
	 Call ID: call_kbbAWBc9KwCWKHmM5v04H88t
	  Args:
	    query: 2024 New York state GDP value from a reputable source
	    search_depth: advanced


Update from subgraph research_agent:


	Update from node tools:


	================================= Tool Message =================================
	Name: tavily_search
	
	{"query": "2024 United States GDP value from a reputable source", "follow_up_questions": null, "answer": null, "images": [], "results": [{"url": "https://www.focus-economics.com/countries/united-states/", "title": "United States Economy Overview - Focus Economics", "content": "The United States' Macroeconomic Analysis:\n------------------------------------------\n\n**Nominal GDP of USD 29,185 billion in 2024.**\n\n**Nominal GDP of USD 29,179 billion in 2024.**\n\n**GDP per capita of USD 86,635 compared to the global average of USD 10,589.**\n\n**GDP per capita of USD 86,652 compared to the global average of USD 10,589.**\n\n**Average real GDP growth of 2.5% over the last decade.**\n\n**Average real GDP growth of 2.5% over the last decade.**\n\nShare of the region's population [...] |  | 2020 | 2021 | 2022 | 2023 | 2024 |\n| --- | --- | --- | --- | --- | --- |\n| [Population (million)](https://www.focus-economics.com/country-indicator/united-states/population/) | 331 | 332 | 334 | 337 | 340 |\n| [GDP (USD bn)](https://www.focus-economics.com/country-indicator/united-states/gdp/) | 21,354 | 23,681 | 26,007 | 27,721 | 29,185 |", "score": 0.73981786, "raw_content": null}, {"url": "https://tradingeconomics.com/united-states/gdp", "title": "United States GDP - Trading Economics", "content": "| Related | Last | Previous | Unit | Reference |\n| --- | --- | --- | --- | --- |\n| [Full Year GDP Growth](/united-states/full-year-gdp-growth) | 2.80 | 2.90 | percent | Dec 2024 |\n| [GDP](/united-states/gdp) | 27720.71 | 26006.89 | USD Billion | Dec 2023 |\n| [GDP Annual Growth Rate](/united-states/gdp-growth-annual) | 2.10 | 2.50 | percent | Mar 2025 |\n| [GDP Constant Prices](/united-states/gdp-constant-prices) | 23528.00 | 23542.30 | USD Billion | Mar 2025 |", "score": 0.65359193, "raw_content": null}, {"url": "https://fred.stlouisfed.org/series/GDP", "title": "Gross Domestic Product (GDP) | FRED | St. Louis Fed", "content": "Q1 2025: 29,976.638 |\nBillions of Dollars, Seasonally Adjusted Annual Rate |\nQuarterly\n\nUpdated:\nMay 29, 2025\n7:56 AM CDT\n\n[Next Release Date:\nJun 26, 2025](/releases/calendar?rid=53&y=2025)\n\nObservations\n\n|  |  |  |\n| --- | --- | --- |\n| Q1 2025: | 29,976.638 |  |\n| Q4 2024: | 29,723.864 |  |\n| Q3 2024: | 29,374.914 |  |\n| Q2 2024: | 29,016.714 |  |\n| Q1 2024: | 28,624.069 |  |\n| [View All](/data/GDP.txt) | |\n\nUnits:\n\nFrequency:", "score": 0.6152965, "raw_content": null}], "response_time": 2.53}


Update from subgraph research_agent:


	Update from node tools:


	================================= Tool Message =================================
	Name: tavily_search
	
	{"query": "2024 New York state GDP value from a reputable source", "follow_up_questions": null, "answer": null, "images": [], "results": [{"url": "https://www.ibisworld.com/united-states/economic-profiles/new-york/", "title": "New York Economic Trends, Stats & Rankings | IBISWorld", "content": "#### What is New York's Gross Domestic Product (GDP)?\n\nIn 2024, New York's GDP reached $1.8tn, representing an increase of 1.3% from 2023. New York's GDP has grown at an annualized rate of 2.9% over the five years to 2024. Moreover, New York's trailing five-year GDP growth ranks it 37th out of all 50 US states. [...] In 2024, the state of New York has a population of 19,482,372, having grown an annualized 0.0% over the five years to 2024, which ranks it 44th out of all 50 US states by growth rate. New York's gross state product (GSP) in 2024 reached $1.8tn, with growth of 1.3% over the 5 years to 2024. Businesses in New York employed a total of 11,671,845 people in 2024, with average annual employment growth over the past five years of 0.0%. The top three sectors by total employment are Finance and [...] The Finance and Insurance, Real Estate and Rental and Leasing and Information sectors contributed the most to New York's GDP in 2024, representing a combined 46.3% of state GDP.\n\nGDP trends by sector are an important indicator of which sectors are contributing the most value-add to the state's economy, in addition to how the state economy is evolving over time.\n\nSector\n\nGDP\n\nGrowth 2024 (%)\n\nAnnualized Growth 2019-24", "score": 0.8051581, "raw_content": null}, {"url": "https://comptroller.nyc.gov/reports/annual-state-of-the-citys-economy-and-finances-2024/", "title": "Annual State of the City's Economy and Finances 2024", "content": "(constant 2019 dollars)**22,550 15,322 13,596 19,451 21,211 21,096\n**_% change_**(32.1%)(11.3%)43.1%9.0%(0.5%)\n\nSource: NY State Department of Taxation and Finance and Office of the New York City Comptroller [...] [[1]](https://comptroller.nyc.gov/reports/annual-state-of-the-citys-economy-and-finances-2024/#_ftnref1) At that time, the Comptroller’s Office expected five-year cumulative real GDP growth, 2020 to 2024, of 8.7 percent while the mayor expected 9.5 percent.\n\n[[2]](https://comptroller.nyc.gov/reports/annual-state-of-the-citys-economy-and-finances-2024/#_ftnref2) U.S. Bureau of Labor Statistics Local Area Unemployment Statistics (LAUS). [...] **($ in millions)****FY 2025****FY 2026****FY 2027****FY 2028****Total****Change from June 2024 (FY2025-FY2028)****Source as Share of Total**\n**General Obligation Bonds**$6,900$6,230$6,920$7,110$27,160$1,960 42.8%\n**TFA FTS Bonds**6,900 6,230 6,920 7,110 27,160 2,460 42.8%\n**NYC Water Finance Authority**1,726 2,474 2,452 2,505 9,157 435 14.4%\n**Total****$15,526****$14,934****$16,292****$16,725****$63,477****$4,855****100.0%**", "score": 0.74541736, "raw_content": null}], "response_time": 3.45}


Update from subgraph research_agent:


	Update from node agent:


	================================== Ai Message ==================================
	Name: research_agent
	
	- United States 2024 GDP: $29.2 trillion (USD)  
	  Source: [Focus Economics](https://www.focus-economics.com/countries/united-states/)
	
	- New York State 2024 GDP: $1.8 trillion (USD)  
	  Source: [IBISWorld](https://www.ibisworld.com/united-states/economic-profiles/new-york/)


Update from subgraph supervisor:


	Update from node agent:


	================================== Ai Message ==================================
	Name: supervisor
	Tool Calls:
	  transfer_to_math_agent (call_EqT01HDOQDd5Timk89cccdXP)
	 Call ID: call_EqT01HDOQDd5Timk89cccdXP
	  Args:
	    task_description: Calculate what percentage of the US GDP ($29.2 trillion) was New York State's GDP ($1.8 trillion) in 2024. Show your working and round the final answer to two decimal points.


Update from subgraph math_agent:


	Update from node agent:


	================================== Ai Message ==================================
	Name: math_agent
	Tool Calls:
	  divide (call_OpdUlYEFqk4RZ2rF46M9eTrS)
	 Call ID: call_OpdUlYEFqk4RZ2rF46M9eTrS
	  Args:
	    a: 1.8
	    b: 29.2


Update from subgraph math_agent:


	Update from node tools:


	================================= Tool Message =================================
	Name: divide
	
	0.06164383561643836


Update from subgraph math_agent:


	Update from node agent:


	================================== Ai Message ==================================
	Name: math_agent
	Tool Calls:
	  multiply (call_vdKJTLtIzmG6JbPcGQn93MR6)
	 Call ID: call_vdKJTLtIzmG6JbPcGQn93MR6
	  Args:
	    a: 0.06164383561643836
	    b: 100


Update from subgraph math_agent:


	Update from node tools:


	================================= Tool Message =================================
	Name: multiply
	
	6.164383561643836


Update from subgraph math_agent:


	Update from node agent:


	================================== Ai Message ==================================
	Name: math_agent
	
	New York State's GDP was approximately 6.16% of the US GDP in 2024.


Update from subgraph supervisor:


	Update from node agent:


	================================== Ai Message ==================================
	Name: supervisor
	
	New York State’s GDP was approximately 6.16% of the US GDP in 2024.
	
	**Working:**
	- Percentage = (NY GDP / US GDP) × 100
	- = ($1.8 trillion / $29.2 trillion) × 100
	- = 0.06164 × 100
	- = 6.16% (rounded to two decimal points)

 

以上



クラスキャット

最近の投稿

  • LangGraph on Colab : マルチエージェント・スーパーバイザー
  • LangGraph on Colab : エージェント型 RAG
  • LangGraph : 例題 : エージェント型 RAG
  • LangGraph Platform : Get started : クイックスタート
  • LangGraph Platform : 概要

タグ

AutoGen (13) ClassCat Press Release (20) ClassCat TF/ONNX Hub (11) DGL 0.5 (14) Eager Execution (7) Edward (17) FLUX.1 (16) Gemini (20) HuggingFace Transformers 4.5 (10) HuggingFace Transformers 4.6 (7) HuggingFace Transformers 4.29 (9) Keras 2 Examples (98) Keras 2 Guide (16) Keras 3 (10) Keras Release Note (17) Kubeflow 1.0 (10) LangChain (45) LangGraph (23) MediaPipe 0.8 (11) Model Context Protocol (16) NNI 1.5 (16) OpenAI Agents SDK (8) OpenAI Cookbook (13) OpenAI platform (10) OpenAI platform 1.x (10) OpenAI ヘルプ (8) TensorFlow 2.0 Advanced Tutorials (33) TensorFlow 2.0 Advanced Tutorials (Alpha) (15) TensorFlow 2.0 Advanced Tutorials (Beta) (16) TensorFlow 2.0 Guide (10) TensorFlow 2.0 Guide (Alpha) (16) TensorFlow 2.0 Guide (Beta) (9) TensorFlow 2.0 Release Note (12) TensorFlow 2.0 Tutorials (20) TensorFlow 2.0 Tutorials (Alpha) (14) TensorFlow 2.0 Tutorials (Beta) (12) TensorFlow 2.4 Guide (24) TensorFlow Deploy (8) TensorFlow Get Started (7) TensorFlow Graphics (7) TensorFlow Probability (9) TensorFlow Programmer's Guide (22) TensorFlow Release Note (18) TensorFlow Tutorials (33) TF-Agents 0.4 (11)
2025年6月
月 火 水 木 金 土 日
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« 5月    
© 2025 ClasCat® AI Research | Powered by Minimalist Blog WordPress Theme