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

# OpenTelemetry スパンを Agents ビューに送信する

> Weave SDK を使用せずに、任意の OpenTelemetry パイプラインから Weave エージェントエンドポイントに OTLP トレースデータを送信します。

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/get-started/opentelemetry" />

W\&B Weave のエージェントの可観測性は [OpenTelemetry (OTel)](https://opentelemetry.io/docs/concepts/) を基盤としており、スパンを **Agents** ビューに取り込む専用の OTLP エンドポイントを提供します。OTel エクスポーターの現在のエンドポイント設定を Weave のエンドポイント設定に置き換えるだけで、OTel でインストルメントされたアプリケーションのスパンの送信先を Weave にすばやく変更できます。このために Weave SDK をインストールする必要はありません。

このページでは、エンドポイントで認証し、スパンを送信する方法を説明します。

<h2 id="authentication">
  認証
</h2>

スパンを次のエンドポイントに送信できます:

* **Path**: `/agents/otel/v1/traces`
* **メソッド**: `POST`
* **Content-Type**: `application/x-protobuf`
* **ベース URL**: Multi-tenant Cloud の場合 `https://trace.wandb.ai`

このエンドポイントは OTLP protobuf ペイロードのみを受け入れます。`opentelemetry-exporter-otlp-proto-http` (Python) や `@opentelemetry/exporter-trace-otlp-proto` (TypeScript) などの protobuf HTTP エクスポーターを使用してください。このエンドポイントは `gzip` および `deflate` のコンテンツエンコーディングもサポートします。

エンドポイントで認証するには、[W\&B APIキー](https://forge.coreweave.com/settings) を `OTLPSpanExporter` の設定に次のいずれかの値で指定してください:

* `wandb-api-key`: W\&B APIキーを値として使用します。
* `Authorization`: ユーザー名を `api`、パスワードを W\&B APIキーとする HTTP Basic 認証を使用します。この形式は、エクスポーターまたはコレクターが標準の認証ヘッダーのみサポートする場合に便利です。

<h2 id="project-routing">
  project のルーティング
</h2>

Weave は、OTel リソース属性またはリクエストヘッダーを使用して、スパンを project にルーティングします。

* **リソース属性** (推奨) : `TracerProvider` リソースで、`wandb.entity` に CoreWeave Forge のチーム名またはユーザー名を、`wandb.project` にプロジェクト名を設定します。
* **`project_id` ヘッダー**: 値を `[YOUR-TEAM]/[YOUR-PROJECT]` に設定します。

両方が存在する場合は、リソース属性が優先されます。entity と project が指定されていないスパンは破棄されます。

<h2 id="shape-spans-for-the-agents-view">
  Agents ビュー向けにスパンを整形する
</h2>

Weave はあらゆる OTel スパンを受け入れ、そのすべての属性を保存しますが、Agents ビューがレンダリングするのは [OTel GenAI セマンティック規約](https://github.com/open-telemetry/semantic-conventions-genai/blob/main/docs/gen-ai/gen-ai-agent-spans.md) に準拠したスパンです。各スパンに `gen_ai.operation.name` を設定して、そのスパンが何を表すかを Weave に伝えます。

| `gen_ai.operation.name` | 表す内容 | レンダリング結果 |
| - | - | - |
| `invoke_agent` | ユーザーとエージェント間の 1 回の完結したやり取り。 | ターン。 |
| `chat` | 言語モデル API への 1 回の呼び出し。 | ターン内の LLM Call。 |
| `execute_tool` | 1 回のツール実行。 | ツール呼び出し。 |

グループ化を制御する属性がほかに 2 つあります。

* `gen_ai.conversation.id`: ターンを会話単位にグループ化します。会話の有効期間中は固定の ID を使用してください。
* `gen_ai.agent.name`: Agents タブで、会話を名前付きのエージェントごとにグループ化します。

`gen_ai.request.model`、`gen_ai.usage.input_tokens`、`gen_ai.usage.output_tokens` など、その他の GenAI セマンティック規約の属性を設定すると、モデル名やトークン数が表示に追加されます。ただし、これらは必須ではありません。これらのスパンが対応するエージェントのデータモデルについては、[エージェントをトレースする](/ja/products/wandb/weave/guides/tracking/trace-agents#the-agent-data-model) を参照してください。

<h2 id="configure-with-environment-variables-only">
  環境変数のみで設定する
</h2>

アプリケーションまたはコレクターが標準の OTel エクスポーター環境変数を読み取る場合は、次の変数を設定するだけで、コードを変更せずにスパンを Weave にルーティングできます。

```bash lines theme={"system"}
export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT="https://trace.wandb.ai/agents/otel/v1/traces"
export OTEL_EXPORTER_OTLP_TRACES_HEADERS="wandb-api-key=$WANDB_API_KEY"
export OTEL_RESOURCE_ATTRIBUTES="wandb.entity=[YOUR-TEAM],wandb.project=[YOUR-PROJECT]"
```

<h2 id="example-emit-agent-spans-without-the-weave-sdk">
  例: Weave SDK を使用せずにエージェント スパンを出力する
</h2>

次の例では、OTel パッケージのみを使用して、最小構成のエージェントのターンをインストルメントします。ターンに対して `invoke_agent` スパン、LLM Call に対して `chat` スパン、ツール呼び出しに対して `execute_tool` スパンを出力し、それらを Weave のエージェントエンドポイントにエクスポートします。

まず、必要な依存関係をインストールします。

<CodeGroup>
  ```bash Python theme={"system"}
  pip install opentelemetry-sdk opentelemetry-exporter-otlp-proto-http
  ```

  ```bash TypeScript theme={"system"}
  npm install @opentelemetry/api @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-base @opentelemetry/resources @opentelemetry/exporter-trace-otlp-proto
  ```
</CodeGroup>

次に、以下のコードで `WANDB_API_KEY`、`ENTITY`、`PROJECT` の値を設定し、実行します。

<CodeGroup>
  ```python Python lines highlight="8,9,14" theme={"system"}
  import os
  from opentelemetry import trace
  from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
  from opentelemetry.sdk import trace as trace_sdk
  from opentelemetry.sdk.resources import Resource
  from opentelemetry.sdk.trace.export import BatchSpanProcessor

  ENTITY = "[YOUR-TEAM]"
  PROJECT = "[YOUR-PROJECT]"

  WEAVE_AGENTS_OTLP_ENDPOINT = "https://trace.wandb.ai/agents/otel/v1/traces"

  # https://forge.coreweave.com/settings でAPIキーを作成します
  WANDB_API_KEY = [YOUR-WANDB-API-KEY]

  exporter = OTLPSpanExporter(
      endpoint=WEAVE_AGENTS_OTLP_ENDPOINT,
      headers={"wandb-api-key": WANDB_API_KEY},
  )

  tracer_provider = trace_sdk.TracerProvider(resource=Resource({
      "wandb.entity": ENTITY,
      "wandb.project": PROJECT,
  }))
  tracer_provider.add_span_processor(BatchSpanProcessor(exporter))
  trace.set_tracer_provider(tracer_provider)

  tracer = trace.get_tracer("my-agent")

  CONVERSATION_ID = "conversation-001"

  # 1つのターン: ユーザーが質問し、エージェントがツールを呼び出してから回答します。
  with tracer.start_as_current_span("invoke_agent my-agent") as turn:
      turn.set_attribute("gen_ai.operation.name", "invoke_agent")
      turn.set_attribute("gen_ai.agent.name", "my-agent")
      turn.set_attribute("gen_ai.conversation.id", CONVERSATION_ID)

      with tracer.start_as_current_span("chat gpt-4o") as llm:
          llm.set_attribute("gen_ai.operation.name", "chat")
          llm.set_attribute("gen_ai.conversation.id", CONVERSATION_ID)
          llm.set_attribute("gen_ai.request.model", "gpt-4o")
          # 実際のLLM Callに置き換え、トークン使用量を記録します。
          llm.set_attribute("gen_ai.usage.input_tokens", 100)
          llm.set_attribute("gen_ai.usage.output_tokens", 20)

          with tracer.start_as_current_span("execute_tool get_weather") as tool:
              tool.set_attribute("gen_ai.operation.name", "execute_tool")
              tool.set_attribute("gen_ai.conversation.id", CONVERSATION_ID)
              tool.set_attribute("gen_ai.tool.name", "get_weather")
              # 実際のツール実行に置き換えます。

  tracer_provider.shutdown()  # 終了前に保留中のすべてのスパンをフラッシュします。
  ```

  ```typescript TypeScript lines highlight="7,8,13" theme={"system"}
  import { trace } from "@opentelemetry/api";
  import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
  import { BatchSpanProcessor } from "@opentelemetry/sdk-trace-base";
  import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
  import { Resource } from "@opentelemetry/resources";

  const ENTITY = "[YOUR-TEAM]";
  const PROJECT = "[YOUR-PROJECT]";

  const WEAVE_AGENTS_OTLP_ENDPOINT = "https://trace.wandb.ai/agents/otel/v1/traces";

  // https://forge.coreweave.com/settings でAPIキーを作成します。
  const WANDB_API_KEY = [YOUR-WANDB-API-KEY]!;

  const exporter = new OTLPTraceExporter({
    url: WEAVE_AGENTS_OTLP_ENDPOINT,
    headers: { "wandb-api-key": WANDB_API_KEY },
  });

  const provider = new NodeTracerProvider({
    resource: new Resource({
      "wandb.entity": ENTITY,
      "wandb.project": PROJECT,
    }),
    spanProcessors: [new BatchSpanProcessor(exporter)],
  });

  provider.register();

  const tracer = trace.getTracer("my-agent");

  const CONVERSATION_ID = "conversation-001";

  // 1つのターン: ユーザーが質問し、エージェントがツールを呼び出してから回答します。
  tracer.startActiveSpan("invoke_agent my-agent", (turn) => {
    turn.setAttribute("gen_ai.operation.name", "invoke_agent");
    turn.setAttribute("gen_ai.agent.name", "my-agent");
    turn.setAttribute("gen_ai.conversation.id", CONVERSATION_ID);

    tracer.startActiveSpan("chat gpt-4o", (llm) => {
      llm.setAttribute("gen_ai.operation.name", "chat");
      llm.setAttribute("gen_ai.conversation.id", CONVERSATION_ID);
      llm.setAttribute("gen_ai.request.model", "gpt-4o");
      // 実際のLLM Callに置き換え、そのトークン使用量を記録します。
      llm.setAttribute("gen_ai.usage.input_tokens", 100);
      llm.setAttribute("gen_ai.usage.output_tokens", 20);

      tracer.startActiveSpan("execute_tool get_weather", (tool) => {
        tool.setAttribute("gen_ai.operation.name", "execute_tool");
        tool.setAttribute("gen_ai.conversation.id", CONVERSATION_ID);
        tool.setAttribute("gen_ai.tool.name", "get_weather");
        // 実際のツール実行に置き換えます。
        tool.end();
      });

      llm.end();
    });

    turn.end();
  });

  await provider.shutdown(); // 終了前に保留中のすべてのスパンをフラッシュします。
  ```
</CodeGroup>

同じ会話にターンを追加するには、同じ `gen_ai.conversation.id` を持つ `invoke_agent` スパンをさらに出力します。各ターンはそれぞれのトレースのルートスパンであるため、ターン間で親スパンを共有する必要はありません。

アプリケーションがスパンをエクスポートしたら、Weave プロジェクトの **Agents** タブを開きます。


## Related topics

- [OpenTelemetry トレースを Weave に送信する](/ja/products/wandb/weave/guides/tracking/otel.md)
