> ## Documentation Index
> Fetch the complete documentation index at: https://docs.coreweave.com/llms.txt
> Use this file to discover all available pages before exploring further.

# サブエージェントをトレースする

> Weave のサブエージェントスパンを使用して、サブエージェントへの委譲をトレースし、ネストされたエージェントの invocation を表示します。

export const AgentLensBanner = ({href}) => <Tip>
    <strong>This workflow is also available in CoreWeave Agent Lens.</strong> Agent Lens is the Forge experience built for tracing, monitoring, and analyzing AI agents, with automated insights into agent failures and user intents. It uses the same trace data as Weights & Biases Weave, so the traces you already send appear there with nothing to migrate.{' '}
    <a href={href || '/products/agent-lens'}>{href ? 'See how to do this in Agent Lens' : 'Learn about Agent Lens'}</a>.
  </Tip>;

<AgentLensBanner href="/ja/products/agent-lens/tracing/sub-agents" />

このガイドでは、W\&B Weave を使用してサブエージェントをトレースし、委譲されたエージェントの invocation が親ターンと同じトレース内のネストされたスパンとして表示されるようにする方法を説明します。サブエージェントをトレースすると、親エージェントが呼び出した専門エージェント、その動作、最終回答への貢献を含め、エージェントの推論の階層全体を確認できます。このガイドは、Weave でマルチエージェントシステムをインストルメントする開発者を対象としています。

サブエージェントは、ターン内で実行される、委譲されたエージェントの invocation です。あるエージェントが別のエージェントに処理を委譲する場合、たとえばスーパーバイザーエージェントが専門エージェントにディスパッチする場合などにサブエージェントを使用します。

Weave でインストルメントすると、サブエージェントは親ターンと同じトレース内に、ネストされた `invoke_agent` OpenTelemetry (OTel) スパンを生成します。**Agents** ビューでは、このネスト構造により、サブエージェントの invocation がそれをトリガーしたターンの下にレンダリングされ、その下に固有の LLM Call とツール呼び出しがまとめられます。

<h2 id="sub-agent-data-model">
  サブエージェントのデータモデル
</h2>

コードをインストルメントする前に、Weave がトレース内でサブエージェントをどのように表現するかを理解しておくと役立ちます。`weave.start_subagent` スパンは OTel の `invoke_agent` スパンに対応し、親ターンと同じ操作名を出力します。Weave は、トレース内の親子関係によって両者を区別します。

```plaintext theme={"system"}
ターン (invoke_agent — ルートスパン)
├── LLM Call (chat)              ← 親エージェントの推論
│   └── サブエージェント (invoke_agent)  ← ここで委譲が行われます
│       ├── LLM Call (chat)      ← サブエージェント自身の LLM Call
│       └── ツール呼び出し (execute_tool)
└── LLM Call (chat)              ← 親エージェントが最終回答をまとめます
```

サブエージェントは現在の会話の `conversation_id` を継承するため、**Agents** ビューでは会話の他の部分と同じグループにまとめられます。

```python lines theme={"system"}
sub = weave.start_subagent(
    name="research-specialist",   # 必須: この sub-agent を UI で識別します。
    model="gpt-4o",               # オプション: 空の場合、親の会話のモデルにデフォルト設定されます。
)
```

`weave.start_subagent` は `invoke_agent` スパンを作成します。このスパンは、OTel コンテキストで現在アクティブなスパン (通常は親ターン、または委譲のきっかけとなった LLM Call) の子として自動的に配置されます。親子関係は OTel コンテキストの伝播によって処理されるため、明示的に委譲を行う必要はありません。

<h2 id="trace-a-single-sub-agent">
  単一のサブエージェントをトレースする
</h2>

次の例では、リクエストを受け取り、回答を検索するために Wikipedia 検索ツールを使用する調査専門のサブエージェントに委譲する、スーパーバイザーエージェントを実行します。

Weave は、会話を `weave.start_conversation`、続いて `conversation.start_turn` でラップすることで、階層全体を取得します。次に、専門エージェントの `weave.start_subagent` ブロックを使用してサブエージェントのトレースを取得し、各 LLM Call とツール実行を子スパンとして記録します。

これらの例では、エージェント間のトレースに焦点を当てるため、ルーティングロジックを意図的に省略しています。

```python lines highlight="4,10,16,22,30" theme={"system"}
import weave
from weave.conversation import Message, Usage

weave.init("[YOUR-TEAM]/[YOUR-PROJECT]")

with weave.start_conversation(agent_name="supervisor") as conversation:
    with conversation.start_turn(user_message="Research the founders of Anthropic.") as turn:

        # スーパーバイザーの LLM Call: 委譲先のスペシャリストを決定します。
        with weave.start_llm(model="gpt-4o", provider_name="openai") as llm:
            llm.input_messages = [Message(role="user", content="Research the founders of Anthropic.")]
            llm.output("Delegating to the research specialist.")
            llm.usage = Usage(input_tokens=80, output_tokens=10)

        # サブエージェントとしてリサーチスペシャリストに委譲します。
        with weave.start_subagent(name="research-specialist", model="gpt-4o") as sub:
            with sub.llm(model="gpt-4o", provider_name="openai") as sub_llm:
                sub_llm.input_messages = [Message(role="user", content="Find founders of Anthropic.")]
                sub_llm.output("I should search for this.")
                sub_llm.usage = Usage(input_tokens=120, output_tokens=15)

                with weave.start_tool(name="wikipedia_search", arguments='{"query":"Anthropic"}') as tool:
                    tool.result = "Anthropic was founded by Dario and Daniela Amodei in 2021."

            with sub.llm(model="gpt-4o", provider_name="openai") as sub_llm:
                sub_llm.output("Anthropic was founded by Dario and Daniela Amodei in 2021.")
                sub_llm.usage = Usage(input_tokens=200, output_tokens=25)

        # スーパーバイザーのターンに戻り、最終的な回答をまとめます。
        with weave.start_llm(model="gpt-4o", provider_name="openai") as llm:
            llm.output("Anthropic was founded by Dario and Daniela Amodei in 2021.")
            llm.usage = Usage(input_tokens=300, output_tokens=20)
```

**Agents** ビューでは、サブエージェントはターン内にネストされた `invoke_agent` ブロックとして表示され、その配下にサブエージェント自身の LLM Call とツール呼び出しがまとめられます。スーパーバイザーが直接行う LLM Call は、引き続きサブエージェントと同じ階層に表示されます。

<h2 id="trace-multiple-sub-agents">
  複数のサブエージェントをトレースする
</h2>

次の例では、コンテンツパイプラインのエージェントを実行します。このエージェントは 1 つのリクエストを処理する際、兄弟関係にある 3 つのサブエージェントに順番に処理を委譲します。事実を収集する `researcher`、投稿の下書きを作成する `writer`、最終出力を仕上げる `reviewer` の 3 つです。

Weave は、サブエージェントごとに個別の `weave.start_subagent` ブロックを開くことで、3 つのサブエージェントすべてを同じターン配下の兄弟として取得します。各サブエージェントは実行中のターンの OTel コンテキストを継承するため、サブエージェント同士が入れ子になることはなく、ターンの下にネストされた対等な `invoke_agent` スパンとして表示されます。

```python lines highlight="1,5,11,15,22" theme={"system"}
with weave.start_conversation(agent_name="content-pipeline") as conversation:
    with conversation.start_turn(user_message="Write a short blog post about Anthropic.") as turn:

        # 調査担当のサブエージェント: 事実を収集します。
        with weave.start_subagent(name="researcher", model="gpt-4o") as researcher:
            with researcher.llm(model="gpt-4o", provider_name="openai") as sub_llm:
                sub_llm.input_messages = [Message(role="user", content="Find key facts about Anthropic.")]
                sub_llm.output("I should search Wikipedia.")
                sub_llm.usage = Usage(input_tokens=80, output_tokens=15)

                with weave.start_tool(name="wikipedia_search", arguments='{"query":"Anthropic"}') as tool:
                    tool.result = "Anthropic was founded by Dario and Daniela Amodei in 2021."

        # 執筆担当のサブエージェント: 投稿の下書きを作成します。
        with weave.start_subagent(name="writer", model="gpt-4o") as writer:
            with writer.llm(model="gpt-4o", provider_name="openai") as sub_llm:
                sub_llm.input_messages = [Message(role="user", content="Draft a post using the research.")]
                sub_llm.output("Anthropic, founded in 2021 by Dario and Daniela Amodei, builds AI safety research...")
                sub_llm.usage = Usage(input_tokens=180, output_tokens=120)

        # レビュー担当のサブエージェント: 下書きを推敲します。
        with weave.start_subagent(name="reviewer", model="gpt-4o") as reviewer:
            with reviewer.llm(model="gpt-4o", provider_name="openai") as sub_llm:
                sub_llm.input_messages = [Message(role="user", content="Review and tighten the draft.")]
                sub_llm.output("Final post: Anthropic, founded in 2021 by Dario and Daniela Amodei, builds AI safety research...")
                sub_llm.usage = Usage(input_tokens=200, output_tokens=140)
```

**Agents** ビューでは、ターンに兄弟関係にある 3 つのサブエージェントの invocation が含まれ、それぞれの下に個別の LLM Call がネストされています。また、`researcher` には自身のツール呼び出しも含まれます。サブエージェント同士が親子関係になることはありません。

<h2 id="trace-nested-sub-agents">
  ネストされたサブエージェントをトレースする
</h2>

サブエージェントは、さらに別のサブエージェントに処理を委譲できます。各 `start_subagent` の呼び出しは、OTel コンテキストで現在実行中のスパンの下にネストされます。

```python lines highlight="1,2,4,5,11,16" theme={"system"}
with weave.start_conversation(agent_name="orchestrator") as conversation:
    with conversation.start_turn(user_message="Compare Anthropic and OpenAI.") as turn:

        with weave.start_subagent(name="research-coordinator") as coordinator:
            with weave.start_subagent(name="anthropic-researcher") as r1:
                with r1.llm(model="gpt-4o", provider_name="openai") as sub_llm:
                    sub_llm.output("Anthropic facts...")
                    sub_llm.usage = Usage(input_tokens=120, output_tokens=30)

                # ネスト: researcher は自身の summarizer sub-agent に委譲する。
                with weave.start_subagent(name="anthropic-summarizer") as summarizer:
                    with summarizer.llm(model="gpt-4o", provider_name="openai") as sub_llm:
                        sub_llm.output("Anthropic summary: ...")
                        sub_llm.usage = Usage(input_tokens=80, output_tokens=20)

            with weave.start_subagent(name="openai-researcher") as r2:
                with r2.llm(model="gpt-4o", provider_name="openai") as sub_llm:
                    sub_llm.output("OpenAI facts...")
                    sub_llm.usage = Usage(input_tokens=120, output_tokens=30)
```

この例では、ターンの下に 3 階層のネストが生成されます。

```plaintext theme={"system"}
turn (invoke_agent)
└── research-coordinator (invoke_agent)
    ├── anthropic-researcher (invoke_agent)
    │   ├── chat
    │   └── anthropic-summarizer (invoke_agent)   ← anthropic-researcher 内にネスト
    │       └── chat
    └── openai-researcher (invoke_agent)          ← anthropic-researcher の兄弟
        └── chat
```

**Agents** ビューでは、`research-coordinator` はターンのサブエージェントとして、`anthropic-researcher` と `openai-researcher` はコーディネーター配下の兄弟要素として、`anthropic-summarizer` は `anthropic-researcher` のサブエージェントとして表示されます。


## Related topics

- [エージェントをトレースする](/ja/products/wandb/weave/guides/tracking/trace-agents.md)
