> ## 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.

# エージェント スパンに属性を設定する

> エージェント スパンにカスタム属性を付与して、Agent Lens でアクティビティをフィルターおよび分析します。

CoreWeave Forge SDK でエージェントをインストルメントすると、各スパンオブジェクト (`Turn`、`LLM`、`Tool`、`SubAgent`) にカスタムメタデータを属性として付与できます。属性とは、スパンが持つキーと値のペアからなるプロパティです。属性を使用すると、ユーザー ID、テナント、実験名、環境ラベルなどのコンテキスト情報をエージェント スパンに記録できます。記録したメタデータを使って、CoreWeave Agent Lens UI でエージェントのアクティビティをフィルターおよびグループ化できます。

属性は、`set_attributes()` (Python) または `setAttributes()` (TypeScript) で個々のスパンに設定できます。また、会話が出力するすべてのスパンに適用される、会話全体の属性として設定することもできます。`set_attributes` は、[OpenTelemetry (OTel) スパン API](https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-spans/) の `Span.set_attributes` メソッドに対応しています。Agent Lens SDK は OTel スパンを出力し、すべての属性を保存するため、Agent Lens で属性をクエリできます。

このページのサンプルは、[エージェントをトレースする](/ja/products/agent-lens/tracing/instrument#before-you-begin)の手順に従って SDK をインストールし、初期化済みであることを前提としています。

<h2 id="set-attributes-on-a-span">
  スパンに属性を設定する
</h2>

`set_attributes()` (Python) または `setAttributes()` (TypeScript) を使用すると、単一のスパンに任意の属性を付与できます。キーが 1 つの場合も複数の場合も、辞書またはオブジェクトを渡してください。このメソッドはスパンを返すため、呼び出しをチェーンできます。

<Tabs>
  <Tab title="Python">
    ```python lines theme={"system"}
    from coreweave.forge.agentlens import tracing

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

    with tracing.start_conversation(agent_name="my-agent"):
        with tracing.start_turn(user_message="What is the weather in Tokyo?") as turn:
            # このターンのスパンに属性を付与する
            turn.set_attributes({"user_id": "12345", "tenant": "acme", "env": "production"})
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript lines theme={"system"}
    import { tracing } from '@coreweave/forge-sdk/agentlens';

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

    await tracing.runIsolated(async () => {
      const conversation = tracing.startConversation({ agentName: 'my-agent' });
      const turn = tracing.startTurn({ userMessage: 'What is the weather in Tokyo?' });

      // このターンのスパンに属性を付与する
      turn.setAttributes({ user_id: '12345', tenant: 'acme', env: 'production' });

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

これらのメソッドはすべてのスパンクラスで使用できます。たとえば、個々のツール呼び出しや LLM Call にタグを付けることもできます。

<Tabs>
  <Tab title="Python">
    ```python lines theme={"system"}
    with tracing.start_turn(user_message="What is the weather in Tokyo?") as turn:
        with turn.start_tool(name="get_weather") as tool:
            tool.set_attributes({"weave.display_name": "Weather lookup"})
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript lines theme={"system"}
    const turn = tracing.startTurn({ userMessage: 'What is the weather in Tokyo?' });
    const tool = turn.startTool({ name: 'get_weather' });

    tool.setAttributes({ 'weave.display_name': 'Weather lookup' });

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

属性キーの大半は任意のカスタムメタデータですが、Agent Lens では 2 つの接頭辞が特別な処理用に予約されています。`weave.*` で始まるキーは Agent Lens の組み込みフィールドに、`gen_ai.*` で始まるキーは OpenTelemetry GenAI セマンティック規約のフィールドにマッピングされます。前の例の `weave.display_name` は予約キーで、Agent Lens UI に表示されるスパンの表示名を設定します。フィルタリングやグループ化に使用する任意のメタデータには、`user_id` や `tenant` などの独自のキーを使用してください。Agent Lens はこれらをフィルタリング可能なカスタム属性として保存します。

<h2 id="record-what-happens-during-a-span">
  スパンの実行中に発生したことを記録する
</h2>

属性を使用すると、権限確認のプロンプトやその結果など、スパンの実行中に発生した出来事も記録できます。出来事が発生した時点で、スパンがまだ記録中のうちに属性を設定してください。

<Tabs>
  <Tab title="Python">
    ```python lines theme={"system"}
    with tracing.start_turn(user_message="Delete the old backups.") as turn:
        turn.set_attributes({"permission.scope": "filesystem.delete"})
        # ... ユーザーに確認し、回答を待つ ...
        turn.set_attributes({"permission.granted": True})
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript lines theme={"system"}
    const turn = tracing.startTurn({ userMessage: 'Delete the old backups.' });
    turn.setAttributes({ 'permission.scope': 'filesystem.delete' });
    // ... ユーザーに確認し、回答を待つ ...
    turn.setAttributes({ 'permission.granted': true });
    turn.end();
    ```
  </Tab>
</Tabs>

属性に記録されるのは値のみで、設定された時刻は記録されません。スパン内で何かが発生した時刻を把握する必要がある場合は、`permission.granted_at` のように、時刻を別の属性として記録してください。

<Note>
  OpenTelemetry が [Span Event API を非推奨にする](https://opentelemetry.io/blog/2026/deprecating-span-events/)ため、SDK の `add_event()` (Python) メソッドおよび `addEvent()` (TypeScript) メソッドは非推奨となりました。このデータは代わりに属性で記録してください。
</Note>

<h2 id="set-attributes-on-every-span-in-a-conversation">
  会話内のすべてのスパンに属性を設定する
</h2>

スパン固有のメタデータであれば、スパンごとに属性を付与する方法が適しています。ただし、メタデータの中には会話全体に適用されるものもあります。会話が出力するすべてのスパンに同じ属性を適用するには、会話の開始時に `attributes` を渡します。この方法は、デプロイメント名や環境など、会話全体に共通するメタデータを伝播させる場合に便利です。

<Tabs>
  <Tab title="Python">
    ```python lines theme={"system"}
    from coreweave.forge.agentlens import tracing

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

    conversation = tracing.start_conversation(
        agent_name="my-agent",
        attributes={"deployment": "canary", "env": "production"},
    )
    # この会話内のすべてのターン、LLM、ツール、サブエージェントのスパンに、これらの属性が付与されます。
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript lines theme={"system"}
    import { tracing } from '@coreweave/forge-sdk/agentlens';

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

    await tracing.runIsolated(async () => {
      const conversation = tracing.startConversation({
        agentName: 'my-agent',
        attributes: { deployment: 'canary', env: 'production' },
      });
      // この会話内のすべてのターン、LLM、ツール、サブエージェントのスパンに、これらの属性が付与されます。
    });
    ```
  </Tab>
</Tabs>

<Note>
  スパンごとの属性と同様に、会話の属性には独自のカスタムキーを使用してください。エージェント名、会話名、モデルなどのセマンティック規約フィールドは、`attributes` ではなく、専用の型付きパラメーター (`agent_name`、`conversation_name`、`model`) で設定してください。また、予約済みの接頭辞 `gen_ai.*` および `weave.*` で始まるキーは使用しないでください。Agent Lens は取り込み時にこれらのキーを型付きフィールドに抽出するため、予約済みキーでのカスタム値の設定はサポートされていません。
</Note>

<h2 id="when-you-can-set-attributes">
  属性を設定できるタイミング
</h2>

属性は、スパンの記録中、つまりスパンの開始後から終了前までの間に設定します。Python では `with` ブロックの内側、TypeScript では `start*()` の後から `end()` の前までが該当します。

まだ開始していないスパン、またはすでに終了したスパンに対して `set_attributes()`(または TypeScript の同等の関数)を呼び出すと、その呼び出しは no-op となり、修正方法を示す警告がログに出力されます。

警告が出力されずに呼び出しが無視されるのは、トレースが初期化されていない場合のみです。

<Tip>
  完了したエージェントのアクティビティを、ライブ実行中ではなく 1 つのバッチでまとめてログする際に属性を付与するには、スパンオブジェクトの宣言済みフィールドに直接値を設定し、そのオブジェクトを `log_turn` または `log_conversation` に渡します。詳しくは、[エージェントのアクティビティをバッチでログする](/ja/products/agent-lens/tracing/batch-logging)を参照してください。
</Tip>

<h2 id="view-and-filter-attributes-in-the-ui">
  UI で属性を表示してフィルターする
</h2>

属性の追加は最初のステップにすぎません。属性が真価を発揮するのは、エージェントのアクティビティの分析に活用したときです。エージェント スパンに属性を付与すると、Agent Lens project の **Conversations** タブで、それらの属性を使ってエージェントの会話をフィルターしたりグループ化したりできます。詳細については、[エージェントのアクティビティを表示する](/ja/products/agent-lens/conversations/view-activity)を参照してください。
