|
| 1 | +import { captureException } from '../../exports'; |
| 2 | +import { SPAN_STATUS_ERROR } from '../../tracing'; |
| 3 | +import type { Span } from '../../types-hoist/span'; |
| 4 | +import { |
| 5 | + ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE, |
| 6 | + GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE, |
| 7 | + GEN_AI_RESPONSE_ID_ATTRIBUTE, |
| 8 | + GEN_AI_RESPONSE_MODEL_ATTRIBUTE, |
| 9 | + GEN_AI_RESPONSE_STREAMING_ATTRIBUTE, |
| 10 | + GEN_AI_RESPONSE_TEXT_ATTRIBUTE, |
| 11 | +} from '../ai/gen-ai-attributes'; |
| 12 | +import { setTokenUsageAttributes } from '../ai/utils'; |
| 13 | +import type { AnthropicAiStreamingEvent } from './types'; |
| 14 | + |
| 15 | +/** |
| 16 | + * State object used to accumulate information from a stream of Anthropic AI events. |
| 17 | + */ |
| 18 | + |
| 19 | +interface StreamingState { |
| 20 | + /** Types of events encountered in the stream. */ |
| 21 | + eventTypes: string[]; |
| 22 | + /** Collected response text fragments (for output recording). */ |
| 23 | + responseTexts: string[]; |
| 24 | + /** Reasons for finishing the response, as reported by the API. */ |
| 25 | + finishReasons: string[]; |
| 26 | + /** The response ID. */ |
| 27 | + responseId: string; |
| 28 | + /** The model name. */ |
| 29 | + responseModel: string; |
| 30 | + /** The timestamp of the response. */ |
| 31 | + responseTimestamp: number; |
| 32 | + /** Number of prompt/input tokens used. */ |
| 33 | + promptTokens: number | undefined; |
| 34 | + /** Number of completion/output tokens used. */ |
| 35 | + completionTokens: number | undefined; |
| 36 | + /** Number of cache creation input tokens used. */ |
| 37 | + cacheCreationInputTokens: number | undefined; |
| 38 | + /** Number of cache read input tokens used. */ |
| 39 | + cacheReadInputTokens: number | undefined; |
| 40 | +} |
| 41 | + |
| 42 | +/** |
| 43 | + * Checks if an event is an error event |
| 44 | + * @param event - The event to process |
| 45 | + * @param state - The state of the streaming process |
| 46 | + * @param recordOutputs - Whether to record outputs |
| 47 | + * @param span - The span to update |
| 48 | + * @returns Whether an error occurred |
| 49 | + */ |
| 50 | + |
| 51 | +function isErrorEvent( |
| 52 | + event: AnthropicAiStreamingEvent, |
| 53 | + state: StreamingState, |
| 54 | + recordOutputs: boolean, |
| 55 | + span: Span, |
| 56 | +): boolean { |
| 57 | + if ('type' in event && typeof event.type === 'string') { |
| 58 | + state.eventTypes.push(event.type); |
| 59 | + |
| 60 | + // If the event is an error, set the span status and capture the error |
| 61 | + // These error events are not rejected by the API by default, but are sent as metadata of the response |
| 62 | + if (event.type === 'error') { |
| 63 | + const message = event.error?.message ?? 'internal_error'; |
| 64 | + span.setStatus({ code: SPAN_STATUS_ERROR, message }); |
| 65 | + captureException(new Error(`anthropic_stream_error: ${message}`), { |
| 66 | + mechanism: { |
| 67 | + handled: false, |
| 68 | + type: 'auto.ai.anthropic', |
| 69 | + data: { |
| 70 | + function: 'anthropic_stream_error', |
| 71 | + }, |
| 72 | + }, |
| 73 | + data: { |
| 74 | + function: 'anthropic_stream_error', |
| 75 | + }, |
| 76 | + }); |
| 77 | + return true; |
| 78 | + } |
| 79 | + |
| 80 | + if (recordOutputs && event.type === 'content_block_delta') { |
| 81 | + const text = event.delta?.text ?? ''; |
| 82 | + if (text) state.responseTexts.push(text); |
| 83 | + } |
| 84 | + } |
| 85 | + return false; |
| 86 | +} |
| 87 | + |
| 88 | +/** |
| 89 | + * Processes the message metadata of an event |
| 90 | + * @param event - The event to process |
| 91 | + * @param state - The state of the streaming process |
| 92 | + */ |
| 93 | + |
| 94 | +function handleMessageMetadata(event: AnthropicAiStreamingEvent, state: StreamingState): void { |
| 95 | + // The token counts shown in the usage field of the message_delta event are cumulative. |
| 96 | + // @see https://docs.anthropic.com/en/docs/build-with-claude/streaming#event-types |
| 97 | + if (event.type === 'message_delta' && event.usage) { |
| 98 | + if ('output_tokens' in event.usage && typeof event.usage.output_tokens === 'number') { |
| 99 | + state.completionTokens = event.usage.output_tokens; |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + if (event.message) { |
| 104 | + const message = event.message; |
| 105 | + |
| 106 | + if (message.id) state.responseId = message.id; |
| 107 | + if (message.model) state.responseModel = message.model; |
| 108 | + if (message.stop_reason) state.finishReasons.push(message.stop_reason); |
| 109 | + |
| 110 | + if (message.usage) { |
| 111 | + if (typeof message.usage.input_tokens === 'number') state.promptTokens = message.usage.input_tokens; |
| 112 | + if (typeof message.usage.cache_creation_input_tokens === 'number') |
| 113 | + state.cacheCreationInputTokens = message.usage.cache_creation_input_tokens; |
| 114 | + if (typeof message.usage.cache_read_input_tokens === 'number') |
| 115 | + state.cacheReadInputTokens = message.usage.cache_read_input_tokens; |
| 116 | + } |
| 117 | + } |
| 118 | +} |
| 119 | + |
| 120 | +/** |
| 121 | + * Processes an event |
| 122 | + * @param event - The event to process |
| 123 | + * @param state - The state of the streaming process |
| 124 | + * @param recordOutputs - Whether to record outputs |
| 125 | + * @param span - The span to update |
| 126 | + */ |
| 127 | + |
| 128 | +function processEvent( |
| 129 | + event: AnthropicAiStreamingEvent, |
| 130 | + state: StreamingState, |
| 131 | + recordOutputs: boolean, |
| 132 | + span: Span, |
| 133 | +): void { |
| 134 | + if (!(event && typeof event === 'object')) { |
| 135 | + state.eventTypes.push('unknown:non-object'); |
| 136 | + return; |
| 137 | + } |
| 138 | + |
| 139 | + const isError = isErrorEvent(event, state, recordOutputs, span); |
| 140 | + if (isError) return; |
| 141 | + |
| 142 | + handleMessageMetadata(event, state); |
| 143 | +} |
| 144 | + |
| 145 | +/** |
| 146 | + * Instruments an async iterable stream of Anthropic events, updates the span with |
| 147 | + * streaming attributes and (optionally) the aggregated output text, and yields |
| 148 | + * each event from the input stream unchanged. |
| 149 | + */ |
| 150 | +export async function* instrumentStream( |
| 151 | + stream: AsyncIterable<AnthropicAiStreamingEvent>, |
| 152 | + span: Span, |
| 153 | + recordOutputs: boolean, |
| 154 | +): AsyncGenerator<AnthropicAiStreamingEvent, void, unknown> { |
| 155 | + const state: StreamingState = { |
| 156 | + eventTypes: [], |
| 157 | + responseTexts: [], |
| 158 | + finishReasons: [], |
| 159 | + responseId: '', |
| 160 | + responseModel: '', |
| 161 | + responseTimestamp: 0, |
| 162 | + promptTokens: undefined, |
| 163 | + completionTokens: undefined, |
| 164 | + cacheCreationInputTokens: undefined, |
| 165 | + cacheReadInputTokens: undefined, |
| 166 | + }; |
| 167 | + |
| 168 | + try { |
| 169 | + for await (const event of stream) { |
| 170 | + processEvent(event, state, recordOutputs, span); |
| 171 | + yield event; |
| 172 | + } |
| 173 | + } finally { |
| 174 | + // Set common response attributes if available |
| 175 | + if (state.responseId) { |
| 176 | + span.setAttributes({ |
| 177 | + [GEN_AI_RESPONSE_ID_ATTRIBUTE]: state.responseId, |
| 178 | + }); |
| 179 | + } |
| 180 | + if (state.responseModel) { |
| 181 | + span.setAttributes({ |
| 182 | + [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: state.responseModel, |
| 183 | + }); |
| 184 | + } |
| 185 | + if (state.responseTimestamp) { |
| 186 | + span.setAttributes({ |
| 187 | + [ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE]: new Date(state.responseTimestamp * 1000).toISOString(), |
| 188 | + }); |
| 189 | + } |
| 190 | + |
| 191 | + setTokenUsageAttributes( |
| 192 | + span, |
| 193 | + state.promptTokens, |
| 194 | + state.completionTokens, |
| 195 | + state.cacheCreationInputTokens, |
| 196 | + state.cacheReadInputTokens, |
| 197 | + ); |
| 198 | + |
| 199 | + span.setAttributes({ |
| 200 | + [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true, |
| 201 | + }); |
| 202 | + |
| 203 | + if (state.finishReasons.length > 0) { |
| 204 | + span.setAttributes({ |
| 205 | + [GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: JSON.stringify(state.finishReasons), |
| 206 | + }); |
| 207 | + } |
| 208 | + |
| 209 | + if (recordOutputs && state.responseTexts.length > 0) { |
| 210 | + span.setAttributes({ |
| 211 | + [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: state.responseTexts.join(''), |
| 212 | + }); |
| 213 | + } |
| 214 | + |
| 215 | + span.end(); |
| 216 | + } |
| 217 | +} |
0 commit comments