Skip to content

refactor(instrumentation-anthropic): use genai-util TelemetryHandler - #3916

Open
eternalcuriouslearner wants to merge 5 commits into
open-telemetry:mainfrom
eternalcuriouslearner:feat/anthropic-telemetry-handler
Open

eternalcuriouslearner wants to merge 5 commits into
open-telemetry:mainfrom
eternalcuriouslearner:feat/anthropic-telemetry-handler

Conversation

@eternalcuriouslearner

Copy link
Copy Markdown
Contributor

Which problem is this PR solving?

@opentelemetry/instrumentation-anthropic builds its spans by hand. This PR switches it to the shared TelemetryHandler from @opentelemetry/genai-util, which instrumentation-langchain already uses. Anthropic calls then get the same GenAI attributes and metrics as other instrumentations, and the duplicated span-ending and stream-wrapping code can go.

Short description of the changes

  • Adds a dependency on @opentelemetry/genai-util.
  • Each messages.create() call is tracked by the handler: it starts an inference call, the request runs inside invocation.withContext(), and the call ends with stop() or fail(). Handling of the lazy APIPromise results and of aborts is unchanged.
  • Raw streams go through handler.wrapAsyncStream, which is attached at Stream.iterator() so streams copied with tee() are still tracked. A stream that ends because of an abort is recorded as a failure (APIUserAbortError).
  • messages.stream() keeps using the helper's own end events to decide whether the call succeeded. Its stream events feed chunk timing and response data.
  • Adds src/utils.ts, with request-option mapping and a ResponseRecorder that merges usage across stream events. The old hand-written span, error and stream helpers are removed.
  • genai-util is not changed.

Telemetry changes

The span name, kind, operation, provider, request model and error.type values stay the same.

  • New span attributes:
    • Request settings: gen_ai.request.max_tokens, temperature, top_p, top_k, stop_sequences and stream.
    • Response data: gen_ai.response.id, gen_ai.response.model and gen_ai.response.finish_reasons. Finish reasons are Anthropic's raw values, such as end_turn.
    • Token usage: gen_ai.usage.input_tokens and output_tokens, plus cache read/write tokens. Input tokens include cached tokens, as the spec defines them.
    • gen_ai.response.time_to_first_chunk on streams.
  • New metrics: call duration (gen_ai.client.operation.duration), token usage, and chunk timing for streams.
  • Error status: a generic failure no longer copies error.message into the span status, so sensitive text can't leak.
  • error.type: an error's code is now used first when it has one, so plain Node errors report values like ECONNRESET.
  • Failed calls: every failed call gets finish_reasons: ['error']. So does a stream that ends without a stop reason.
  • Schema URL: the tracer and meter now carry the GenAI schema URL.
  • Content capture: still off.

Not included in this PR

Message content capture, server.address/server.port, and mapping Anthropic stop reasons onto genai-util's names.

Checklist

  • Ran npm run compile, eslint, prettier, markdownlint, lint:readme and knip
  • Tests: 42 passing (7 new), and one existing expectation updated for the new response and usage attributes
  • Updated the README, which previously said response attributes and metrics were out of scope

🤖 Generated with Claude Code

@opentelemetry-pr-dashboard

opentelemetry-pr-dashboard Bot commented Nov 14, 2026 •

Copy link
Copy Markdown

Pull request dashboard status

Waiting on the author · refreshed 2026-11-25 01:08 UTC

Respond to 1 review item (e.g. link a commit, explain why not, ask a follow-up):

  • Top-level threads: 1
Status above doesn't look right?
  • Just replied or pushed? Anything around or after the refresh time above may not be picked up yet — give it a few minutes.
  • Should this be with reviewers? Comment /dashboard route:reviewers to route it to them.
  • Anything wrong — including the routing? Report it with what you expected; it helps us improve the dashboard.

…ener throws

A listener that throws inside the helper's `_emit` skipped span completion
for `end`, and for `finalMessage`/`error`/`abort` it escaped before the SDK
emitted `end` at all, leaving the span open forever. Complete the invocation
in a `finally` instead.

Also let the genai-util stream wrapper alone record raw-stream iterator
failures, and reuse `isRecord` for the params check.

@sangwoorhie sangwoorhie left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked against current main (a209d83): both commits cherry-pick cleanly and the anthropic tests pass (44), both on main alone and on top of #3917.

One gap related to #3917: the existing test ends the span when a streaming response is read via asResponse checks the span status but not the finish reasons, so it passes either way. Before this PR the instrumentation didn't set finish reasons at all, so it didn't need to; now it does. With this assertion added after the status check, the test passes on top of #3917 and fails on main alone with Received: ["error"], which is the case #3917 describes:

expect(
  spans[0].attributes['gen_ai.response.finish_reasons']
).toBeUndefined();

So if this PR lands before #3917, asResponse() streams would report finish_reasons: ['error'] on successful spans until #3917 is in. Adding the assertion would lock in the intended behaviour, with #3917 merged first or this PR rebased on it.

I focused on the stream and asResponse() paths and haven't gone through the rest of the refactor in detail, so I'm leaving this as a comment rather than an approval.

…assifying aborts

A single `awaitingNext` flag was cleared by the first of several outstanding `next()` calls to settle, so an SDK abort for an SSE `error` event during a later read was recorded as `APIUserAbortError`. Count pending reads instead.
…the stream is observed

`requestOptions.stream: true` alone made a successful `stop()` report
`gen_ai.response.finish_reasons: ['error']`. A caller that requests a stream
but never reads it through the invocation (e.g. hands the raw HTTP response
to the user) has no finish reason to report, so the span claimed an error
for a successful call.

The `['error']` default now applies only after the stream has been observed
via `setStreaming()`, which the stream wrapper and `recordStreamChunk()`
call. Early breaks, empty wrapped streams and failures are unchanged.
@opentelemetry-pr-dashboard

Copy link
Copy Markdown

Hi @eternalcuriouslearner — just a friendly reminder that this pull request is waiting on you. The dashboard status comment has the open items and is kept current.

  • Replying is enough to hand it off — answer, explain why no change is needed, or ask a follow-up. The dashboard routes it onward once nothing on the list is waiting on you.
  • To hand it back for any other reason, including the dashboard getting this wrong, comment /dashboard route:reviewers.

@sangwoorhie sangwoorhie left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-checked the new commits on top of current main (9782c55). All five commits cherry-pick cleanly, and instrumentation-anthropic has 45 passing.

  • 5f4079f (concurrent reads): reverting only its src/instrumentation.ts change makes the new test fail with Expected: not "APIUserAbortError", so it covers the case raised in the inline comment above.
  • 57d7902 (asResponse): reverting only the genai-util change from cca873e (packages/genai-util/src/invocations/inference.ts) makes the asResponse test fail with ["error"], which is the case I mentioned earlier. With the change, gen_ai.response.finish_reasons stays unset.

cca873e has the same patch as #3917 (git patch-id matches), so the merge-order dependency I raised is no longer an issue: this PR is safe whether #3917 lands first or not.

Scope: I only re-ran the anthropic unit tests and the two checks above. I didn't re-run genai-util's own tests or an end-to-end run against the real SDK this time.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants