|
| 1 | +import { |
| 2 | + getClient, |
| 3 | + hasSpanStreamingEnabled, |
| 4 | + SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, |
| 5 | + SPAN_STATUS_ERROR, |
| 6 | + startSpan, |
| 7 | + startSpanManual, |
| 8 | + stringify, |
| 9 | +} from '@sentry/core'; |
| 10 | +import type { Span, SpanAttributeValue } from '@sentry/core'; |
| 11 | +import { |
| 12 | + GEN_AI_AGENT_NAME, |
| 13 | + GEN_AI_EMBEDDINGS_INPUT, |
| 14 | + GEN_AI_INPUT_MESSAGES, |
| 15 | + GEN_AI_OPERATION_NAME, |
| 16 | + GEN_AI_PROVIDER_NAME, |
| 17 | + GEN_AI_SYSTEM_INSTRUCTIONS, |
| 18 | +} from '@sentry/conventions/attributes'; |
| 19 | +import type { InstrumentedMethodEntry } from '../core/utils'; |
| 20 | +import { |
| 21 | + buildMethodPath, |
| 22 | + extractSystemInstructions, |
| 23 | + getGenAiSpanOp, |
| 24 | + resolveAIRecordingOptions, |
| 25 | + wrapPromiseWithMethods, |
| 26 | +} from '../core/utils'; |
| 27 | +import { MISTRAL_METHOD_REGISTRY } from './constants'; |
| 28 | +import { instrumentStream } from './streaming'; |
| 29 | +import type { MistralOptions } from './types'; |
| 30 | +import { addResponseAttributes, extractRequestParameters, getModelForSpanName } from './utils'; |
| 31 | + |
| 32 | +/** |
| 33 | + * Extract request attributes from method arguments. |
| 34 | + */ |
| 35 | +export function extractRequestAttributes(args: unknown[], operationName: string): Record<string, unknown> { |
| 36 | + const attributes: Record<string, unknown> = { |
| 37 | + [GEN_AI_PROVIDER_NAME]: 'mistral', |
| 38 | + [GEN_AI_OPERATION_NAME]: operationName, |
| 39 | + [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ai.mistral', |
| 40 | + }; |
| 41 | + |
| 42 | + if (args.length > 0 && typeof args[0] === 'object' && args[0] !== null) { |
| 43 | + const params = args[0] as Record<string, unknown>; |
| 44 | + |
| 45 | + if (operationName === 'invoke_agent' && typeof params.agentId === 'string') { |
| 46 | + attributes[GEN_AI_AGENT_NAME] = params.agentId; |
| 47 | + } |
| 48 | + |
| 49 | + Object.assign(attributes, extractRequestParameters(params)); |
| 50 | + } |
| 51 | + |
| 52 | + return attributes; |
| 53 | +} |
| 54 | + |
| 55 | +/** |
| 56 | + * Record AI request inputs on the span, if recording is enabled. |
| 57 | + */ |
| 58 | +export function addRequestAttributes(span: Span, params: Record<string, unknown>, operationName: string): void { |
| 59 | + if (operationName === 'embeddings') { |
| 60 | + const input = params.inputs; |
| 61 | + if (input == null || (typeof input === 'string' && input.length === 0) || (Array.isArray(input) && !input.length)) { |
| 62 | + return; |
| 63 | + } |
| 64 | + span.setAttribute(GEN_AI_EMBEDDINGS_INPUT, stringify(input, String)); |
| 65 | + return; |
| 66 | + } |
| 67 | + |
| 68 | + // FIM completions carry a raw `prompt` string rather than a messages array. |
| 69 | + if (operationName === 'text_completion') { |
| 70 | + if (typeof params.prompt === 'string' && params.prompt.length > 0) { |
| 71 | + span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify(params.prompt)); |
| 72 | + } |
| 73 | + return; |
| 74 | + } |
| 75 | + |
| 76 | + const src = 'messages' in params ? params.messages : undefined; |
| 77 | + if (!src || (Array.isArray(src) && src.length === 0)) { |
| 78 | + return; |
| 79 | + } |
| 80 | + |
| 81 | + const { systemInstructions, filteredMessages } = extractSystemInstructions(src); |
| 82 | + if (systemInstructions) { |
| 83 | + span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS, systemInstructions); |
| 84 | + } |
| 85 | + span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify(filteredMessages)); |
| 86 | +} |
| 87 | + |
| 88 | +/** |
| 89 | + * Instrument a single Mistral SDK method with a gen_ai span. |
| 90 | + * @see https://docs.sentry.io/platforms/javascript/guides/node/tracing/instrumentation/ai-agents-module/#manual-instrumentation |
| 91 | + */ |
| 92 | +function instrumentMethod<T extends unknown[], R>( |
| 93 | + originalMethod: (...args: T) => Promise<R>, |
| 94 | + instrumentedMethod: InstrumentedMethodEntry, |
| 95 | + context: unknown, |
| 96 | + options: MistralOptions, |
| 97 | +): (...args: T) => Promise<R> { |
| 98 | + return function instrumentedCall(...args: T): Promise<R> { |
| 99 | + const operationName = instrumentedMethod.operation || 'unknown'; |
| 100 | + const requestAttributes = extractRequestAttributes(args, operationName); |
| 101 | + |
| 102 | + const params = args[0] as Record<string, unknown> | undefined; |
| 103 | + const model = getModelForSpanName(params, operationName); |
| 104 | + // `*.stream` methods are always streaming; `complete` methods stream only with `stream: true`. |
| 105 | + const isStreamRequested = !!instrumentedMethod.streaming || params?.stream === true; |
| 106 | + const client = getClient(); |
| 107 | + |
| 108 | + const spanConfig = { |
| 109 | + // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality. |
| 110 | + name: |
| 111 | + model !== 'unknown' || !(client && hasSpanStreamingEnabled(client)) |
| 112 | + ? `${operationName} ${model}` |
| 113 | + : operationName, |
| 114 | + op: getGenAiSpanOp(operationName), |
| 115 | + attributes: requestAttributes as Record<string, SpanAttributeValue>, |
| 116 | + }; |
| 117 | + |
| 118 | + if (isStreamRequested) { |
| 119 | + let originalResult!: Promise<R>; |
| 120 | + |
| 121 | + const instrumentedPromise = startSpanManual(spanConfig, (span: Span) => { |
| 122 | + originalResult = originalMethod.apply(context, args); |
| 123 | + |
| 124 | + if (options.recordInputs && params) { |
| 125 | + addRequestAttributes(span, params, operationName); |
| 126 | + } |
| 127 | + |
| 128 | + return (async () => { |
| 129 | + try { |
| 130 | + const result = await originalResult; |
| 131 | + return instrumentStream( |
| 132 | + result as AsyncIterable<unknown>, |
| 133 | + span, |
| 134 | + options.recordOutputs ?? false, |
| 135 | + ) as unknown as R; |
| 136 | + } catch (error) { |
| 137 | + span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); |
| 138 | + span.end(); |
| 139 | + throw error; |
| 140 | + } |
| 141 | + })(); |
| 142 | + }); |
| 143 | + |
| 144 | + return wrapPromiseWithMethods(originalResult, instrumentedPromise); |
| 145 | + } |
| 146 | + |
| 147 | + let originalResult!: Promise<R>; |
| 148 | + |
| 149 | + const instrumentedPromise = startSpan(spanConfig, (span: Span) => { |
| 150 | + originalResult = originalMethod.apply(context, args); |
| 151 | + |
| 152 | + if (options.recordInputs && params) { |
| 153 | + addRequestAttributes(span, params, operationName); |
| 154 | + } |
| 155 | + |
| 156 | + return originalResult.then(result => { |
| 157 | + addResponseAttributes(span, result, options.recordOutputs); |
| 158 | + return result; |
| 159 | + }); |
| 160 | + }); |
| 161 | + |
| 162 | + return wrapPromiseWithMethods(originalResult, instrumentedPromise); |
| 163 | + }; |
| 164 | +} |
| 165 | + |
| 166 | +/** |
| 167 | + * Create a deep proxy for Mistral client instrumentation. |
| 168 | + */ |
| 169 | +function createDeepProxy<T extends object>(target: T, currentPath = '', options: MistralOptions): T { |
| 170 | + return new Proxy(target, { |
| 171 | + get(obj: object, prop: string): unknown { |
| 172 | + const value = (obj as Record<string, unknown>)[prop]; |
| 173 | + const methodPath = buildMethodPath(currentPath, String(prop)); |
| 174 | + |
| 175 | + const instrumentedMethod = MISTRAL_METHOD_REGISTRY[methodPath as keyof typeof MISTRAL_METHOD_REGISTRY]; |
| 176 | + if (typeof value === 'function' && instrumentedMethod) { |
| 177 | + return instrumentMethod(value as (...args: unknown[]) => Promise<unknown>, instrumentedMethod, obj, options); |
| 178 | + } |
| 179 | + |
| 180 | + if (typeof value === 'function') { |
| 181 | + // Preserve the original `this` for uninstrumented methods (private class fields). |
| 182 | + return value.bind(obj); |
| 183 | + } |
| 184 | + |
| 185 | + if (value && typeof value === 'object') { |
| 186 | + return createDeepProxy(value, methodPath, options); |
| 187 | + } |
| 188 | + |
| 189 | + return value; |
| 190 | + }, |
| 191 | + }) as T; |
| 192 | +} |
| 193 | + |
| 194 | +/** |
| 195 | + * Instrument a Mistral client with Sentry tracing. |
| 196 | + * Can be used across Node.js, Cloudflare Workers, and Vercel Edge. |
| 197 | + */ |
| 198 | +export function instrumentMistralClient<T extends object>(client: T, options?: MistralOptions): T { |
| 199 | + return createDeepProxy(client, '', resolveAIRecordingOptions(options)); |
| 200 | +} |
0 commit comments