跳到正文
DEV Community· ExtensionBooster·· 2 小時前AI 評分62

如何用 OpenTelemetry 監測 Node.js 後端的 LLM 呼叫

LLM observability with OpenTelemetry for Node.js backends

AI 導讀

OpenTelemetry 可在 Node.js 後端將 OpenAI、Claude 和 Gemini 的每次模型呼叫記為一個 CLIENT span,並以標準 gen_ai.* 屬性追蹤。

正文

Originally published on Extenify.

LLM observability starts with a simple question your logs probably can't answer yet: which feature, prompt and model made that slow, expensive or failed call? If your extension or app talks to OpenAI, Claude and Gemini from a Node.js backend, OpenTelemetry gives you one vendor-neutral way to trace all three. Here is the short version of how to set it up without double-counting tokens or leaking user data.

One span per model call

The OpenTelemetry GenAI semantic conventions boil down to a single rule: every model call becomes one CLIENT span, named {operation} {model} (for example chat claude-...), carrying a standard set of gen_ai.* attributes. Because the names are standard, any OTLP-compatible backend can store and query them.

The attributes worth setting on every call:

Purpose Attributes
Who and what gen_ai.provider.name, gen_ai.operation.name, gen_ai.request.model, gen_ai.response.model
Result gen_ai.response.id, gen_ai.response.finish_reasons, error.type
Usage gen_ai.usage.input_tokens, gen_ai.usage.output_tokens, gen_ai.usage.cache_read.input_tokens, gen_ai.usage.reasoning.output_tokens
Context server.address, gen_ai.conversation.id, gen_ai.prompt.name, gen_ai.prompt.version

Two counting rules trip people up:

  • Input tokens include cached tokens. A response with 12 uncached and 100 cached input tokens should record input_tokens = 112.
  • Reasoning tokens count as output tokens.

Raw usage fields from providers don't always follow these rules, so normalize them before writing the span.

Claude: let the SDK do it

From version 0.134.0 of the Claude TypeScript SDK (@anthropic-ai/sdk), spans are emitted automatically as soon as your app registers a global tracer provider. Setup is a few lines with @opentelemetry/sdk-trace-node and @opentelemetry/exporter-trace-otlp-proto, loaded before the rest of your code.

A few details matter:

  • Content capture defaults to metadata_only, so prompts and responses stay out of spans unless you opt in.
  • Tracing can be switched off per client or with an environment variable.
  • You can also enable API-side spans in the Claude Console. If you do, count Claude tokens from one source only (SDK spans or API spans), or your dashboards will show double usage.

Pin the SDK version once you upgrade, so a dependency bump doesn't silently change your traces.

OpenAI and Gemini: a small wrapper

The official @opentelemetry/instrumentation-openai package covers openai from 4.19.0 up to, but not including, version 7. On the 7.x SDK, and for Gemini, you add spans yourself. A wrapper with @opentelemetry/api keeps it tidy:

import { trace, SpanKind, SpanStatusCode } from "@opentelemetry/api";

const tracer = trace.getTracer("llm");

export async function tracedCall({ provider, model, feature, promptVersion }, call, readUsage) {
  return tracer.startActiveSpan(`chat ${model}`, { kind: SpanKind.CLIENT }, async (span) => {
    span.setAttributes({
      "gen_ai.provider.name": provider,
      "gen_ai.operation.name": "chat",
      "gen_ai.request.model": model,
      "app.feature": feature,
      "app.prompt_version": promptVersion,
    });
    try {
      const res = await call();
      span.setAttributes(readUsage(res)); // map provider fields to gen_ai.usage.*
      return res;
    } catch (err) {
      span.setAttribute("error.type", String(err.status ?? err.name));
      span.setStatus({ code: SpanStatusCode.ERROR });
      throw err;
    } finally {
      span.end();
    }
  });
}

Write one readUsage function per provider, since each API reports tokens differently. In the original tests, a 429 surfaced as error.type: rate_limit_error for Claude and "429" for OpenAI through the wrapper, so expect provider-specific values there too.

Your own attributes, and what to leave out

Custom attributes like app.feature, app.plan, app.user_id and app.prompt_version are what turn raw traces into answers ("the summarize feature on the free plan costs the most"). Add them on every call.

What you should not add: prompts and responses. Keep content capture off in production by default, especially when the input is user content such as reviews or emails.

From traces to dashboards

Once spans flow, build five dashboards and two alerts:

  1. Latency per model
  2. Tokens per feature
  3. Cache hit rate
  4. Errors
  5. Truncation (finish reasons)

Alerts: error rate, and daily tokens per feature, which catches runaway cost before the invoice does.

Key takeaways

  • Model every LLM call as one CLIENT span with standard gen_ai.* attributes.
  • Count cached tokens inside input tokens and reasoning tokens inside output tokens.
  • Claude's SDK traces itself from 0.134.0; OpenAI 7.x and Gemini need a small wrapper.
  • Count Claude tokens from SDK spans or API spans, never both.
  • Tag spans with feature and prompt version, and keep user content out of traces.

The full walkthrough, with the complete setup for each provider and a rollout checklist, is in Extenify's guide to LLM observability with OpenTelemetry for OpenAI, Claude and Gemini. If you also ship browser extensions or mobile apps, Extenify tracks your store ratings, reviews and versions alongside this kind of backend telemetry.

How are you tracking LLM cost and latency per feature today: OpenTelemetry, a vendor SDK, or plain logs?

來源:DEV Community · dev.to