> ## 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 SDK を使用してマルチターンのエージェント型アプリケーションをインストルメントし、Agents タブで表示します。

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/instrument" />

W\&B Weave SDK を使用してマルチターンのエージェント型アプリケーションをインストルメントし、エージェントの動作を表示、デバッグ、評価する方法について説明します。このガイドは、エージェントを構築または統合する開発者のうち、会話、ターン、LLM Call、ツール実行を構造的に可視化したい方を対象としています。

Agents 向けの Weave SDK は、マルチターンのエージェントの会話のライフサイクル全体をモデル化します。具体的には、多数の会話を持つエージェント、ターンをまとめる会話、ユーザーとエージェント間の個々のやり取り (ターン)、ターン内の LLM Call、そして LLM によってトリガーされるツール実行が含まれます。トレースは Weave プロジェクトの **Agents** タブに表示されます。各会話では、ネストされたツール呼び出し、トークン使用量、フィードバックを含むマルチターンのタイムラインを確認できます。

Weave は、分散トレースのオープン標準である [OpenTelemetry (OTel)](https://opentelemetry.io/docs/concepts/) を基盤としています。ターン、LLM Call、ツール呼び出しはそれぞれ OTel の *スパン* (1 つの操作を表す構造化レコード) を出力します。各スパンには、`gen_ai.agent.name` や `gen_ai.conversation.id` などの [GenAI セマンティック規約](https://opentelemetry.io/docs/specs/semconv/gen-ai/)に準拠した属性が付与されます。

`@weave.op` デコレーターを使用して個々の関数を Op としてトレースする場合は、[LLM アプリケーションをトレースする](/ja/products/wandb/weave/guides/tracking/tracing)を参照してください。

<h2 id="before-you-begin">
  はじめる前に
</h2>

まず、`weave` パッケージをインストールして project を初期化します。このステップでチームと project が Weave に登録され、SDK がスパンを UI 上の正しい場所に送信できるようになります。

<Tabs>
  <Tab title="Python">
    ```bash lines theme={"system"}
    pip install weave
    ```

    `[YOUR-TEAM]` を CoreWeave Forge のチーム名に、`[YOUR-PROJECT]` を Weights & Biases のプロジェクト名に置き換えてください。

    ```python lines theme={"system"}
    import weave

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

    `start_conversation()`、`start_turn()`、`start_llm()`、`start_tool()`、`start_subagent()` のいずれかを呼び出す前に、`weave.init()` を呼び出してください。トレースが無効になっている場合や init が呼び出されていない場合、エージェントトレースの関数はすべて、エラーを出さずに no-op として動作します。そのため、インストルメンテーションを本番コードに残したまま、設定で有効・無効を切り替えられます。
  </Tab>

  <Tab title="TypeScript">
    ```bash lines theme={"system"}
    npm install weave
    ```

    `[YOUR-TEAM]` を CoreWeave Forge のチーム名に、`[YOUR-PROJECT]` を Weights & Biases のプロジェクト名に置き換えてください。

    ```typescript lines twoslash theme={"system"}
    // @noErrors
    import * as weave from 'weave';

    await weave.init('[YOUR-TEAM]/[YOUR-PROJECT]');
    ```

    `startConversation()`、`startTurn()`、`startLLM()`、`startTool()`、`startSubagent()` のいずれかを呼び出す前に、`weave.init()` を呼び出してください。トレースが無効になっている場合や init が呼び出されていない場合、エージェントトレースの関数はすべて、エラーを出さずに no-op として動作します。そのため、インストルメンテーションを本番コードに残したまま、設定で有効・無効を切り替えられます。
  </Tab>
</Tabs>

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

Weave は、エージェントの動作を 1 対多の関係からなる階層としてモデル化します。各エージェントは複数の会話を持つことができ、各会話は複数のターンを、各ターンは複数の LLM Call を持つことができます。さらに、各 LLM Call は複数のツール呼び出しをトリガーできます。

| 概念 | Weave SDK クラス | OTel スパンタイプ | 説明 | リファレンスページ |
| - | - | - | - | - |
| エージェント | *(クラスなし)* | *(スパンなし。`agent_name` 属性でグループ化)* | Agents タブに表示されるエージェント型アプリケーションで、1 つ以上の会話を含みます。 | |
| 会話 | `Conversation` | *(スパンなし。ターンは `conversation_id` 属性でグループ化)* | 1 つ以上のターンを含む会話または run です。 | [Python](/ja/products/wandb/weave/reference/python-sdk#class-conversation) <br /> [TypeScript](/ja/products/wandb/weave/reference/typescript-sdk/interfaces/conversation) |
| ターン | `Turn` | `invoke_agent` | 1 件のユーザーメッセージと、それに対するエージェントの完全な応答です。 | [Python](/ja/products/wandb/weave/reference/python-sdk#class-turn) <br /> [TypeScript](/ja/products/wandb/weave/reference/typescript-sdk/interfaces/turn) |
| LLM Call | `LLM` | `chat` | 言語モデル API への 1 回の呼び出しです。 | [Python](/ja/products/wandb/weave/reference/python-sdk#class-llm) <br /> [TypeScript](/ja/products/wandb/weave/reference/typescript-sdk/interfaces/llm) |
| ツール呼び出し | `Tool` | `execute_tool` | LLM の応答によってトリガーされた 1 回のツール呼び出しです。 | [Python](/ja/products/wandb/weave/reference/python-sdk#class-tool) <br /> [TypeScript](/ja/products/wandb/weave/reference/typescript-sdk/interfaces/tool) |
| サブエージェント Call | `SubAgent` | `invoke_agent` | ネストされたエージェントの invocation です。通常、あるエージェントが別のエージェントに処理を委譲する場合に発生します。 | [Python](/ja/products/wandb/weave/reference/python-sdk#class-subagent) <br /> [TypeScript](/ja/products/wandb/weave/reference/typescript-sdk/interfaces/subagent) |

次の図は、1 つのエージェントが複数の会話を持ち、1 つの会話が複数のターンを持つ、といった階層関係を示しています。

```mermaid theme={"system"}
flowchart TB
    Agent["エージェント<br/>agent_name"]

    Agent --> S1 & S2

    S1["会話 1<br/>conversation_id<br/>(OTel スパンなし)"]
    S2["会話 2<br/>conversation_id<br/>(OTel スパンなし)"]

    S1 --> T1 & T2
    S2 --> T3

    T1["ターン 1<br/>invoke_agent<br/>(ルートスパン, 独自のトレース)"]
    T2["ターン 2<br/>invoke_agent<br/>(ルートスパン, 独自のトレース)"]
    T3["ターン 1<br/>invoke_agent<br/>(ルートスパン, 独自のトレース)"]

    T1 --> L1 & L2
    L1["LLM Call<br/>chat"]
    L2["LLM Call<br/>chat"]

    L1 --> Tool1["ツール呼び出し<br/>execute_tool"]

    classDef agent fill:#DE72FF33,stroke:#454B52,stroke-width:2px
    classDef conversation fill:#FFD95C33,stroke:#454B52,stroke-width:2px
    classDef turn fill:#00CDDB33,stroke:#454B52,stroke-width:2px
    classDef llm fill:#FFCBAD33,stroke:#454B52,stroke-width:2px
    classDef tool fill:#f4f4f5,stroke:#454B52,stroke-width:2px

    class Agent agent
    class S1,S2 conversation
    class T1,T2,T3 turn
    class L1,L2 llm
    class Tool1 tool
```

会話は、親スパンではなく共通の `conversation_id` 属性によってターンをグループ化します。そのため、各ターンはそれぞれ独立した OTel トレースを開始します。この設計により、分散トレースと並列実行がサポートされます。クライアントはサーバー側で集約を行わず、スパンを OTel コレクターへ直接送信します。

<Tip>
  Claude Agent SDK や Codex などの SDK またはハーネスと Weave を統合するには、[エージェントインテグレーションを選択する](/ja/products/wandb/weave/agent-integration-quickstart)を参照してください。Weave は、エージェント構築用の複数の SDK やエージェントハーネスに自動でパッチを適用するため、すばやく統合できます。
</Tip>

<h2 id="agent-tracing-apis">
  エージェントトレース API
</h2>

以下のセクションでは、トップレベルの各トレース関数と、それぞれが受け入れる引数について説明します。これらの関数を使用して、前のセクションで説明したデータモデルの会話、ターン、LLM Call、ツール呼び出しの各レイヤーをインストルメントします。

Weave は以下のトップレベル関数を提供しています。各関数が返すオブジェクトは、コンテキストマネージャーとして使用できます (Python では `with`、TypeScript では `try/finally` を使用) 。`.end()` を呼び出して手動で終了することもできます。

<h3 id="start-a-conversation">
  会話を開始する
</h3>

`start_conversation()` (Python) または `startConversation()` (TypeScript) は、すべての子スパンに `conversation_id` 属性を付与し、ターンが Agents タブでグループ化されるようにします。`conversation_id` / `conversationId` を渡す場合、その値は会話の有効期間を通じて変わらないようにする必要があります。既存の会話に新しいターンを追加するには、同じ ID を再利用してください。省略した場合は、SDK が UUID を自動生成します。

実行中の会話はコンテキスト (Python の `ContextVar` または Node.js の `AsyncLocalStorage`) に保存されます。そのため、同じ非同期コンテキスト内で実行されるコードであれば、会話オブジェクトを明示的に渡さなくても、`weave.get_current_conversation()` / `weave.getCurrentConversation()` で取得できます。

<Tabs>
  <Tab title="Python">
    ```python lines theme={"system"}
    conversation = weave.start_conversation(
        agent_name="my-agent",    # オプション: UI でエージェントを識別します。省略すると、会話は名前付きエージェントの下にグループ化されません。
        conversation_id="",       # オプション: ターンをグループ化するための固定の ID。空の場合は自動生成されます。
        model="",                 # オプション: この会話のターンで使用するデフォルトのモデル。
        conversation_name="",     # オプション: UI に表示される、人が読みやすいラベル。
        include_content=True,     # オプション: False に設定すると、スパンからメッセージ本文を除外します。
        continue_parent_trace=False,  # オプション: 新しいトレースを開始せず、既存の OTel トレースに紐付けます。
    )
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript lines twoslash theme={"system"}
    // @noErrors
    const conversation = weave.startConversation({
      agentName: 'my-agent',  // オプション: UI でエージェントを識別します。省略すると、会話は名前付きエージェントの下にグループ化されません。
      conversationId: '',     // オプション: ターンをグループ化するための固定の ID。空の場合は自動生成されます。
      model: '',              // オプション: この会話のターンで使用するデフォルトのモデル。
    });
    ```
  </Tab>
</Tabs>

<h3 id="start-a-turn">
  ターンを開始する
</h3>

`start_turn()` (Python) と `startTurn()` (TypeScript) は、新しい `invoke_agent` スパンを作成します。このスパンは新しい OTel トレースのルートになります。Weave はこのスパンを使用して、ユーザーとエージェント間の 1 回分の完結したやり取りをタイムラインビューに表示します。

呼び出し方法は 2 通りあります。

* **トップレベル関数として**呼び出す (`weave.start_turn(...)` / `weave.startTurn(...)`)。以下のサンプルではこの形式を使用しています。コンテキストから実行中の会話を解決し、その会話 ID を継承します。実行中の会話がない場合、ターンは `conversation_id` なしで作成され、他のターンとはグループ化されません。
* **インスタンスメソッドとして**、参照を保持している会話から呼び出す (`conversation.start_turn(...)` / `conversation.startTurn(...)`)。コンテキストマネージャーのブロック内など、会話オブジェクトをスコープ内で明示的に扱える場合に便利です。以下の「コンテキストマネージャーまたは try-finally パターン」のサンプルではこの形式を使用しています。両 SDK の `Conversation`、`Turn`、`LLM`、`Tool`、`SubAgent` の各リファレンスページへの直接リンクについては、上記のデータモデルの表を参照してください。

<Tabs>
  <Tab title="Python">
    ```python lines theme={"system"}
    turn = weave.start_turn(
        user_message="What is the weather in Tokyo?",  # ユーザーの入力テキスト。
        agent_name="my-agent",   # オプション: 会話レベルのエージェント名をオーバーライドします。
        model="gpt-4o",          # オプション: このターンで使用するモデル。
    )
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript lines twoslash theme={"system"}
    // @noErrors
    const turn = weave.startTurn({
      agentName: 'my-agent',  // オプション: 会話レベルのエージェント名をオーバーライドします。
      model: 'gpt-4o',        // オプション: このターンで使用するモデル。
    });
    ```
  </Tab>
</Tabs>

<h3 id="start-an-llm-call">
  LLM Call を開始する
</h3>

`start_llm()` / `startLLM()` は、現在のターンの下にネストされた `chat` スパンを作成します。Weave はこのスパンを使用して、トークン使用量、モデル名、入力メッセージと出力メッセージ、推論を Agents ビューに表示します。

<Tabs>
  <Tab title="Python">
    ```python lines theme={"system"}
    llm = weave.start_llm(
        model="gpt-4o",             # モデル識別子。
        provider_name="openai",     # オプション: プロバイダー名（例: "openai"、"anthropic"）。下記の注記を参照してください。
        system_instructions=["Be concise."],  # オプション: システムプロンプトの strings。
    )
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript lines twoslash theme={"system"}
    // @noErrors
    const llm = weave.startLLM({
      model: 'gpt-4o',          // モデル識別子。
      providerName: 'openai',   // オプション: プロバイダー名（例: "openai"、"anthropic"）。下記の注記を参照してください。
    });
    ```
  </Tab>
</Tabs>

LLM Call が完了したら、`llm` オブジェクトが閉じられる前に応答データを割り当てます。

<Tabs>
  <Tab title="Python">
    ```python lines theme={"system"}
    with weave.start_llm(model="gpt-4o", provider_name="openai") as llm:
        response = openai_client.chat.completions.create(...)
        llm.input_messages = [Message(role="user", content="...")]
        llm.output_messages = [Message(role="assistant", content=response.choices[0].message.content)]
        llm.usage = Usage(
            input_tokens=response.usage.prompt_tokens,
            output_tokens=response.usage.completion_tokens,
        )
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript lines twoslash theme={"system"}
    // @noErrors
    const llm = weave.startLLM({ model: 'gpt-4o', providerName: 'openai' });
    try {
      const response = await openaiClient.chat.completions.create({ ... });
      llm.record({
        inputMessages: [{ role: 'user', content: '...' }],
        outputMessages: [{ role: 'assistant', content: response.choices[0].message.content ?? '' }],
        usage: {
          inputTokens: response.usage?.prompt_tokens,
          outputTokens: response.usage?.completion_tokens,
        },
      });
    } finally {
      llm.end();
    }
    ```

    `llm.record()` は、`inputMessages`、`outputMessages`、`usage`、`reasoning` を 1 回の呼び出しでまとめて割り当てるためのショートカットです。必要に応じて、各プロパティを個別に設定することもできます。Python SDK にも同じメソッドが `llm.record(...)` として用意されており、snake\_case のキーワード引数で指定します。
  </Tab>
</Tabs>

`provider_name` / `providerName` は明示的に指定してください。Weave はモデルの string からプロバイダーを推測しません。

<h3 id="start-a-tool-call">
  ツール呼び出しを開始する
</h3>

`start_tool()` / `startTool()` は `execute_tool` スパンを作成します。このスパンは、コンテキスト内で実行中の OTel スパン (通常は、そのツール呼び出しを生成した LLM Call の `chat` スパン) の子になります。

<Tabs>
  <Tab title="Python">
    ```python lines theme={"system"}
    tool = weave.start_tool(
        name="get_weather",                  # LLM に宣言したツール名。
        arguments='{"city": "Tokyo"}',       # ツール引数の JSON string。
        tool_call_id="call_abc123",          # オプション: LLM の応答に含まれるツール呼び出し ID。
    )
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript lines twoslash theme={"system"}
    // @noErrors
    const tool = weave.startTool({
      name: 'get_weather',            // LLM に宣言したツール名。
      args: '{"city": "Tokyo"}',      // オプション: ツール引数の JSON string。
      toolCallId: 'call_abc123',      // オプション: LLM の応答に含まれるツール呼び出し ID。
    });
    ```
  </Tab>
</Tabs>

終了する前にツール結果を設定します。

<Tabs>
  <Tab title="Python">
    ```python lines theme={"system"}
    with weave.start_tool(name="get_weather", arguments='{"city": "Tokyo"}') as tool:
        result = get_weather_api("Tokyo")
        tool.result = result  # dict、list、string を受け入れます。自動的に JSON エンコードされます。
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript lines twoslash theme={"system"}
    // @noErrors
    const tool = weave.startTool({ name: 'get_weather', args: '{"city": "Tokyo"}' });
    try {
      tool.result = await getWeatherApi('Tokyo');
    } finally {
      tool.end();
    }
    ```
  </Tab>
</Tabs>

<h2 id="usage-patterns-for-agent-tracing">
  エージェントトレースの使用パターン
</h2>

以下のセクションでは、エージェントのコード構成に応じてこれらの関数をどのように組み合わせるかを説明します。

以下のサンプルでは、Weave SDK の 2 つのタイプを使用します。

* `Message` ([Python](/ja/products/wandb/weave/reference/python-sdk#class-message) · [TypeScript](/ja/products/wandb/weave/reference/typescript-sdk/interfaces/message)) は、会話内の 1 つのエントリ (ユーザー入力、アシスタントの応答、システムプロンプト、ツール結果のいずれか) を表します。モデルが受け取った内容を記録するには、メッセージのリストを `llm.input_messages` / `llm.inputMessages` に割り当てます。モデルが生成した内容を記録するには、`llm.output_messages` / `llm.outputMessages` に割り当てます。
* `Usage` ([Python](/ja/products/wandb/weave/reference/python-sdk#class-usage) · [TypeScript](/ja/products/wandb/weave/reference/typescript-sdk/interfaces/usage)) は、LLM の応答からトークン数を取得するもので、`llm.usage` に割り当てます。

Weave はこれら 2 つを使用して、各 LLM Call の入力、出力、トークン使用量を Agents ビューに表示します。

<h3 id="context-manager-or-try-finally-pattern">
  コンテキストマネージャーまたは try-finally パターン
</h3>

ほとんどのエージェントでは、Python ではコンテキストマネージャーパターンを、TypeScript では try-finally パターンを使用してください。例外が発生した場合でも、ブロックの終了時にスパンが閉じられ、送信されます。

Weave は実行中の会話、ターン、LLM Call をコンテキストに保持します。そのため、ブロック内で呼び出される関数は、親への参照を明示的に保持していなくても `start_llm()` / `startLLM()` や `start_tool()` / `startTool()` を呼び出せます。コードが同じ非同期コンテキストで実行されている限り、この仕組みはモジュールの境界を越えても機能します。コールスタック内のどこからでも実行中のオブジェクトを取得するには、`weave.get_current_conversation()` / `weave.getCurrentConversation()`、`weave.get_current_turn()` / `weave.getCurrentTurn()`、`weave.get_current_llm()` / `weave.getCurrentLLM()` を使用します。

<Tabs>
  <Tab title="Python">
    ```python lines highlight="13,14,17,25,29" theme={"system"}
    import weave
    from weave.conversation import Message, Usage

    # プレースホルダー関数: 独自の実装に置き換えてください。
    def call_openai(*args, **kwargs):
        pass  # 使用する LLM クライアントの呼び出しに置き換えてください。

    def get_weather_api(city: str) -> str:
        return "24°C, sunny"  # 使用する天気 API の呼び出しに置き換えてください。

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

    with weave.start_conversation(agent_name="weather-bot") as conversation:
        with conversation.start_turn(user_message="What is the weather in Tokyo?") as turn:

            # 1 回目の LLM Call: ツール呼び出しを返します。
            with weave.start_llm(model="gpt-4o", provider_name="openai") as llm:
                response = call_openai(...)
                llm.input_messages = [Message(role="user", content="What is the weather?")]
                llm.think("User wants weather data, I should call get_weather.")
                llm.output("Let me check the weather for you.")
                llm.usage = Usage(input_tokens=100, output_tokens=20)

                # ツール呼び出し: 呼び出しを要求した LLM Call の子として記録されます。
                with weave.start_tool(name="get_weather", arguments='{"city":"Tokyo"}') as tool:
                    tool.result = get_weather_api("Tokyo")  # "24°C, sunny" を返します。

            # 2 回目の LLM Call: 最終的な回答を生成します。
            with weave.start_llm(model="gpt-4o", provider_name="openai") as llm:
                llm.input_messages = [Message(role="user", content="What is the weather?")]
                llm.output("It is 24°C and sunny in Tokyo today.")
                llm.usage = Usage(input_tokens=150, output_tokens=30)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript lines highlight="11,13,16,24,35" twoslash theme={"system"}
    // @noErrors
    import * as weave from 'weave';
    import type { Message, Usage } from 'weave';

    // プレースホルダー関数: 独自の実装に置き換えてください。
    async function getWeatherApi(city: string): Promise<string> {
      return '24°C, sunny';  // 使用する天気 API の呼び出しに置き換えてください。
    }

    await weave.init('[YOUR-TEAM]/[YOUR-PROJECT]');

    const conversation = weave.startConversation({ agentName: 'weather-bot' });
    try {
      const turn = conversation.startTurn({ agentName: 'weather-bot' });
      try {
        // 1 回目の LLM Call: ツール呼び出しを返します。
        const llm = weave.startLLM({ model: 'gpt-4o', providerName: 'openai' });
        try {
          llm.inputMessages = [{ role: 'user', content: 'What is the weather?' }];
          llm.think('User wants weather data, I should call get_weather.');
          llm.output('Let me check the weather for you.');
          llm.usage = { inputTokens: 100, outputTokens: 20 };

          // ツール呼び出し: 呼び出しを要求した LLM Call の子として記録されます。
          const tool = weave.startTool({ name: 'get_weather', args: '{"city":"Tokyo"}' });
          try {
            tool.result = await getWeatherApi('Tokyo');  // "24°C, sunny" を返します。
          } finally {
            tool.end();
          }
        } finally {
          llm.end();
        }

        // 2 回目の LLM Call: 最終的な回答を生成します。
        const llm2 = weave.startLLM({ model: 'gpt-4o', providerName: 'openai' });
        try {
          llm2.inputMessages = [{ role: 'user', content: 'What is the weather?' }];
          llm2.output('It is 24°C and sunny in Tokyo today.');
          llm2.usage = { inputTokens: 150, outputTokens: 30 };
        } finally {
          llm2.end();
        }
      } finally {
        turn.end();
      }
    } finally {
      conversation.end();
    }
    ```
  </Tab>
</Tabs>

<h3 id="manual-start-and-end-pattern">
  手動で開始・終了するパターン
</h3>

`with` ブロックや `try/finally` を使用できない場合は、`.end()` を明示的に呼び出します。たとえば、スパンの開始と終了を別々の関数の Call で行う場合や、コルーチンの外部で非同期のライフサイクルを管理する場合などです。スパンを確実に閉じてコレクターにフラッシュするため、作成したすべてのオブジェクトに対して必ず `.end()` を呼び出してください。

<Tabs>
  <Tab title="Python">
    ```python lines highlight="1,2,4,9,15" theme={"system"}
    conversation = weave.start_conversation(agent_name="weather-bot")
    turn = conversation.start_turn(user_message="What is the weather?")

    llm = weave.start_llm(model="gpt-4o", provider_name="openai")
    llm.input_messages = [Message(role="user", content="What is the weather?")]
    llm.output("Let me check.")
    llm.usage = Usage(input_tokens=100, output_tokens=20)

    tool = weave.start_tool(name="get_weather", arguments='{"city": "Tokyo"}')
    tool.result = "24°C, sunny"
    tool.end()   # end() は冪等なため、複数回呼び出しても安全です。

    llm.end()

    llm2 = weave.start_llm(model="gpt-4o", provider_name="openai")
    llm2.output("It is 24°C and sunny in Tokyo.")
    llm2.usage = Usage(input_tokens=150, output_tokens=30)
    llm2.end()

    turn.end()
    conversation.end()
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript lines highlight="1,2,4,9,15" twoslash theme={"system"}
    // @noErrors
    const conversation = weave.startConversation({ agentName: 'weather-bot' });
    const turn = conversation.startTurn({ agentName: 'weather-bot' });

    const llm = weave.startLLM({ model: 'gpt-4o', providerName: 'openai' });
    llm.inputMessages = [{ role: 'user', content: 'What is the weather?' }];
    llm.output('Let me check.');
    llm.usage = { inputTokens: 100, outputTokens: 20 };

    const tool = weave.startTool({ name: 'get_weather', args: '{"city": "Tokyo"}' });
    tool.result = '24°C, sunny';
    tool.end();  // end() は冪等なため、複数回呼び出しても安全です。

    llm.end();

    const llm2 = weave.startLLM({ model: 'gpt-4o', providerName: 'openai' });
    llm2.output('It is 24°C and sunny in Tokyo.');
    llm2.usage = { inputTokens: 150, outputTokens: 30 };
    llm2.end();

    turn.end();
    conversation.end();
    ```
  </Tab>
</Tabs>

<h2 id="semantic-conventions">
  セマンティック規約
</h2>

Weave SDK は、[GenAI セマンティック規約](https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-spans/)および [GenAI エージェントスパン規約](https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-agent-spans/)に準拠した OTel スパンを出力します。Weave はあらゆる OTel スパンを受け入れ、すべての属性を保存してクエリできるようにします。Weave のトレースオブジェクトと併用して、標準の OTel スパン API でスパンに任意の属性を追加することもできます。

<h2 id="how-data-appears-in-the-weights-biases-ui">
  Weights & Biases UI でのデータの表示
</h2>

前述のパターンでエージェントをインストルメントして実行すると、トレースは Weave プロジェクトの **Agents** タブ (`https://forge.coreweave.com/wandb/[YOUR-TEAM]/[YOUR-PROJECT]/weave/agents`) に表示されます。

* **Conversations タブ**には、すべての会話が、ターンのアクティビティを示すミニマップとともに表示されます。
* **Conversation 詳細ビュー**は会話をクリックすると開きます。このビューには、その会話のすべてのターン、LLM Call、ツール実行、トークン数、および関連付けられたフィードバックが表示されます。

Weave で Agents データを表示する方法の詳細については、[エージェントのアクティビティを表示する](/ja/products/wandb/weave/guides/tracking/view-agent-activity)を参照してください。


## Related topics

- [インテグレーションの概要](/ja/products/wandb/weave/guides/integrations.md)
