Repository navigation
refactor(instrumentation-anthropic): use genai-util TelemetryHandler - #3916
eternalcuriouslearner wants to merge 5 commits into
Conversation
Pull request dashboard statusWaiting 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):
Status above doesn't look right?
|
…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
left a comment
There was a problem hiding this comment.
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.
|
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.
|
sangwoorhie
left a comment
There was a problem hiding this comment.
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.tschange makes the new test fail withExpected: 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 theasResponsetest fail with["error"], which is the case I mentioned earlier. With the change,gen_ai.response.finish_reasonsstays 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.
Which problem is this PR solving?
@opentelemetry/instrumentation-anthropicbuilds its spans by hand. This PR switches it to the sharedTelemetryHandlerfrom@opentelemetry/genai-util, whichinstrumentation-langchainalready 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
@opentelemetry/genai-util.messages.create()call is tracked by the handler: it starts an inference call, the request runs insideinvocation.withContext(), and the call ends withstop()orfail(). Handling of the lazyAPIPromiseresults and of aborts is unchanged.handler.wrapAsyncStream, which is attached atStream.iterator()so streams copied withtee()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.src/utils.ts, with request-option mapping and aResponseRecorderthat merges usage across stream events. The old hand-written span, error and stream helpers are removed.genai-utilis not changed.Telemetry changes
The span name, kind, operation, provider, request model and
error.typevalues stay the same.gen_ai.request.max_tokens,temperature,top_p,top_k,stop_sequencesandstream.gen_ai.response.id,gen_ai.response.modelandgen_ai.response.finish_reasons. Finish reasons are Anthropic's raw values, such asend_turn.gen_ai.usage.input_tokensandoutput_tokens, plus cache read/write tokens. Input tokens include cached tokens, as the spec defines them.gen_ai.response.time_to_first_chunkon streams.gen_ai.client.operation.duration), token usage, and chunk timing for streams.error.messageinto the span status, so sensitive text can't leak.error.type: an error'scodeis now used first when it has one, so plain Node errors report values likeECONNRESET.finish_reasons: ['error']. So does a stream that ends without a stop reason.Not included in this PR
Message content capture,
server.address/server.port, and mapping Anthropic stop reasons onto genai-util's names.Checklist
npm run compile, eslint, prettier, markdownlint,lint:readmeand knip🤖 Generated with Claude Code