> ## Documentation Index
> Fetch the complete documentation index at: https://wb-21fd5541-feature-automate-reference-docs-generation.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Otel

## 概要

Weaveは専用エンドポイントを通じてOpenTelemetry互換のトレースデータの取り込みをサポートしています。このエンドポイントを使用すると、OTLP（OpenTelemetryプロトコル）形式のトレースデータをWeaveプロジェクトに直接送信できます。

## エンドポイントの詳細

**パス**: `/otel/v1/traces`
**Method**: POST
**Content-Type**: `application/x-protobuf`

## Authentication

標準のW\&B認証が使用されます。トレースデータを送信するプロジェクトに対する書き込み権限が必要です。

## 必須ヘッダー

* `project_id: <your_entity>/<your_project_name>`
* `Authorization=Basic <Base64 Encoding of api:$WANDB_API_KEY>`

## Examples:

以下のコードサンプルを実行する前に、次のフィールドを変更する必要があります：

1. `WANDB_API_KEY`: これは以下から取得できます [https://wandb.ai/authorize](https://wandb.ai/authorize)。
2. Entity: You can only log traces to the project under an entity that you have access to. You can find your entity name by visiting your W\&N dashboard at \[[https://wandb.ai/home](https://wandb.ai/home)], そして左サイドバーの **Teams** フィールドを確認します。
3. プロジェクト名: 楽しい名前を選んでください！
4. `OPENAI_API_KEY`: これは [OpenAI dashboard](https://platform.openai.com/api-keys)から取得できます。

### OpenInference インストルメンテーション:

この例ではOpenAIインストルメンテーションの使用方法を示しています。公式リポジトリで利用可能な他の多くのインストルメンテーションがあります: [https://github.com/Arize-ai/openinference](https://github.com/Arize-ai/openinference)

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

```bash
pip install openai openinference-instrumentation-openai opentelemetry-exporter-otlp-proto-http
```

次に、以下のコードをPythonファイル（例えば `openinference_example.py`

```python
import base64
import openai
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk import trace as trace_sdk
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
from openinference.instrumentation.openai import OpenAIInstrumentor

OPENAI_API_KEY="YOUR_OPENAI_API_KEY"
WANDB_BASE_URL = "https://trace.wandb.ai"
PROJECT_ID = "<your-entity>/<your-project>"

OTEL_EXPORTER_OTLP_ENDPOINT = f"{WANDB_BASE_URL}/otel/v1/traces"

# Can be found at https://wandb.ai/authorize
WANDB_API_KEY = "<your-wandb-api-key>"
AUTH = base64.b64encode(f"api:{WANDB_API_KEY}".encode()).decode()

OTEL_EXPORTER_OTLP_HEADERS = {
    "Authorization": f"Basic {AUTH}",
    "project_id": PROJECT_ID,
}

tracer_provider = trace_sdk.TracerProvider()

# Configure the OTLP exporter
exporter = OTLPSpanExporter(
    endpoint=OTEL_EXPORTER_OTLP_ENDPOINT,
    headers=OTEL_EXPORTER_OTLP_HEADERS,
)

# Add the exporter to the tracer provider
tracer_provider.add_span_processor(SimpleSpanProcessor(exporter))

# Optionally, print the spans to the console.
tracer_provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))

OpenAIInstrumentor().instrument(tracer_provider=tracer_provider)

def main():
    client = openai.OpenAI(api_key=OPENAI_API_KEY)
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[{"role": "user", "content": "Describe OTEL in a single sentence."}],
        max_tokens=20,
        stream=True,
        stream_options={"include_usage": True},
    )
    for chunk in response:
        if chunk.choices and (content := chunk.choices[0].delta.content):
            print(content, end="")

if __name__ == "__main__":
    main()
```

最後に、上記で指定したフィールドを正しい値に設定したら、コードを実行します：

```bash
python openinference_example.py
```

### OpenLLMetry インストルメンテーション:

以下の例ではOpenAIインストルメンテーションの使用方法を示しています。追加の例は [https://github.com/traceloop/openllmetry/tree/main/packages](https://github.com/traceloop/openllmetry/tree/main/packages)で利用可能です。

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

```bash
pip install openai opentelemetry-instrumentation-openai opentelemetry-exporter-otlp-proto-http
```

次に、以下のコードをPythonファイル（例えば `openllmetry_example.py`）に貼り付けます。これは上記と同じコードですが、 `OpenAIInstrumentor` は `opentelemetry.instrumentation.openai` からではなく `openinference.instrumentation.openai`

```python
import base64
import openai
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk import trace as trace_sdk
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
from opentelemetry.instrumentation.openai import OpenAIInstrumentor

OPENAI_API_KEY="YOUR_OPENAI_API_KEY"
WANDB_BASE_URL = "https://trace.wandb.ai"
PROJECT_ID = "<your-entity>/<your-project>"

OTEL_EXPORTER_OTLP_ENDPOINT = f"{WANDB_BASE_URL}/otel/v1/traces"

# Can be found at https://wandb.ai/authorize
WANDB_API_KEY = "<your-wandb-api-key>"
AUTH = base64.b64encode(f"api:{WANDB_API_KEY}".encode()).decode()

OTEL_EXPORTER_OTLP_HEADERS = {
    "Authorization": f"Basic {AUTH}",
    "project_id": PROJECT_ID,
}

tracer_provider = trace_sdk.TracerProvider()

# Configure the OTLP exporter
exporter = OTLPSpanExporter(
    endpoint=OTEL_EXPORTER_OTLP_ENDPOINT,
    headers=OTEL_EXPORTER_OTLP_HEADERS,
)

# Add the exporter to the tracer provider
tracer_provider.add_span_processor(SimpleSpanProcessor(exporter))

# Optionally, print the spans to the console.
tracer_provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))

OpenAIInstrumentor().instrument(tracer_provider=tracer_provider)

def main():
    client = openai.OpenAI(api_key=OPENAI_API_KEY)
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[{"role": "user", "content": "Describe OTEL in a single sentence."}],
        max_tokens=20,
        stream=True,
        stream_options={"include_usage": True},
    )
    for chunk in response:
        if chunk.choices and (content := chunk.choices[0].delta.content):
            print(content, end="")

if __name__ == "__main__":
    main()
```

最後に、上記で指定したフィールドを正しい値に設定したら、コードを実行します：

```bash
python openllmetry_example.py
```

### インストルメンテーションなしの場合

インストルメンテーションパッケージの代わりにOTELを直接使用したい場合は、そうすることもできます。スパン属性は [https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-spans/](https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-spans/)で説明されているOpenTelemetryセマンティック規約に従って解析されます。

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

```bash
pip install openai opentelemetry-sdk opentelemetry-api opentelemetry-exporter-otlp-proto-http
```

次に、以下のコードをPythonファイル（例えば `opentelemetry_example.py`

```python
import json
import base64
import openai
from opentelemetry import trace
from opentelemetry.sdk import trace as trace_sdk
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor

OPENAI_API_KEY = "YOUR_OPENAI_API_KEY"
WANDB_BASE_URL = "https://trace.wandb.ai"
PROJECT_ID = "<your-entity>/<your-project>"

OTEL_EXPORTER_OTLP_ENDPOINT = f"{WANDB_BASE_URL}/otel/v1/traces"

# Can be found at https://wandb.ai/authorize
WANDB_API_KEY = "<your-wandb-api-key>"
AUTH = base64.b64encode(f"api:{WANDB_API_KEY}".encode()).decode()

OTEL_EXPORTER_OTLP_HEADERS = {
    "Authorization": f"Basic {AUTH}",
    "project_id": PROJECT_ID,
}

tracer_provider = trace_sdk.TracerProvider()

# Configure the OTLP exporter
exporter = OTLPSpanExporter(
    endpoint=OTEL_EXPORTER_OTLP_ENDPOINT,
    headers=OTEL_EXPORTER_OTLP_HEADERS,
)

# Add the exporter to the tracer provider
tracer_provider.add_span_processor(SimpleSpanProcessor(exporter))

# Optionally, print the spans to the console.
tracer_provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))

trace.set_tracer_provider(tracer_provider)
# Creates a tracer from the global tracer provider
tracer = trace.get_tracer(__name__)
tracer.start_span('name=standard-span')

def my_function():
    with tracer.start_as_current_span("outer_span") as outer_span:
        client = openai.OpenAI()
        input_messages=[{"role": "user", "content": "Describe OTEL in a single sentence."}]
        # This will only appear in the side panel
        outer_span.set_attribute("input.value", json.dumps(input_messages))
        # This follows conventions and will appear in the dashboard
        outer_span.set_attribute("gen_ai.system", 'openai')
        response = client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=input_messages,
            max_tokens=20,
            stream=True,
            stream_options={"include_usage": True},
        )
        out = ""
        for chunk in response:
            if chunk.choices and (content := chunk.choices[0].delta.content):
                out += content
        # This will only appear in the side panel
        outer_span.set_attribute("output.value", json.dumps({"content": out}))

if __name__ == "__main__":
    my_function()
```

最後に、上記で指定したフィールドを正しい値に設定したら、コードを実行します：

```bash
python opentelemetry_example.py
```

スパン属性のプレフィックス `gen_ai` および `openinference` は、トレースを解釈する際にどの規約を使用するか（もしあれば）を決定するために使用されます。どちらのキーも検出されない場合、すべてのスパン属性がトレースビューで表示されます。トレースを選択すると、サイドパネルで完全なスパンが利用可能です。
