diff --git a/package-lock.json b/package-lock.json index ca55374ba4..47ccde18b9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -37655,6 +37655,7 @@ "license": "Apache-2.0", "dependencies": { "@opentelemetry/core": "^3.0.0", + "@opentelemetry/genai-util": "^0.5.0", "@opentelemetry/instrumentation": "^0.301.0" }, "devDependencies": { diff --git a/packages/genai-util/src/invocations/inference.ts b/packages/genai-util/src/invocations/inference.ts index 206ab9e093..ca10638485 100644 --- a/packages/genai-util/src/invocations/inference.ts +++ b/packages/genai-util/src/invocations/inference.ts @@ -127,7 +127,13 @@ export class InferenceInvocation extends BaseInvocation { private readonly _serverAddress?: string; private readonly _serverPort?: number; private readonly _contentCaptureMode: ContentCaptureMode; - private _isStreaming: boolean; + /** + * Whether the response was observed as a stream, through {@link setStreaming} + * (called by the stream wrapper and {@link recordStreamChunk}). Requesting a + * stream alone does not set it: a caller that never reads the stream has no + * finish reason to report, missing or otherwise. + */ + private _isStreaming = false; private _responseModel?: string; private _finishReasons?: FinishReason[]; private _usage?: TokenUsageDetails; @@ -159,7 +165,6 @@ export class InferenceInvocation extends BaseInvocation { this._requestModel = options.requestModel; this._serverAddress = options.serverAddress; this._serverPort = options.serverPort; - this._isStreaming = options.requestOptions?.stream === true; this._contentCaptureMode = handler.getContentCaptureMode(); this._inputMessages = options.inputMessages ? [...options.inputMessages] @@ -171,6 +176,7 @@ export class InferenceInvocation extends BaseInvocation { * Set the request streaming attribute to true. * * This is a convenience method for the case when the user is streaming the response. + * Once called, a stream that ends without a finish reason reports `'error'`. */ public setStreaming(): this { this.setAttribute(ATTR_GEN_AI_REQUEST_STREAM, true); @@ -360,9 +366,10 @@ export class InferenceInvocation extends BaseInvocation { _endTime: HrTime, errorType?: string ): void { - // Avoids putting ['error'] on a successful non-streaming span when - // setFinishReasons() wasn't called, while still defaulting to ['error'] if - // a stream ends early (e.g. break before the final chunk) or if fail() is called. + // Avoids putting ['error'] on a successful span when setFinishReasons() + // wasn't called and no stream was observed, while still defaulting to + // ['error'] if an observed stream ends early (e.g. break before the final + // chunk) or if fail() is called. if ( this._finishReasons !== undefined || errorType !== undefined || diff --git a/packages/genai-util/test/invocations/inference.test.ts b/packages/genai-util/test/invocations/inference.test.ts index 6f5845d17d..710b246061 100644 --- a/packages/genai-util/test/invocations/inference.test.ts +++ b/packages/genai-util/test/invocations/inference.test.ts @@ -541,6 +541,47 @@ describe('InferenceInvocation', () => { ); }); + it('should default finish_reasons to error only once a requested stream has been observed', () => { + const handler = new TelemetryHandler({ + instrumentationName: 'test-instrumentation', + instrumentationVersion: '1.0.0', + tracerProvider: ctx.tracerProvider, + }); + const startStreaming = () => + handler.startInference({ + providerName: 'openai', + requestOptions: { stream: true }, + }); + + // The caller took the raw response and never read the stream, so there is + // no finish reason to report. + startStreaming().stop(); + + const observed = startStreaming(); + observed.recordStreamChunk(); + observed.stop(); + + const explicit = startStreaming(); + explicit.setStreaming(); + explicit.stop(); + + startStreaming().fail({ errorType: 'TimeoutError' }); + + const spans = ctx.memoryExporter.getFinishedSpans(); + assert.strictEqual(spans.length, 4); + assert.strictEqual(spans[0].attributes[ATTR_GEN_AI_REQUEST_STREAM], true); + assert.strictEqual( + spans[0].attributes[ATTR_GEN_AI_RESPONSE_FINISH_REASONS], + undefined + ); + for (const span of spans.slice(1)) { + assert.deepStrictEqual( + span.attributes[ATTR_GEN_AI_RESPONSE_FINISH_REASONS], + ['error'] + ); + } + }); + it('should record time to first chunk once and time per output chunk for each later chunk', async () => { const handler = new TelemetryHandler({ instrumentationName: 'test-instrumentation', diff --git a/packages/instrumentation-anthropic/README.md b/packages/instrumentation-anthropic/README.md index a86a5cc7e7..5f7d1189bc 100644 --- a/packages/instrumentation-anthropic/README.md +++ b/packages/instrumentation-anthropic/README.md @@ -30,12 +30,22 @@ instead; see its `openTelemetry` client option. - `anthropic.messages.create({ stream: true })` - `anthropic.messages.stream()` -The current scaffold creates a client span for each call, records the GenAI -provider, operation, and requested model, and marks failed calls as errors. The +Telemetry is produced through the `TelemetryHandler` of +[`@opentelemetry/genai-util`](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/genai-util), which owns each call's span and +metrics. Each call creates a client span that records the GenAI provider, +operation, requested model and request parameters (`max_tokens`, +`temperature`, `top_p`, `top_k`, `stop_sequences`, `stream`), the response id, +model, finish reason and token usage, and marks failed calls as errors. The provider is derived from the client's base URL, so `AnthropicBedrock` and `AnthropicVertex` calls are reported as `aws.bedrock` and `gcp.vertex_ai`. -Response attributes, tools, metrics, logs, and content capture are intentionally -out of scope. + +The GenAI client metrics are recorded for each call: operation duration, input +and output token usage (including prompt cache reads and writes), and, for +streams, time to first chunk and time per output chunk. As with +`gen_ai.usage.input_tokens`, input token counts include prompt cache reads and +writes, which Anthropic reports separately from `input_tokens`. + +Tools, logs, and message content capture are out of scope. The patch is registered on the shared `Messages` resource module rather than on the package root, in both its CommonJS and ESM builds, so it applies however the diff --git a/packages/instrumentation-anthropic/package.json b/packages/instrumentation-anthropic/package.json index e0718ebbba..8c4b689895 100644 --- a/packages/instrumentation-anthropic/package.json +++ b/packages/instrumentation-anthropic/package.json @@ -65,6 +65,7 @@ }, "dependencies": { "@opentelemetry/core": "^3.0.0", + "@opentelemetry/genai-util": "^0.5.0", "@opentelemetry/instrumentation": "^0.301.0" }, "homepage": "https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/instrumentation-anthropic#readme" diff --git a/packages/instrumentation-anthropic/src/instrumentation.ts b/packages/instrumentation-anthropic/src/instrumentation.ts index 6e557739c1..d84d5b6d94 100644 --- a/packages/instrumentation-anthropic/src/instrumentation.ts +++ b/packages/instrumentation-anthropic/src/instrumentation.ts @@ -4,15 +4,23 @@ */ import type Anthropic from '@anthropic-ai/sdk'; -import { context, SpanKind, SpanStatusCode, trace } from '@opentelemetry/api'; -import type { Span } from '@opentelemetry/api'; +import { context } from '@opentelemetry/api'; +import type { MeterProvider, TracerProvider } from '@opentelemetry/api'; import { InstrumentationBase, InstrumentationNodeModuleDefinition, InstrumentationNodeModuleFile, } from '@opentelemetry/instrumentation'; import { isTracingSuppressed } from '@opentelemetry/core'; +import { TelemetryHandler } from '@opentelemetry/genai-util'; import type { AnthropicInstrumentationConfig } from './types'; +import { + getProviderName, + getRequestOptions, + isRecord, + ResponseRecorder, + type InferenceInvocation, +} from './utils'; /** @knipignore */ import { PACKAGE_NAME, PACKAGE_VERSION } from './version'; @@ -30,10 +38,10 @@ const SUPPORTED_VERSIONS = ['>=0.65.0 <0.134.0']; let inMessagesStreamHelper = 0; /** The state of the span the helper just started, handed to `patchedStream`. */ -let pendingHelperState: SpanState | undefined; +let pendingHelperState: CallState | undefined; /** Read and clear it. A function, so its declared return type survives. */ -function takePendingHelperState(): SpanState | undefined { +function takePendingHelperState(): CallState | undefined { const state = pendingHelperState; pendingHelperState = undefined; return state; @@ -55,6 +63,9 @@ interface AnthropicMessageStream { receivedMessages: unknown[]; } +/** `MessageStream` events after which the helper emits `end` and nothing else. */ +const TERMINAL_HELPER_EVENTS = new Set(['finalMessage', 'error', 'abort']); + function isMessageStream(value: unknown): value is AnthropicMessageStream { const candidate = value as AnthropicMessageStream; return ( @@ -68,22 +79,32 @@ interface MessagesModule { Messages: { prototype: Record }; } -interface SpanState { - span: Span; - ended: boolean; +interface CallState { + /** Owns the span and metrics of the call; completes at most once. */ + invocation: InferenceInvocation; + /** Records response metadata and usage onto `invocation`. */ + response: ResponseRecorder; /** - * Set only while an `iterator.next()` call is outstanding. The SDK aborts - * its own controller from inside that call when an SSE `error` event ends - * iteration, so an abort observed in this window belongs to the iterator. + * The number of `iterator.next()` calls still outstanding. The SDK aborts + * its own controller from inside such a call when an SSE `error` event ends + * iteration, so an abort observed while any is pending belongs to the + * iterator. A count rather than a flag, because a caller may issue several + * reads before awaiting any, and the first to settle must not hide the rest. * A suspended iterator (parked at `yield`) is caller-controlled time and is * deliberately excluded, so cancelling there still ends the span. */ - awaitingNext: boolean; + pendingReads: number; /** * Set while the wrapped iterator closes the SDK iterator. `return()` aborts * the controller as ordinary cleanup, which must not read as a cancellation. */ closing: boolean; + /** + * Set when the iteration ended because the caller aborted: the SDK swallows + * abort errors and simply stops yielding, so this is read when the stream + * wrapper finishes to record the abort instead of a success. + */ + aborted: boolean; /** * Set when the call was made by `messages.stream()`. The helper keeps * consuming after the raw stream ends — accumulating events into a final @@ -111,38 +132,7 @@ interface AnthropicAPIPromise extends Promise { function isMessageCreateParams( value: unknown ): value is Anthropic.Messages.MessageCreateParams { - return typeof value === 'object' && value !== null; -} - -/** - * `AnthropicBedrock` and `AnthropicVertex` extend `BaseAnthropic` and reuse the - * core `Messages` resource, so the same patch serves all three. Derive the - * provider from the client's base URL rather than assuming the first-party API. - */ -function getProviderName(client: unknown): string { - const baseURL = (client as { baseURL?: unknown })?.baseURL; - if (typeof baseURL === 'string') { - let host: string; - try { - host = new URL(baseURL).host; - } catch { - return 'anthropic'; - } - if (/\.amazonaws\.com$/.test(host) && host.includes('bedrock')) { - return 'aws.bedrock'; - } - // `AnthropicBedrockMantle` uses `bedrock-mantle..api.aws`. - if (/^bedrock-mantle\.[a-z0-9-]+\.api\.aws$/.test(host)) { - return 'aws.bedrock'; - } - // Regional endpoints are `-aiplatform.googleapis.com`, the global - // endpoint has no region prefix, and the `us` and `eu` multi-region - // endpoints are `aiplatform..rep.googleapis.com`. - if (/(^|[.-])aiplatform\.([a-z0-9-]+\.rep\.)?googleapis\.com$/.test(host)) { - return 'gcp.vertex_ai'; - } - } - return 'anthropic'; + return isRecord(value); } function isAPIPromise(value: Promise): value is AnthropicAPIPromise { @@ -165,10 +155,45 @@ function isAnthropicStream(value: unknown): value is AnthropicStream { } export class AnthropicInstrumentation extends InstrumentationBase { + // Declared rather than initialized: the base constructor may call the + // provider setters below before subclass field initializers would run. + declare private _telemetry: TelemetryHandler | undefined; + declare private _telemetryTracerProvider: TracerProvider | undefined; + declare private _telemetryMeterProvider: MeterProvider | undefined; + constructor(config: AnthropicInstrumentationConfig = {}) { super(PACKAGE_NAME, PACKAGE_VERSION, config); } + override setTracerProvider(provider: TracerProvider) { + super.setTracerProvider(provider); + this._telemetryTracerProvider = provider; + this._telemetry = undefined; + } + + override setMeterProvider(provider: MeterProvider) { + super.setMeterProvider(provider); + this._telemetryMeterProvider = provider; + this._telemetry = undefined; + } + + /** + * The handler that owns each call's span and metrics. It is rebuilt when a + * provider changes so that new calls report through the current providers. + */ + private _getTelemetry(): TelemetryHandler { + return (this._telemetry ??= new TelemetryHandler({ + instrumentationName: PACKAGE_NAME, + instrumentationVersion: PACKAGE_VERSION, + tracerProvider: this._telemetryTracerProvider, + meterProvider: this._telemetryMeterProvider, + diag: this._diag, + // Message content is not recorded by this instrumentation, so the + // capture environment variable must not change what is emitted. + contentCaptureMode: 'none', + })); + } + protected init() { // Patch the shared `Messages` resource file rather than the package root: // `@anthropic-ai/sdk/client` and the Bedrock and Vertex packages import SDK @@ -239,53 +264,40 @@ export class AnthropicInstrumentation extends InstrumentationBase 0, }; if (state.helperOwned) { pendingHelperState = state; } - const ctx = trace.setSpan(context.active(), span); let result: Promise; try { - result = context.with(ctx, () => original.apply(this, args)); + result = invocation.withContext(() => original.apply(this, args)); } catch (error) { - instrumentation._endSpanWithError(state, error); + instrumentation._fail(state, error); throw error; } - const onError = (error: unknown) => - instrumentation._endSpanWithError(state, error); - if (isAPIPromise(result)) { instrumentation._observeAPIPromise(result, state); } else { // Not an `APIPromise`: fall back to observing the plain promise. - result.then(value => { - if (isAnthropicStream(value)) { - instrumentation._wrapStream(value, state); - } else { - instrumentation._endSpan(state); - } - }, onError); + result.then( + value => instrumentation._onParsed(value, state), + error => instrumentation._fail(state, error) + ); } // Preserve the Anthropic SDK's customized APIPromise instance. @@ -355,11 +367,31 @@ export class AnthropicInstrumentation extends InstrumentationBase { + if (aborted) { + instrumentation._failWithAbort(state); + } else if (failed) { + instrumentation._fail(state, failure); + } else if (messageStream.receivedMessages.length === 0) { + // The stream ended before `message_stop`, so the helper cannot + // produce a final message and `finalMessage()` will reject with + // an `AnthropicError`. + state.invocation.fail({ + errorType: 'AnthropicError', + statusDescription: + 'stream ended without producing a Message with role=assistant', + }); + } else { + state.invocation.stop(); + } + }; this._wrap(messageStream, '_emit', original => { return function patchedEmit( @@ -368,34 +400,38 @@ export class AnthropicInstrumentation extends InstrumentationBase, - state: SpanState + state: CallState ): void { - const onError = (error: unknown) => this._endSpanWithError(state, error); + const onError = (error: unknown) => this._fail(state, error); let parsed = false; this._wrap(apiPromise, 'parse', originalParse => { @@ -441,14 +477,7 @@ export class AnthropicInstrumentation extends InstrumentationBase { - if (isAnthropicStream(value)) { - // The span now belongs to the stream's lifetime. - this._wrapStream(value, state); - } else { - this._endSpan(state); - } - }, onError); + parsePromise.then(value => this._onParsed(value, state), onError); return parsePromise; }; }); @@ -460,7 +489,7 @@ export class AnthropicInstrumentation extends InstrumentationBase { // Call with the stream as receiver: `iterator` is an own-property closure // in current SDK versions, but the supported range is `>=0.65.0 <0.134.0`. - return () => - this._streamIterator(originalIterator.call(stream), state, stream); + const observed: AsyncIterable = { + [Symbol.asyncIterator]: () => + this._observeIterator(originalIterator.call(stream), state, signal), + }; + // A helper stream is not finished when its events run out: the helper + // still has to turn them into a final message, and reports its events + // and outcome through `_emit` instead. + const iterable = state.helperOwned + ? observed + : this._getTelemetry().wrapAsyncStream(observed, { + invocation: state.invocation, + onChunk: event => state.response.recordStreamEvent(event), + onEnd: () => { + if (state.aborted) this._failWithAbort(state); + }, + }); + return () => iterable[Symbol.asyncIterator](); }); // A stream that is abandoned without ever being iterated would otherwise // leave the span open forever, since it is only ended from the iterator. - const signal = stream.controller?.signal; if (signal) { if ( signal.aborted && - !state.awaitingNext && + state.pendingReads === 0 && !state.closing && !state.helperOwned ) { - this._endSpanWithAbort(state); + this._failWithAbort(state); return; } signal.addEventListener( @@ -500,8 +556,12 @@ export class AnthropicInstrumentation extends InstrumentationBase, - state: SpanState, - stream?: AnthropicStream - ): AsyncGenerator { - const signal = stream?.controller?.signal; + state: CallState, + signal: AbortSignal | undefined + ): AsyncIterator { let exhausted = false; - try { - while (true) { - state.awaitingNext = true; - let next; + return { + next: async () => { + state.pendingReads++; + let result: IteratorResult; try { - next = await iterator.next(); + result = await iterator.next(); + } catch (error) { + // A raw stream's failure is recorded by the genai-util stream + // wrapper this iterator sits under; a helper stream has no wrapper. + if (state.helperOwned) this._fail(state, error); + throw error; } finally { - state.awaitingNext = false; + state.pendingReads--; } - if (next.done) { + if (result.done) { exhausted = true; - break; - } - // An abort raised while `next()` was outstanding is deferred to here, - // and that call can still deliver a buffered event. The abort listener - // has already fired by now, so nothing else would ever end the span if - // the caller stops reading after this event. - if (signal?.aborted && !state.helperOwned) { - this._endSpanWithAbort(state); + // `Stream.fromSSEResponse` swallows abort errors and simply stops + // yielding, so an aborted generation is indistinguishable from a + // completed one without checking the signal. + if (signal?.aborted) state.aborted = true; + } else if (signal?.aborted && !state.helperOwned) { + // An abort raised while `next()` was outstanding is deferred to + // here, and that call can still deliver a buffered event. The abort + // listener has already fired by now, so nothing else would ever end + // the span if the caller stops reading after this event. + this._failWithAbort(state); } - yield next.value; - } - // `Stream.fromSSEResponse` swallows abort errors and simply stops - // yielding, so an aborted generation is indistinguishable from a - // completed one without checking the signal. - // A helper stream is not finished when its events run out: the helper - // still has to turn them into a final message, and can fail doing so. - if (state.helperOwned) { - // `MessageStream.done()` reports the outcome. - } else if (signal?.aborted) { - this._endSpanWithAbort(state); - } else { - this._endSpan(state); - } - } catch (error) { - this._endSpanWithError(state, error); - throw error; - } finally { - // Whether the span has already ended is irrelevant to SDK cleanup: the - // response body still has to be released and cancelled, exactly as it - // would be without instrumentation. - if (!exhausted) { + return result; + }, + return: async (value?: unknown) => { // Sampled before `return()`, which aborts the controller itself when // the caller breaks out of the loop. - const abortedByCaller = signal?.aborted ?? false; + if (!exhausted && signal?.aborted) state.aborted = true; + // Whether the span has already ended is irrelevant to SDK cleanup: the + // response body still has to be released and cancelled, exactly as it + // would be without instrumentation. state.closing = true; try { - await iterator.return?.(); + await iterator.return?.(value); } catch (error) { this._diag.debug('error closing Anthropic stream iterator:', error); } finally { state.closing = false; } - if (state.helperOwned) { - // `MessageStream.done()` reports the outcome. - } else if (abortedByCaller) { - this._endSpanWithAbort(state); - } else { - this._endSpan(state); - } - } - } + return { done: true, value }; + }, + }; } - private _endSpanWithAbort(state: SpanState): void { - if (state.ended) return; - state.span.setStatus({ - code: SpanStatusCode.ERROR, - message: 'stream aborted', + private _failWithAbort(state: CallState): void { + state.invocation.fail({ + errorType: 'APIUserAbortError', + statusDescription: 'stream aborted', }); - state.span.setAttribute('error.type', 'APIUserAbortError'); - this._endSpan(state); } - private _endSpan(state: SpanState): void { - if (state.ended) return; - state.ended = true; - state.span.end(); - } - - private _endSpanWithError( - state: SpanState, - error: unknown, - errorType?: string - ): void { - if (state.ended) return; + private _fail(state: CallState, error: unknown): void { // The SDK's error classes (`RateLimitError`, `APIConnectionError`, ...) - // are the most reliable low-cardinality identifier, as in the OpenAI - // instrumentation. A thrown non-`Error` has no such name, so it falls back - // to `_OTHER` per semantic conventions rather than a misleading `Error`. - const isError = error instanceof Error; - state.span.setStatus({ - code: SpanStatusCode.ERROR, - message: isError ? error.message : String(error), + // are the most reliable low-cardinality identifier, and are what + // genai-util derives `error.type` from. A thrown non-`Error` has no such + // name, so it falls back to `_OTHER` per semantic conventions. + state.invocation.fail({ + exception: error instanceof Error ? error : undefined, }); - state.span.setAttribute( - 'error.type', - errorType ?? (isError ? error.constructor.name : '_OTHER') - ); - this._endSpan(state); } } diff --git a/packages/instrumentation-anthropic/src/utils.ts b/packages/instrumentation-anthropic/src/utils.ts new file mode 100644 index 0000000000..4a03f9700d --- /dev/null +++ b/packages/instrumentation-anthropic/src/utils.ts @@ -0,0 +1,173 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +import type Anthropic from '@anthropic-ai/sdk'; +import type { TelemetryHandler } from '@opentelemetry/genai-util'; + +type InferenceInvocationOptions = Parameters< + TelemetryHandler['startInference'] +>[0]; +export type InferenceInvocation = ReturnType< + TelemetryHandler['startInference'] +>; +type InferenceRequestOptions = NonNullable< + InferenceInvocationOptions['requestOptions'] +>; +type TokenUsageDetails = Parameters[0]; + +/** The token counts of `Anthropic.Messages.Usage` that map to GenAI usage. */ +interface AnthropicUsage { + input_tokens?: number; + output_tokens?: number; + cache_creation_input_tokens?: number; + cache_read_input_tokens?: number; +} + +const USAGE_KEYS = [ + 'input_tokens', + 'output_tokens', + 'cache_creation_input_tokens', + 'cache_read_input_tokens', +] as const; + +export function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null; +} + +function asNumber(value: unknown): number | undefined { + return typeof value === 'number' && Number.isFinite(value) + ? value + : undefined; +} + +function asString(value: unknown): string | undefined { + return typeof value === 'string' && value !== '' ? value : undefined; +} + +/** + * `AnthropicBedrock` and `AnthropicVertex` extend `BaseAnthropic` and reuse the + * core `Messages` resource, so the same patch serves all three. Derive the + * provider from the client's base URL rather than assuming the first-party API. + */ +export function getProviderName(client: unknown): string { + const baseURL = (client as { baseURL?: unknown })?.baseURL; + if (typeof baseURL === 'string') { + let host: string; + try { + host = new URL(baseURL).host; + } catch { + return 'anthropic'; + } + if (/\.amazonaws\.com$/.test(host) && host.includes('bedrock')) { + return 'aws.bedrock'; + } + // `AnthropicBedrockMantle` uses `bedrock-mantle..api.aws`. + if (/^bedrock-mantle\.[a-z0-9-]+\.api\.aws$/.test(host)) { + return 'aws.bedrock'; + } + // Regional endpoints are `-aiplatform.googleapis.com`, the global + // endpoint has no region prefix, and the `us` and `eu` multi-region + // endpoints are `aiplatform..rep.googleapis.com`. + if (/(^|[.-])aiplatform\.([a-z0-9-]+\.rep\.)?googleapis\.com$/.test(host)) { + return 'gcp.vertex_ai'; + } + } + return 'anthropic'; +} + +/** Map the request parameters onto the invocation's `gen_ai.request.*` options. */ +export function getRequestOptions( + params: Anthropic.Messages.MessageCreateParams +): InferenceRequestOptions { + const stopSequences = Array.isArray(params.stop_sequences) + ? params.stop_sequences.filter( + (value): value is string => typeof value === 'string' + ) + : undefined; + return { + maxTokens: asNumber(params.max_tokens), + temperature: asNumber(params.temperature), + topP: asNumber(params.top_p), + topK: asNumber(params.top_k), + stopSequences, + stream: params.stream === true, + }; +} + +/** + * Anthropic reports `input_tokens` excluding the prompt cache, while + * `gen_ai.usage.input_tokens` includes cache reads and writes. + */ +function toTokenUsage(usage: AnthropicUsage): TokenUsageDetails { + const cacheRead = usage.cache_read_input_tokens; + const cacheWrite = usage.cache_creation_input_tokens; + return { + inputTokenCount: + usage.input_tokens === undefined + ? undefined + : usage.input_tokens + (cacheRead ?? 0) + (cacheWrite ?? 0), + outputTokenCount: usage.output_tokens, + cacheReadTokenCount: cacheRead, + cacheWriteTokenCount: cacheWrite, + }; +} + +/** + * Records response metadata and token usage onto an inference invocation, from + * either a complete `Message` or the events of a streamed one. + */ +export class ResponseRecorder { + private readonly _usage: AnthropicUsage = {}; + + constructor(private readonly _invocation: InferenceInvocation) {} + + /** Record a complete `Message`, or the partial one in `message_start`. */ + recordMessage(message: unknown): void { + // An abort can end the invocation while a buffered event is still being + // delivered; the span no longer accepts attributes by then. + if (!isRecord(message) || this._invocation.isEnded()) return; + const id = asString(message.id); + if (id) this._invocation.setResponseId(id); + const model = asString(message.model); + if (model) this._invocation.setResponseModel(model); + this._recordStopReason(message.stop_reason); + this._recordUsage(message.usage); + } + + /** Record one raw stream event. */ + recordStreamEvent(event: unknown): void { + if (!isRecord(event) || this._invocation.isEnded()) return; + if (event.type === 'message_start') { + this.recordMessage(event.message); + } else if (event.type === 'message_delta') { + if (isRecord(event.delta)) { + this._recordStopReason(event.delta.stop_reason); + } + this._recordUsage(event.usage); + } + } + + private _recordStopReason(value: unknown): void { + const stopReason = asString(value); + if (stopReason) this._invocation.setFinishReasons([stopReason]); + } + + /** + * Streams report usage across `message_start` and `message_delta`, where + * later counts are cumulative, so merge them and report the combined total. + */ + private _recordUsage(usage: unknown): void { + if (!isRecord(usage)) return; + let changed = false; + for (const key of USAGE_KEYS) { + const count = asNumber(usage[key]); + if (count !== undefined) { + this._usage[key] = count; + changed = true; + } + } + if (changed) this._invocation.setUsage(toTokenUsage(this._usage)); + } +} diff --git a/packages/instrumentation-anthropic/test/anthropic.test.ts b/packages/instrumentation-anthropic/test/anthropic.test.ts index 1eef4abe47..b236db29f8 100644 --- a/packages/instrumentation-anthropic/test/anthropic.test.ts +++ b/packages/instrumentation-anthropic/test/anthropic.test.ts @@ -6,9 +6,11 @@ import { instrumentation } from './load-instrumentation'; import { getTestSpans, + initMeterProvider, resetMemoryExporter, runTestFixture, TestCollector, + type TestMetricReader, } from '@opentelemetry/contrib-test-utils'; import Anthropic from '@anthropic-ai/sdk'; import { context, SpanKind, SpanStatusCode } from '@opentelemetry/api'; @@ -127,6 +129,24 @@ async function withCassette( } } +/** + * Run `fn` and resolve with the next unhandled rejection, which mocha would + * otherwise report as a test failure. + */ +async function captureUnhandledRejection(fn: () => void): Promise { + const listeners = process.listeners('unhandledRejection'); + process.removeAllListeners('unhandledRejection'); + try { + return await new Promise(resolve => { + process.once('unhandledRejection', resolve); + fn(); + }); + } finally { + process.removeAllListeners('unhandledRejection'); + listeners.forEach(listener => process.on('unhandledRejection', listener)); + } +} + describe('Anthropic instrumentation', function () { this.timeout(30000); nockBack.fixtures = path.join(__dirname, 'mock-responses'); @@ -153,8 +173,23 @@ describe('Anthropic instrumentation', function () { }); nockBack.setMode(missingKey ? 'lockdown' : (requestedMode ?? 'lockdown')); + let metricReader: TestMetricReader; + + /** Collect the metrics recorded since the last collection, keyed by name. */ + async function collectMetrics() { + const { resourceMetrics, errors } = await metricReader.collect(); + expect(errors).toEqual([]); + return new Map( + resourceMetrics.scopeMetrics + .flatMap(scope => scope.metrics) + .map(metric => [metric.descriptor.name, metric.dataPoints]) + ); + } + beforeEach(() => { resetMemoryExporter(); + // A fresh provider per test, so cumulative metrics start from zero. + metricReader = initMeterProvider(instrumentation); instrumentation.enable(); }); @@ -187,6 +222,12 @@ describe('Anthropic instrumentation', function () { 'gen_ai.operation.name': 'chat', 'gen_ai.provider.name': 'anthropic', 'gen_ai.request.model': model, + 'gen_ai.request.max_tokens': 16, + 'gen_ai.response.id': expect.stringMatching(/^msg_/), + 'gen_ai.response.model': model, + 'gen_ai.response.finish_reasons': ['end_turn'], + 'gen_ai.usage.input_tokens': 17, + 'gen_ai.usage.output_tokens': 7, }); }); @@ -528,6 +569,10 @@ describe('Anthropic instrumentation', function () { expect(spans).toHaveLength(1); expect(spans[0].name).toBe(`chat ${model}`); expect(spans[0].status.code).not.toBe(SpanStatusCode.ERROR); + // The body was never read, so there is no finish reason to report. + expect( + spans[0].attributes['gen_ai.response.finish_reasons'] + ).toBeUndefined(); }); it('leaves the SDK untouched when tracing is suppressed', async () => { @@ -562,6 +607,29 @@ describe('Anthropic instrumentation', function () { expect(getTestSpans()).toHaveLength(0); }); + it('records an SSE error raised during concurrent reads rather than an abort', async () => { + await withCassette('anthropic-messages-stream-sse-error.json', async () => { + const stream = await mockClient.messages.create({ + ...requestBody, + stream: true, + }); + + // The first read settling must not hide that the second is still + // pending when the SDK aborts its controller for the SSE error. + const iterator = stream[Symbol.asyncIterator](); + const results = await Promise.allSettled([ + iterator.next(), + iterator.next(), + ]); + expect(results.map(result => result.status)).toContain('rejected'); + }); + + const spans = getTestSpans(); + expect(spans).toHaveLength(1); + expect(spans[0].status.code).toBe(SpanStatusCode.ERROR); + expect(spans[0].attributes['error.type']).not.toBe('APIUserAbortError'); + }); + it('records an SSE error rather than the abort the SDK raises for it', async () => { await withCassette('anthropic-messages-stream-sse-error.json', async () => { const stream = await mockClient.messages.create({ @@ -757,6 +825,27 @@ describe('Anthropic instrumentation', function () { expect(spans[0].attributes['error.type']).toBe('APIUserAbortError'); }); + for (const event of ['end', 'finalMessage'] as const) { + it(`ends the messages.stream span when a '${event}' listener throws`, async () => { + // The listener's error escapes `_emit` inside the helper's own promise + // chain, so the SDK surfaces it as an unhandled rejection. + const rejection = await withCassette( + 'anthropic-messages-stream-complete.json', + () => + captureUnhandledRejection(() => { + mockClient.messages.stream(requestBody).on(event, () => { + throw new Error('listener failed'); + }); + }) + ); + expect(rejection).toEqual(new Error('listener failed')); + + const spans = getTestSpans(); + expect(spans).toHaveLength(1); + expect(spans[0].status.code).not.toBe(SpanStatusCode.ERROR); + }); + } + it('creates no telemetry for a suppressed messages.stream', async () => { await withCassette('anthropic-messages-stream.json', async () => { const client = createRecordingClient(); @@ -839,4 +928,120 @@ describe('Anthropic instrumentation', function () { expect(spans[0].status.code).toBe(SpanStatusCode.ERROR); expect(spans[0].attributes['error.type']).toBe('RateLimitError'); }); + + it('records response attributes for a raw stream', async () => { + await withCassette('anthropic-messages-create-streaming.json', async () => { + const stream = await createRecordingClient().messages.create({ + ...requestBody, + stream: true, + }); + for await (const event of stream) { + void event; + } + }); + + const spans = getTestSpans(); + expect(spans).toHaveLength(1); + expect(spans[0].status.code).not.toBe(SpanStatusCode.ERROR); + expect(spans[0].attributes).toMatchObject({ + 'gen_ai.operation.name': 'chat', + 'gen_ai.provider.name': 'anthropic', + 'gen_ai.request.model': model, + 'gen_ai.request.max_tokens': 16, + 'gen_ai.request.stream': true, + 'gen_ai.response.id': expect.stringMatching(/^msg_/), + 'gen_ai.response.model': model, + 'gen_ai.response.finish_reasons': [expect.any(String)], + 'gen_ai.usage.input_tokens': expect.any(Number), + 'gen_ai.usage.output_tokens': expect.any(Number), + 'gen_ai.response.time_to_first_chunk': expect.any(Number), + }); + expect(spans[0].attributes['gen_ai.response.finish_reasons']).not.toEqual([ + 'error', + ]); + }); + + it('records response attributes for messages.stream', async () => { + await withCassette('anthropic-messages-stream.json', () => + createRecordingClient().messages.stream(requestBody).finalMessage() + ); + + const spans = getTestSpans(); + expect(spans).toHaveLength(1); + expect(spans[0].status.code).not.toBe(SpanStatusCode.ERROR); + expect(spans[0].attributes).toMatchObject({ + 'gen_ai.request.stream': true, + 'gen_ai.response.id': expect.stringMatching(/^msg_/), + 'gen_ai.response.model': model, + 'gen_ai.response.finish_reasons': [expect.any(String)], + 'gen_ai.usage.input_tokens': expect.any(Number), + 'gen_ai.usage.output_tokens': expect.any(Number), + 'gen_ai.response.time_to_first_chunk': expect.any(Number), + }); + }); + + it('records duration and token usage metrics', async () => { + await withCassette('anthropic-messages-create.json', () => + createRecordingClient().messages.create(requestBody) + ); + + const metrics = await collectMetrics(); + const attributes = { + 'gen_ai.operation.name': 'chat', + 'gen_ai.provider.name': 'anthropic', + 'gen_ai.request.model': model, + 'gen_ai.response.model': model, + }; + const [duration] = metrics.get('gen_ai.client.operation.duration') ?? []; + expect(duration.attributes).toEqual(attributes); + expect( + metrics.get('gen_ai.client.inference.operation.input_tokens') + ).toMatchObject([{ attributes, value: { sum: 17, count: 1 } }]); + expect( + metrics.get('gen_ai.client.inference.operation.output_tokens') + ).toMatchObject([{ attributes, value: { sum: 7, count: 1 } }]); + expect( + metrics.get('gen_ai.client.inference.usage.input_tokens') + ).toMatchObject([ + { + attributes: { ...attributes, 'gen_ai.token.modality': 'unknown' }, + value: 17, + }, + ]); + }); + + it('records error.type on the duration metric of a failed call', async () => { + await withCassette('anthropic-messages-create-rate-limited.json', () => + expect(mockClient.messages.create(requestBody)).rejects.toThrow() + ); + + const metrics = await collectMetrics(); + const [duration] = metrics.get('gen_ai.client.operation.duration') ?? []; + expect(duration.attributes).toEqual({ + 'gen_ai.operation.name': 'chat', + 'gen_ai.provider.name': 'anthropic', + 'gen_ai.request.model': model, + 'error.type': 'RateLimitError', + }); + }); + + it('records streaming chunk metrics', async () => { + await withCassette('anthropic-messages-create-streaming.json', async () => { + const stream = await mockClient.messages.create({ + ...requestBody, + stream: true, + }); + for await (const event of stream) { + void event; + } + }); + + const metrics = await collectMetrics(); + expect( + metrics.get('gen_ai.client.operation.time_to_first_chunk') + ).toMatchObject([{ value: { count: 1 } }]); + expect( + metrics.get('gen_ai.client.operation.time_per_output_chunk')?.length + ).toBe(1); + }); }); diff --git a/packages/instrumentation-anthropic/test/utils.test.ts b/packages/instrumentation-anthropic/test/utils.test.ts new file mode 100644 index 0000000000..34e1dfd352 --- /dev/null +++ b/packages/instrumentation-anthropic/test/utils.test.ts @@ -0,0 +1,76 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +import './load-instrumentation'; +import { + getTestSpans, + resetMemoryExporter, +} from '@opentelemetry/contrib-test-utils'; +import { TelemetryHandler } from '@opentelemetry/genai-util'; +import { expect } from 'expect'; +import { ResponseRecorder } from '../src/utils'; + +describe('ResponseRecorder', () => { + const handler = new TelemetryHandler({ + instrumentationName: 'test', + instrumentationVersion: '0.0.0', + }); + + beforeEach(() => { + resetMemoryExporter(); + }); + + it('counts prompt cache reads and writes as input tokens', () => { + const invocation = handler.startInference({ providerName: 'anthropic' }); + new ResponseRecorder(invocation).recordMessage({ + id: 'msg_1', + model: 'claude', + stop_reason: 'max_tokens', + usage: { + input_tokens: 10, + cache_read_input_tokens: 5, + cache_creation_input_tokens: 3, + output_tokens: 2, + }, + }); + invocation.stop(); + + expect(getTestSpans()[0].attributes).toMatchObject({ + 'gen_ai.response.id': 'msg_1', + 'gen_ai.response.model': 'claude', + 'gen_ai.response.finish_reasons': ['max_tokens'], + 'gen_ai.usage.input_tokens': 18, + 'gen_ai.usage.cache_read.input_tokens': 5, + 'gen_ai.usage.cache_write.input_tokens': 3, + 'gen_ai.usage.output_tokens': 2, + }); + }); + + it('merges usage reported across stream events', () => { + const invocation = handler.startInference({ providerName: 'anthropic' }); + const recorder = new ResponseRecorder(invocation); + recorder.recordStreamEvent({ + type: 'message_start', + message: { + id: 'msg_2', + model: 'claude', + stop_reason: null, + usage: { input_tokens: 10, output_tokens: 1 }, + }, + }); + recorder.recordStreamEvent({ + type: 'message_delta', + delta: { stop_reason: 'end_turn' }, + usage: { output_tokens: 7 }, + }); + invocation.stop(); + + expect(getTestSpans()[0].attributes).toMatchObject({ + 'gen_ai.response.finish_reasons': ['end_turn'], + 'gen_ai.usage.input_tokens': 10, + 'gen_ai.usage.output_tokens': 7, + }); + }); +});