Skip to main content

Copilot SDK 的 OpenTelemetry 工具

了解如何在 Copilot SDK 应用程序中添加 OpenTelemetry 跟踪。

谁可以使用此功能?

GitHub Copilot SDK 适用于所有 Copilot 计划。

在本文中

注意

          Copilot SDK 当前处于 技术预览版. 功能和可用性可能会发生更改。
          GitHub Copilot SDK 内置支持在 CLI 进程中配置 OpenTelemetry,并在 SDK 和 CLI 之间传播 W3C 跟踪上下文。

有关 Python、Go 和 .NET 中的示例,请参阅 github/copilot-sdk存储库

内置遥测支持

若要选择加入遥测,请在创建客户端时提供一个 TelemetryConfig

TypeScript
import { CopilotClient } from "@github/copilot-sdk";

const client = new CopilotClient({
  telemetry: {
    otlpEndpoint: "http://localhost:4318",
  },
});

TelemetryConfig 选项

选项Node.js说明
OTLP 终结点otlpEndpointOTLP HTTP 终结点 URL
文件路径filePathJSON 行跟踪输出的文件路径
导出程序类型exporterType
          `"otlp-http"` 或 `"file"` |

| 源名称 | sourceName | 仪器范围名称 | | 捕获内容 | captureContent | 是否捕获消息内容 |

跟踪上下文传播

注意

大多数用户不需要这样做。 以上的 TelemetryConfig 就是您从 CLI 收集跟踪所需的全部内容。 跟踪上下文传播是一项高级功能,适用于创建自己的 OpenTelemetry 范围的应用程序,并希望它们与 CLI 跨度在同一分布式跟踪中显示。

SDK 可以在 JSON-RPC 有效负载上传播 W3C 跟踪上下文(traceparent/tracestate),以便应用程序范围和 CLI 跨度链接在一个分布式跟踪中。 例如,当你想要将 SDK 调用显示为请求处理范围的子级时,这非常有用。

有关会话流的详细序列图,请参阅 github/copilot-sdk存储库

SDK 到 CLI (向外)

在客户端选项中提供onGetTraceContext回调。 仅当应用程序已使用 @opentelemetry/api 并且想要将范围与 CLI 的跨度链接时,才需要这样做。 SDK 在 session.createsession.resumesession.send RPC 调用之前先调用此回调:

TypeScript
import { CopilotClient } from "@github/copilot-sdk";
import { propagation, context } from "@opentelemetry/api";

const client = new CopilotClient({
  telemetry: { otlpEndpoint: "http://localhost:4318" },
  onGetTraceContext: () => {
    const carrier: Record<string, string> = {};
    propagation.inject(context.active(), carrier);
    return carrier; // { traceparent: "00-...", tracestate: "..." }
  },
});

CLI 到 SDK(入站)

当 CLI 调用工具处理程序时,来自 CLI 范围的 traceparenttracestate 可用。 由于 SDK 没有 OpenTelemetry 依赖项,因此它们作为对象的原始字符串 ToolInvocation 传递。 如果需要,请手动还原上下文:

TypeScript
import { propagation, context, trace } from "@opentelemetry/api";

session.registerTool(myTool, async (args, invocation) => {
  // Restore the CLI's trace context as the active context
  const carrier = {
    traceparent: invocation.traceparent,
    tracestate: invocation.tracestate,
  };
  const parentCtx = propagation.extract(context.active(), carrier);

  // Create a child span under the CLI's span
  const tracer = trace.getTracer("my-app");
  return context.with(parentCtx, () =>
    tracer.startActiveSpan("my-tool", async (span) => {
      try {
        const result = await doWork(args);
        return result;
      } finally {
        span.end();
      }
    })
  );
});

延伸阅读

  •         [OpenTelemetry 文档中的 OpenTelemetry GenAI 语义约定](https://opentelemetry.io/docs/specs/semconv/gen-ai/)
    
  •         [OpenTelemetry 文档中的 OpenTelemetry MCP 语义约定](https://opentelemetry.io/docs/specs/semconv/gen-ai/mcp/)
    
  •         [OpenTelemetry 文档中的 OpenTelemetry Python SDK](https://opentelemetry.io/docs/instrumentation/python/)