{"meta":{"title":"Copilot SDK 用の OpenTelemetry インストルメンテーション","intro":"このガイドでは、OpenTelemetry トレースを Copilot SDK アプリケーションに追加する方法について説明します。","product":"GitHub Copilot","breadcrumbs":[{"href":"/ja/copilot","title":"GitHub Copilot"},{"href":"/ja/copilot/how-tos","title":"方法"},{"href":"/ja/copilot/how-tos/copilot-sdk","title":"Copilot SDK"},{"href":"/ja/copilot/how-tos/copilot-sdk/observability","title":"可観測性"},{"href":"/ja/copilot/how-tos/copilot-sdk/observability/opentelemetry","title":"Opentelemetry"}],"documentType":"article"},"body":"# Copilot SDK 用の OpenTelemetry インストルメンテーション\n\nこのガイドでは、OpenTelemetry トレースを Copilot SDK アプリケーションに追加する方法について説明します。\n\n<!-- markdownlint-disable GHD046 GHD005 -->\n\n<!-- Suppressed: GHD046 (outdated release terminology), GHD005 (hardcoded data variable) -->\n\n## 組み込みのテレメトリのサポート\n\nSDK には、CLI プロセスで OpenTelemetry を構成し、SDK と CLI の間で W3C トレース コンテキストを伝達するためのサポートが組み込まれています。 オプトインするクライアントを作成するときに `TelemetryConfig` を指定します。\n\n<div class=\"ghd-codetabs\">\n<div class=\"ghd-codetab\" data-lang=\"typescript\" data-label=\"TypeScript\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">TypeScript</div>\n\n<!-- docs-validate: skip -->\n\n```typescript\nimport { CopilotClient } from \"@github/copilot-sdk\";\n\nconst client = new CopilotClient({\n  telemetry: {\n    otlpEndpoint: \"http://localhost:4318\",\n  },\n});\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"python\" data-label=\"Python\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Python</div>\n\n<!-- docs-validate: skip -->\n\n```python\nfrom copilot import CopilotClient\n\nclient = CopilotClient(\n    telemetry={\n        \"otlp_endpoint\": \"http://localhost:4318\",\n    },\n)\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"go\" data-label=\"Go\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Go</div>\n\n<!-- docs-validate: skip -->\n\n```golang\nclient := copilot.NewClient(&copilot.ClientOptions{\n    Telemetry: &copilot.TelemetryConfig{\n        OTLPEndpoint: \"http://localhost:4318\",\n    },\n})\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"dotnet\" data-label=\".NET\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">.NET</div>\n\n<!-- docs-validate: skip -->\n\n```csharp\nvar client = new CopilotClient(new CopilotClientOptions\n{\n    Telemetry = new TelemetryConfig\n    {\n        OtlpEndpoint = \"http://localhost:4318\",\n    },\n});\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"java\" data-label=\"Java\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Java</div>\n\n<!-- docs-validate: skip -->\n\n```java\nimport com.github.copilot.CopilotClient;\nimport com.github.copilot.rpc.*;\n\nvar client = new CopilotClient(new CopilotClientOptions()\n    .setTelemetry(new TelemetryConfig()\n        .setOtlpEndpoint(\"http://localhost:4318\"))\n);\n```\n\n</div>\n\n<div class=\"ghd-codetab\" data-lang=\"rust\" data-label=\"Rust\"><div class=\"ghd-codetab-fallback-label\" role=\"heading\" aria-level=\"3\">Rust</div>\n\n<!-- docs-validate: skip -->\n\n```rust\nuse github_copilot_sdk::{Client, ClientOptions, TelemetryConfig};\n\nlet client = Client::start(ClientOptions::new()\n    .with_telemetry(TelemetryConfig::new()\n        .with_otlp_endpoint(\"http://localhost:4318\"))\n).await?;\n```\n\n</div>\n\n</div>\n\n### TelemetryConfig オプション\n\n| オプション                      | Node.js          | Python            | Go               | .NET             | Java             | Rust              | 説明                                                             |\n| -------------------------- | ---------------- | ----------------- | ---------------- | ---------------- | ---------------- | ----------------- | -------------------------------------------------------------- |\n| OTLP エンドポイント               | `otlpEndpoint`   | `otlp_endpoint`   | `OTLPEndpoint`   | `OtlpEndpoint`   | `otlpEndpoint`   | `otlp_endpoint`   | OTLP HTTP エンドポイント URL                                          |\n| OTLP プロトコル                 | `otlpProtocol`   | `otlp_protocol`   | `OTLPProtocol`   | `OtlpProtocol`   | `otlpProtocol`   | `otlp_protocol`   | すべてのシグナルの OTLP HTTP プロトコル: `\"http/json\"` または `\"http/protobuf\"` |\n| ファイルパス                     | `filePath`       | `file_path`       | `FilePath`       | `FilePath`       | `filePath`       | `file_path`       | JSON 行トレース出力のファイル パス                                           |\n| エクスポーターの種類                 | `exporterType`   | `exporter_type`   | `ExporterType`   | `ExporterType`   | `exporterType`   | `exporter_type`   |                                                                |\n| `\"otlp-http\"` または `\"file\"` |                  |                   |                  |                  |                  |                   |                                                                |\n| ソース名                       | `sourceName`     | `source_name`     | `SourceName`     | `SourceName`     | `sourceName`     | `source_name`     | 計装範囲名                                                          |\n| コンテンツをキャプチャする              | `captureContent` | `capture_content` | `CaptureContent` | `CaptureContent` | `captureContent` | `capture_content` | メッセージの内容をキャプチャするかどうか                                           |\n\nOTLP プロトコル フィールドは、すべての信号に対して CLI の `\"otlp-http\"` エクスポーターを構成します。 CLI の既定値を使用するように設定したままにするか、http 経由で protobuf をエクスポートする `\"http/protobuf\"` に設定します。\n\n### トレース コンテキストの伝達\n\n> **ほとんどのユーザーはこれを必要としません。** 上記の `TelemetryConfig` は、CLI からトレースを収集するために必要なすべてです。 このセクションで説明するトレース コンテキスト伝達は、独自の OpenTelemetry スパンを作成し、CLI のスパンと**同じ分散トレース**に表示するアプリケーションの**高度な機能**です。\n\nSDK は、JSON-RPC ペイロードに W3C トレース コンテキスト (`traceparent`/`tracestate`) を伝達できるため、アプリケーションのスパンと CLI のスパンが 1 つの分散トレースにリンクされます。 これは、たとえば、アプリ内の「ツール呼び出しを処理」スパンが CLI の「ツールを実行」スパンの内側に入れ子になった状態で表示したい場合や、SDK 呼び出しをリクエスト処理スパンの子として表示したい場合に便利です。\n\nトレースとあわせてコストの帰属を確認するには、`assistant.usage` イベントを購読し、`apiEndpoint`（`AssistantUsageApiEndpoint`）を確認して、そのターンで Chat Completions、Responses、または Anthropic Messages のいずれが使用されたかを確認します。[ストリーミング セッション イベント](/ja/copilot/how-tos/copilot-sdk/features/streaming-events) を参照してください。\n\n#### SDK → CLI (送信)\n\n**Node.js**の場合は、クライアント オプションに`onGetTraceContext`コールバックを指定します。 これは、アプリケーションで既に `@opentelemetry/api` を使用しており、スパンを CLI のスパンにリンクする場合にのみ必要です。 SDK は、RPC を `session.create`、 `session.resume`、および `session.send` する前に、このコールバックを呼び出します。\n\n<!-- docs-validate: skip -->\n\n```typescript\nimport { CopilotClient } from \"@github/copilot-sdk\";\nimport { propagation, context } from \"@opentelemetry/api\";\n\nconst client = new CopilotClient({\n  telemetry: { otlpEndpoint: \"http://localhost:4318\" },\n  onGetTraceContext: () => {\n    const carrier: Record<string, string> = {};\n    propagation.inject(context.active(), carrier);\n    return carrier; // { traceparent: \"00-...\", tracestate: \"...\" }\n  },\n});\n```\n\n**Python**、**Go**、および **.NET** では、それぞれの OpenTelemetry/Activity API が構成されている場合、トレース コンテキストの挿入は自動的に行われます。コールバックは必要ありません。\n\n#### CLI → SDK（インバウンド）\n\nCLI がツール ハンドラーを呼び出すと、CLI のスパンからの `traceparent` と `tracestate` は、すべての言語で使用できます。\n\n* **Go**: `ToolInvocation.TraceContext` フィールドは、すでに復元されたトレースを含む `context.Context` です。これをスパンの親としてそのまま使用してください。\n* **Python**: トレース コンテキストは、`trace_context()` を介してハンドラーの周囲に自動的に復元されます。子スパンは CLI のスパンに自動的に親されます。\n* **.NET**: トレース コンテキストは自動的に復元され、`RestoreTraceContext()`子`Activity`インスタンスは自動的に CLI のスパンに紐付けられます。\n* **Node.js**: SDK には OpenTelemetry 依存関係がないため、 `traceparent` と `tracestate` は、 `ToolInvocation` オブジェクトに生の文字列として渡されます。 必要に応じて、コンテキストを手動で復元します。\n\n<!-- docs-validate: skip -->\n\n```typescript\nimport { defineTool } from \"@github/copilot-sdk\";\nimport { propagation, context, trace } from \"@opentelemetry/api\";\n\nconst myTool = defineTool(\"my-tool\", {\n  description: \"Do work\",\n  handler: async (args, invocation) => {\n    // Restore the CLI's trace context as the active context\n    const carrier = {\n      traceparent: invocation.traceparent,\n      tracestate: invocation.tracestate,\n    };\n    const parentCtx = propagation.extract(context.active(), carrier);\n\n    // Create a child span under the CLI's span\n    const tracer = trace.getTracer(\"my-app\");\n    return context.with(parentCtx, () =>\n      tracer.startActiveSpan(\"my-tool\", async (span) => {\n        try {\n          const result = await doWork(args);\n          return result;\n        } finally {\n          span.end();\n        }\n      })\n    );\n  },\n});\n\n// Tool handlers are registered when the session is created.\nconst session = await client.createSession({ tools: [myTool] });\n```\n\n### 言語ごとの依存関係\n\n| Language | 依存関係                                 | メモ                                                                                               |\n| -------- | ------------------------------------ | ------------------------------------------------------------------------------------------------ |\n| Node.js  | —                                    | 依存関係なし。外向き伝播用の`onGetTraceContext`コールバックを提供する                                                     |\n| Python   | `opentelemetry-api`                  | を使用してインストールする `pip install copilot-sdk[telemetry]`                                               |\n| Go       | `go.opentelemetry.io/otel`           | 必要な依存関係                                                                                          |\n| .NET     | —                                    | 組み込みの `System.Diagnostics.Activity` を使用する                                                        |\n| Java     | `io.opentelemetry:opentelemetry-api` | SDK ベースのセットアップにこの依存関係を追加します。OpenTelemetry Java エージェントまたは SDK が構成されている場合、トレース コンテキストの挿入は自動的に行われます |\n\n## References\n\n* [OpenTelemetry GenAI セマンティック規則](https://opentelemetry.io/docs/specs/semconv/gen-ai/)\n* [OpenTelemetry MCP セマンティック規則](https://opentelemetry.io/docs/specs/semconv/gen-ai/mcp/)\n* [OpenTelemetry Python SDK](https://opentelemetry.io/docs/instrumentation/python/)\n* [Copilot SDK ドキュメント](https://github.com/github/copilot-sdk)"}