|
| 1 | +import { getCurrentScope } from '../../currentScopes'; |
| 2 | +import { captureException } from '../../exports'; |
| 3 | +import { startSpan } from '../../tracing/trace'; |
| 4 | +import type { Span, SpanAttributeValue } from '../../types-hoist/span'; |
| 5 | +import { |
| 6 | + ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE, |
| 7 | + GEN_AI_OPERATION_NAME_ATTRIBUTE, |
| 8 | + GEN_AI_PROMPT_ATTRIBUTE, |
| 9 | + GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE, |
| 10 | + GEN_AI_REQUEST_MESSAGES_ATTRIBUTE, |
| 11 | + GEN_AI_REQUEST_MODEL_ATTRIBUTE, |
| 12 | + GEN_AI_REQUEST_STREAM_ATTRIBUTE, |
| 13 | + GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE, |
| 14 | + GEN_AI_REQUEST_TOP_K_ATTRIBUTE, |
| 15 | + GEN_AI_REQUEST_TOP_P_ATTRIBUTE, |
| 16 | + GEN_AI_RESPONSE_ID_ATTRIBUTE, |
| 17 | + GEN_AI_RESPONSE_MODEL_ATTRIBUTE, |
| 18 | + GEN_AI_RESPONSE_TEXT_ATTRIBUTE, |
| 19 | + GEN_AI_SYSTEM_ATTRIBUTE, |
| 20 | +} from '../ai/gen-ai-attributes'; |
| 21 | +import { buildMethodPath, getFinalOperationName, getSpanOperation, setTokenUsageAttributes } from '../ai/utils'; |
| 22 | +import { ANTHROPIC_AI_INTEGRATION_NAME } from './constants'; |
| 23 | +import type { |
| 24 | + AnthropicAiClient, |
| 25 | + AnthropicAiInstrumentedMethod, |
| 26 | + AnthropicAiIntegration, |
| 27 | + AnthropicAiOptions, |
| 28 | + AnthropicAiResponse, |
| 29 | +} from './types'; |
| 30 | +import { shouldInstrument } from './utils'; |
| 31 | + |
| 32 | +/** |
| 33 | + * Extract request attributes from method arguments |
| 34 | + */ |
| 35 | +function extractRequestAttributes(args: unknown[], methodPath: string): Record<string, unknown> { |
| 36 | + const attributes: Record<string, unknown> = { |
| 37 | + [GEN_AI_SYSTEM_ATTRIBUTE]: 'anthropic', |
| 38 | + [GEN_AI_OPERATION_NAME_ATTRIBUTE]: getFinalOperationName(methodPath), |
| 39 | + }; |
| 40 | + |
| 41 | + if (args.length > 0 && typeof args[0] === 'object' && args[0] !== null) { |
| 42 | + const params = args[0] as Record<string, unknown>; |
| 43 | + |
| 44 | + attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = params.model ?? 'unknown'; |
| 45 | + if ('temperature' in params) attributes[GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE] = params.temperature; |
| 46 | + if ('top_p' in params) attributes[GEN_AI_REQUEST_TOP_P_ATTRIBUTE] = params.top_p; |
| 47 | + if ('stream' in params) attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE] = params.stream; |
| 48 | + if ('top_k' in params) attributes[GEN_AI_REQUEST_TOP_K_ATTRIBUTE] = params.top_k; |
| 49 | + attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE] = params.frequency_penalty; |
| 50 | + } else { |
| 51 | + attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = 'unknown'; |
| 52 | + } |
| 53 | + |
| 54 | + return attributes; |
| 55 | +} |
| 56 | + |
| 57 | +/** |
| 58 | + * Add private request attributes to spans. |
| 59 | + * This is only recorded if recordInputs is true. |
| 60 | + */ |
| 61 | +function addPrivateRequestAttributes(span: Span, params: Record<string, unknown>): void { |
| 62 | + if ('messages' in params) { |
| 63 | + span.setAttributes({ [GEN_AI_REQUEST_MESSAGES_ATTRIBUTE]: JSON.stringify(params.messages) }); |
| 64 | + } |
| 65 | + if ('input' in params) { |
| 66 | + span.setAttributes({ [GEN_AI_REQUEST_MESSAGES_ATTRIBUTE]: JSON.stringify(params.input) }); |
| 67 | + } |
| 68 | + if ('prompt' in params) { |
| 69 | + span.setAttributes({ [GEN_AI_PROMPT_ATTRIBUTE]: JSON.stringify(params.prompt) }); |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +/** |
| 74 | + * Add response attributes to spans |
| 75 | + */ |
| 76 | +function addResponseAttributes(span: Span, response: AnthropicAiResponse, recordOutputs?: boolean): void { |
| 77 | + if (!response || typeof response !== 'object') return; |
| 78 | + |
| 79 | + // Private response attributes that are only recorded if recordOutputs is true. |
| 80 | + if (recordOutputs) { |
| 81 | + // Messages.create |
| 82 | + if ('content' in response) { |
| 83 | + span.setAttributes({ [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: response.content }); |
| 84 | + } |
| 85 | + // Completions.create |
| 86 | + if ('completion' in response) { |
| 87 | + span.setAttributes({ [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: response.completion }); |
| 88 | + } |
| 89 | + // Models.countTokens |
| 90 | + if ('input_tokens' in response) { |
| 91 | + span.setAttributes({ [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: JSON.stringify(response.input_tokens) }); |
| 92 | + } |
| 93 | + } |
| 94 | + |
| 95 | + span.setAttributes({ |
| 96 | + [GEN_AI_RESPONSE_ID_ATTRIBUTE]: response.id, |
| 97 | + }); |
| 98 | + span.setAttributes({ |
| 99 | + [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: response.model, |
| 100 | + }); |
| 101 | + span.setAttributes({ |
| 102 | + [ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE]: new Date(response.created * 1000).toISOString(), |
| 103 | + }); |
| 104 | + |
| 105 | + if (response.usage) { |
| 106 | + setTokenUsageAttributes( |
| 107 | + span, |
| 108 | + response.usage.input_tokens, |
| 109 | + response.usage.output_tokens, |
| 110 | + response.usage.cache_creation_input_tokens, |
| 111 | + response.usage.cache_read_input_tokens, |
| 112 | + ); |
| 113 | + } |
| 114 | +} |
| 115 | + |
| 116 | +/** |
| 117 | + * Get record options from the integration |
| 118 | + */ |
| 119 | +function getOptionsFromIntegration(): AnthropicAiOptions { |
| 120 | + const scope = getCurrentScope(); |
| 121 | + const client = scope.getClient(); |
| 122 | + const integration = client?.getIntegrationByName(ANTHROPIC_AI_INTEGRATION_NAME) as AnthropicAiIntegration | undefined; |
| 123 | + const shouldRecordInputsAndOutputs = integration ? Boolean(client?.getOptions().sendDefaultPii) : false; |
| 124 | + |
| 125 | + return { |
| 126 | + recordInputs: integration?.options?.recordInputs ?? shouldRecordInputsAndOutputs, |
| 127 | + recordOutputs: integration?.options?.recordOutputs ?? shouldRecordInputsAndOutputs, |
| 128 | + }; |
| 129 | +} |
| 130 | + |
| 131 | +/** |
| 132 | + * Instrument a method with Sentry spans |
| 133 | + * Following Sentry AI Agents Manual Instrumentation conventions |
| 134 | + * @see https://docs.sentry.io/platforms/javascript/guides/node/tracing/instrumentation/ai-agents-module/#manual-instrumentation |
| 135 | + */ |
| 136 | +function instrumentMethod<T extends unknown[], R>( |
| 137 | + originalMethod: (...args: T) => Promise<R>, |
| 138 | + methodPath: AnthropicAiInstrumentedMethod, |
| 139 | + context: unknown, |
| 140 | + options?: AnthropicAiOptions, |
| 141 | +): (...args: T) => Promise<R> { |
| 142 | + return async function instrumentedMethod(...args: T): Promise<R> { |
| 143 | + const finalOptions = options || getOptionsFromIntegration(); |
| 144 | + const requestAttributes = extractRequestAttributes(args, methodPath); |
| 145 | + const model = requestAttributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] ?? 'unknown'; |
| 146 | + const operationName = getFinalOperationName(methodPath); |
| 147 | + |
| 148 | + // TODO: Handle streaming responses |
| 149 | + return startSpan( |
| 150 | + { |
| 151 | + name: `${operationName} ${model}`, |
| 152 | + op: getSpanOperation(methodPath), |
| 153 | + attributes: requestAttributes as Record<string, SpanAttributeValue>, |
| 154 | + }, |
| 155 | + async (span: Span) => { |
| 156 | + try { |
| 157 | + if (finalOptions.recordInputs && args[0] && typeof args[0] === 'object') { |
| 158 | + addPrivateRequestAttributes(span, args[0] as Record<string, unknown>); |
| 159 | + } |
| 160 | + |
| 161 | + const result = await originalMethod.apply(context, args); |
| 162 | + addResponseAttributes(span, result, finalOptions.recordOutputs); |
| 163 | + return result; |
| 164 | + } catch (error) { |
| 165 | + captureException(error); |
| 166 | + throw error; |
| 167 | + } |
| 168 | + }, |
| 169 | + ); |
| 170 | + }; |
| 171 | +} |
| 172 | + |
| 173 | +/** |
| 174 | + * Create a deep proxy for Anthropic AI client instrumentation |
| 175 | + */ |
| 176 | +function createDeepProxy<T extends AnthropicAiClient>(target: T, currentPath = '', options?: AnthropicAiOptions): T { |
| 177 | + return new Proxy(target, { |
| 178 | + get(obj: object, prop: string): unknown { |
| 179 | + const value = (obj as Record<string, unknown>)[prop]; |
| 180 | + const methodPath = buildMethodPath(currentPath, String(prop)); |
| 181 | + // eslint-disable-next-line no-console |
| 182 | + console.log('value ----->>>>', value); |
| 183 | + |
| 184 | + if (typeof value === 'function' && shouldInstrument(methodPath)) { |
| 185 | + return instrumentMethod(value as (...args: unknown[]) => Promise<unknown>, methodPath, obj, options); |
| 186 | + } |
| 187 | + |
| 188 | + if (typeof value === 'function') { |
| 189 | + // Bind non-instrumented functions to preserve the original `this` context, |
| 190 | + // which is required for accessing private class fields (e.g. #baseURL) in OpenAI SDK v5. |
| 191 | + return value.bind(obj); |
| 192 | + } |
| 193 | + |
| 194 | + if (value && typeof value === 'object') { |
| 195 | + return createDeepProxy(value as object, methodPath, options); |
| 196 | + } |
| 197 | + |
| 198 | + return value; |
| 199 | + }, |
| 200 | + }) as T; |
| 201 | +} |
| 202 | + |
| 203 | +/** |
| 204 | + * Instrument an Anthropic AI client with Sentry tracing |
| 205 | + * Can be used across Node.js, Cloudflare Workers, and Vercel Edge |
| 206 | + * |
| 207 | + * @template T - The type of the client that extends AnthropicAiClient |
| 208 | + * @param client - The Anthropic AI client to instrument |
| 209 | + * @param options - Optional configuration for recording inputs and outputs |
| 210 | + * @returns The instrumented client with the same type as the input |
| 211 | + */ |
| 212 | +export function instrumentAnthropicAiClient<T extends AnthropicAiClient>(client: T, options?: AnthropicAiOptions): T { |
| 213 | + return createDeepProxy(client, '', options); |
| 214 | +} |
0 commit comments