@sentry/server-utils 11.13.0 → 11.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/cjs/chunks/config.js +19 -5
- package/build/cjs/chunks/config.js.map +1 -1
- package/build/cjs/chunks/exports.js +72 -26
- package/build/cjs/chunks/exports.js.map +1 -1
- package/build/cjs/chunks/moduleInjectedTransform.js +6 -5
- package/build/cjs/chunks/moduleInjectedTransform.js.map +1 -1
- package/build/cjs/index.js +161 -65
- package/build/cjs/index.js.map +1 -1
- package/build/cjs/orchestrion/bundler/rollup.js +4 -4
- package/build/cjs/orchestrion/bundler/rollup.js.map +1 -1
- package/build/esm/ai/google-genai/constants.js +2 -1
- package/build/esm/ai/google-genai/constants.js.map +1 -1
- package/build/esm/ai/google-genai/decisions.js +25 -0
- package/build/esm/ai/google-genai/decisions.js.map +1 -0
- package/build/esm/ai/google-genai/index.js +16 -5
- package/build/esm/ai/google-genai/index.js.map +1 -1
- package/build/esm/ai/mistral/index.js +9 -8
- package/build/esm/ai/mistral/index.js.map +1 -1
- package/build/esm/ai/mistral/streaming.js +3 -7
- package/build/esm/ai/mistral/streaming.js.map +1 -1
- package/build/esm/ai/mistral/utils.js +9 -1
- package/build/esm/ai/mistral/utils.js.map +1 -1
- package/build/esm/ai/vercel-ai/index.js +3 -1
- package/build/esm/ai/vercel-ai/index.js.map +1 -1
- package/build/esm/ai/workers-ai/index.js +8 -7
- package/build/esm/ai/workers-ai/index.js.map +1 -1
- package/build/esm/ai/workers-ai/streaming.js +3 -7
- package/build/esm/ai/workers-ai/streaming.js.map +1 -1
- package/build/esm/index.js +3 -2
- package/build/esm/index.js.map +1 -1
- package/build/esm/integrations/cron.js +2 -2
- package/build/esm/integrations/cron.js.map +1 -1
- package/build/esm/integrations/google-genai.js +10 -6
- package/build/esm/integrations/google-genai.js.map +1 -1
- package/build/esm/integrations/mistral.js +4 -3
- package/build/esm/integrations/mistral.js.map +1 -1
- package/build/esm/integrations/node-cron.js +5 -4
- package/build/esm/integrations/node-cron.js.map +1 -1
- package/build/esm/integrations/node-schedule.js +2 -2
- package/build/esm/integrations/node-schedule.js.map +1 -1
- package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +9 -1
- package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
- package/build/esm/orchestrion/bundler/moduleInjectedTransform.js +6 -5
- package/build/esm/orchestrion/bundler/moduleInjectedTransform.js.map +1 -1
- package/build/esm/orchestrion/bundler/rollup.js +4 -4
- package/build/esm/orchestrion/bundler/rollup.js.map +1 -1
- package/build/esm/orchestrion/config/google-genai.js +19 -5
- package/build/esm/orchestrion/config/google-genai.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/esm/utils/cronMonitoring.js +128 -50
- package/build/esm/utils/cronMonitoring.js.map +1 -1
- package/build/types/ai/google-genai/constants.d.ts +3 -0
- package/build/types/ai/google-genai/constants.d.ts.map +1 -1
- package/build/types/ai/google-genai/decisions.d.ts +8 -0
- package/build/types/ai/google-genai/decisions.d.ts.map +1 -0
- package/build/types/ai/google-genai/index.d.ts +3 -1
- package/build/types/ai/google-genai/index.d.ts.map +1 -1
- package/build/types/ai/mistral/index.d.ts.map +1 -1
- package/build/types/ai/mistral/streaming.d.ts +1 -1
- package/build/types/ai/mistral/streaming.d.ts.map +1 -1
- package/build/types/ai/mistral/utils.d.ts +5 -0
- package/build/types/ai/mistral/utils.d.ts.map +1 -1
- package/build/types/ai/vercel-ai/index.d.ts.map +1 -1
- package/build/types/ai/vercel-ai/vercel-ai-attributes.d.ts +3 -0
- package/build/types/ai/vercel-ai/vercel-ai-attributes.d.ts.map +1 -1
- package/build/types/ai/workers-ai/index.d.ts.map +1 -1
- package/build/types/ai/workers-ai/streaming.d.ts +1 -1
- package/build/types/ai/workers-ai/streaming.d.ts.map +1 -1
- package/build/types/index.d.ts +3 -1
- package/build/types/index.d.ts.map +1 -1
- package/build/types/integrations/cron.d.ts.map +1 -1
- package/build/types/integrations/google-genai.d.ts +3 -3
- package/build/types/integrations/google-genai.d.ts.map +1 -1
- package/build/types/integrations/mistral.d.ts.map +1 -1
- package/build/types/integrations/node-cron.d.ts +1 -1
- package/build/types/integrations/node-cron.d.ts.map +1 -1
- package/build/types/integrations/node-schedule.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
- package/build/types/orchestrion/bundler/moduleInjectedTransform.d.ts.map +1 -1
- package/build/types/orchestrion/bundler/rollup.d.ts +3 -3
- package/build/types/orchestrion/bundler/rollup.d.ts.map +1 -1
- package/build/types/orchestrion/channels.d.ts +1 -0
- package/build/types/orchestrion/channels.d.ts.map +1 -1
- package/build/types/orchestrion/config/google-genai.d.ts +13 -0
- package/build/types/orchestrion/config/google-genai.d.ts.map +1 -1
- package/build/types/utils/cronMonitoring.d.ts +4 -5
- package/build/types/utils/cronMonitoring.d.ts.map +1 -1
- package/package.json +3 -3
|
@@ -19,7 +19,7 @@ function rawExternalMatchesModule(external, name) {
|
|
|
19
19
|
* `@rollup/plugin-commonjs` options for builds that bundle CommonJS packages while their
|
|
20
20
|
* dependencies stay external. Builtin `require()`s unwrap to the module (a namespace breaks
|
|
21
21
|
* direct calls) and convert inside `try` blocks (a bare `require` throws in ESM output).
|
|
22
|
-
* Externals keep `'auto'`, which {@link sentryCommonJSInteropPlugin} fixes for Node >= 23.
|
|
22
|
+
* Externals keep `'auto'`, which {@link sentryCommonJSInteropPlugin} fixes for Node >= 23, Deno and Bun.
|
|
23
23
|
*/
|
|
24
24
|
function commonJSInteropOptions() {
|
|
25
25
|
return {
|
|
@@ -29,10 +29,10 @@ function commonJSInteropOptions() {
|
|
|
29
29
|
}
|
|
30
30
|
const COMMONJS_HELPERS_ID = "\0commonjsHelpers.js";
|
|
31
31
|
const BROKEN_NAMESPACE_CHECK = "Object.keys(n).length === 1";
|
|
32
|
-
const FIXED_NAMESPACE_CHECK = "Object.keys(n).filter(k => k !== 'module.exports').length === 1";
|
|
32
|
+
const FIXED_NAMESPACE_CHECK = "(Object.keys(n).filter(k => k !== 'module.exports').length === 1 || (typeof n['default'] === 'function' && Object.keys(n).every(k => k === 'default' || k === 'module.exports' || n[k] === n['default'][k]) && Object.keys(n).some(k => Object.getOwnPropertyDescriptor(n['default'], k)?.enumerable === false)))";
|
|
33
33
|
/**
|
|
34
|
-
* Fixes `@rollup/plugin-commonjs`' `'auto'` interop for Node >= 23 by patching the
|
|
35
|
-
* namespace check in its helpers module. The patch applies only while the exact broken
|
|
34
|
+
* Fixes `@rollup/plugin-commonjs`' `'auto'` interop for Node >= 23, Deno and Bun by patching the
|
|
35
|
+
* broken namespace check in its helpers module. The patch applies only while the exact broken
|
|
36
36
|
* expression exists, so it retires itself once the plugin is fixed upstream.
|
|
37
37
|
*/
|
|
38
38
|
function sentryCommonJSInteropPlugin() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rollup.js","names":["externalEntryMatchesModule","isBuiltin","instrumentedModuleNames","codeTransformer","orchestrionTransformOptions","resolveOrchestrionRuntimeRequest","externalizedModulesWarning"],"sources":["../../../../src/orchestrion/bundler/rollup.ts"],"sourcesContent":["import { isBuiltin } from 'node:module';\n\nimport codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/rollup';\nimport type {\n ExternalOption,\n InputOptions,\n NormalizedInputOptions,\n Plugin,\n PluginContext,\n ResolveIdHook,\n} from 'rollup';\n\nexport type { Plugin as RollupPlugin } from 'rollup';\nimport { instrumentedModuleNames } from '../config';\nimport type { PluginOptions } from './options';\nimport { externalEntryMatchesModule, externalizedModulesWarning, orchestrionTransformOptions } from './options';\nimport { resolveOrchestrionRuntimeRequest, SNIPPET_IMPORT_SPECIFIER } from './resolve';\n\n/**\n * Whether a raw (un-normalized) `external` input option marks `name` as\n * external. String entries use the shared subpath-aware matching so a\n * `'mysql/lib/...'` entry flags `mysql`, consistent with the esbuild and\n * webpack plugins.\n */\nfunction rawExternalMatchesModule(external: ExternalOption, name: string): boolean {\n if (typeof external === 'function') {\n return !!external(name, undefined, false);\n }\n const entries = Array.isArray(external) ? external : [external];\n return entries.some(entry =>\n typeof entry === 'string' ? externalEntryMatchesModule(entry, name) : entry.test(name),\n );\n}\n\n/**\n * Structural subset of `@rollup/plugin-commonjs` options, so this package needs no dependency on\n * the plugin for its types.\n */\nexport interface CommonJSInteropOptions {\n requireReturnsDefault: (id: string) => boolean | 'auto' | 'preferred' | 'namespace';\n ignoreTryCatch: (id: string) => boolean;\n}\n\n/**\n * `@rollup/plugin-commonjs` options for builds that bundle CommonJS packages while their\n * dependencies stay external. Builtin `require()`s unwrap to the module (a namespace breaks\n * direct calls) and convert inside `try` blocks (a bare `require` throws in ESM output).\n * Externals keep `'auto'`, which {@link sentryCommonJSInteropPlugin} fixes for Node >= 23.\n */\nexport function commonJSInteropOptions(): CommonJSInteropOptions {\n return {\n requireReturnsDefault: id => (isBuiltin(id) ? true : 'auto'),\n ignoreTryCatch: id => !isBuiltin(id),\n };\n}\n\nconst COMMONJS_HELPERS_ID = '\\0commonjsHelpers.js';\n\n// The plugin's `'auto'` helper unwraps a required external module only when `default` is the\n// sole key on its namespace. Node >= 23
|
|
1
|
+
{"version":3,"file":"rollup.js","names":["externalEntryMatchesModule","isBuiltin","instrumentedModuleNames","codeTransformer","orchestrionTransformOptions","resolveOrchestrionRuntimeRequest","externalizedModulesWarning"],"sources":["../../../../src/orchestrion/bundler/rollup.ts"],"sourcesContent":["import { isBuiltin } from 'node:module';\n\nimport codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/rollup';\nimport type {\n ExternalOption,\n InputOptions,\n NormalizedInputOptions,\n Plugin,\n PluginContext,\n ResolveIdHook,\n} from 'rollup';\n\nexport type { Plugin as RollupPlugin } from 'rollup';\nimport { instrumentedModuleNames } from '../config';\nimport type { PluginOptions } from './options';\nimport { externalEntryMatchesModule, externalizedModulesWarning, orchestrionTransformOptions } from './options';\nimport { resolveOrchestrionRuntimeRequest, SNIPPET_IMPORT_SPECIFIER } from './resolve';\n\n/**\n * Whether a raw (un-normalized) `external` input option marks `name` as\n * external. String entries use the shared subpath-aware matching so a\n * `'mysql/lib/...'` entry flags `mysql`, consistent with the esbuild and\n * webpack plugins.\n */\nfunction rawExternalMatchesModule(external: ExternalOption, name: string): boolean {\n if (typeof external === 'function') {\n return !!external(name, undefined, false);\n }\n const entries = Array.isArray(external) ? external : [external];\n return entries.some(entry =>\n typeof entry === 'string' ? externalEntryMatchesModule(entry, name) : entry.test(name),\n );\n}\n\n/**\n * Structural subset of `@rollup/plugin-commonjs` options, so this package needs no dependency on\n * the plugin for its types.\n */\nexport interface CommonJSInteropOptions {\n requireReturnsDefault: (id: string) => boolean | 'auto' | 'preferred' | 'namespace';\n ignoreTryCatch: (id: string) => boolean;\n}\n\n/**\n * `@rollup/plugin-commonjs` options for builds that bundle CommonJS packages while their\n * dependencies stay external. Builtin `require()`s unwrap to the module (a namespace breaks\n * direct calls) and convert inside `try` blocks (a bare `require` throws in ESM output).\n * Externals keep `'auto'`, which {@link sentryCommonJSInteropPlugin} fixes for Node >= 23, Deno and Bun.\n */\nexport function commonJSInteropOptions(): CommonJSInteropOptions {\n return {\n requireReturnsDefault: id => (isBuiltin(id) ? true : 'auto'),\n ignoreTryCatch: id => !isBuiltin(id),\n };\n}\n\nconst COMMONJS_HELPERS_ID = '\\0commonjsHelpers.js';\n\n// The plugin's `'auto'` helper unwraps a required external module only when `default` is the\n// sole key on its namespace. Node >= 23 and Deno add a `'module.exports'` key to every CommonJS\n// namespace (nodejs/node#53848), so ignoring that key restores the check there. Bun adds a key\n// for each own property of `module.exports`, which for a function includes the non-enumerable\n// `length` and `name`. So on Bun, a namespace whose keys all mirror its function default, at least\n// one of them a non-enumerable property, is unwrapped. An ES module namespace can match only when\n// its named exports equal the same properties of its default export, which loses nothing.\nconst BROKEN_NAMESPACE_CHECK = 'Object.keys(n).length === 1';\nconst FIXED_NAMESPACE_CHECK =\n \"(Object.keys(n).filter(k => k !== 'module.exports').length === 1 || (typeof n['default'] === 'function' && Object.keys(n).every(k => k === 'default' || k === 'module.exports' || n[k] === n['default'][k]) && Object.keys(n).some(k => Object.getOwnPropertyDescriptor(n['default'], k)?.enumerable === false)))\";\n\n/**\n * Fixes `@rollup/plugin-commonjs`' `'auto'` interop for Node >= 23, Deno and Bun by patching the\n * broken namespace check in its helpers module. The patch applies only while the exact broken\n * expression exists, so it retires itself once the plugin is fixed upstream.\n */\nexport function sentryCommonJSInteropPlugin(): Plugin {\n return {\n name: 'sentry-commonjs-interop',\n transform(code: string, id: string) {\n if (id !== COMMONJS_HELPERS_ID || !code.includes(BROKEN_NAMESPACE_CHECK)) {\n return null;\n }\n return { code: code.replace(BROKEN_NAMESPACE_CHECK, FIXED_NAMESPACE_CHECK), map: null };\n },\n };\n}\n\n/**\n * Rollup plugin that runs the orchestrion code transform on the bundled output.\n *\n * Use when bundling a Node app with Rollup. For unbundled Node processes use the\n * runtime hook instead (`node --import @sentry/node/orchestrion app.js`).\n *\n * @example\n * ```ts\n * // rollup.config.js\n * import { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/rollup';\n * export default { plugins: [sentryOrchestrionPlugin()] };\n * ```\n */\nexport function sentryOrchestrionPlugin(options: PluginOptions = {}): Plugin {\n if (options.buildTimeInstrumentation === false) {\n // Inert plugin — no code transform, so no instrumentation lands in the bundle.\n return { name: 'sentry-orchestrion-disabled' };\n }\n\n const moduleNames = instrumentedModuleNames(options.instrumentations);\n\n // Rolldown omits `external` from the normalized options passed to\n // `buildStart` (function-typed options don't cross its Rust/JS boundary —\n // rolldown/rolldown#1041), so capture the raw value for the probe below.\n let rawExternal: ExternalOption | undefined;\n\n return {\n ...codeTransformer(orchestrionTransformOptions(options)),\n options(inputOptions: InputOptions): null {\n rawExternal = inputOptions.external;\n return null;\n },\n // The module-injected snippet imports `@sentry/server-utils` from INSIDE\n // transformed `node_modules` files. Under isolated installs (pnpm) that bare\n // specifier doesn't resolve from an instrumented package's location, so when\n // normal resolution fails, fall back to this package's own resolution so it\n // gets bundled from its real on-disk path.\n //\n // Forward `options` unchanged: it carries the `custom` metadata `@rollup/plugin-commonjs`\n // uses to recognize a `require()` it is already resolving. Drop it and that plugin warns\n // (THIS_RESOLVE_WITHOUT_OPTIONS), then abandons the resolution.\n async resolveId(\n this: PluginContext,\n source: string,\n importer: string | undefined,\n options: Parameters<ResolveIdHook>[2],\n ) {\n if (source !== SNIPPET_IMPORT_SPECIFIER) {\n return null;\n }\n const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });\n if (resolved) {\n return resolved;\n }\n return resolveOrchestrionRuntimeRequest(source) ?? null;\n },\n buildStart(this: PluginContext, rollupOptions: NormalizedInputOptions): void {\n // An externalized dependency never passes through the code transform, so\n // its diagnostics_channel calls are silently never injected. Rollup has\n // normalized `external` into a single predicate by the time buildStart\n // runs; Rolldown doesn't provide it here at all, so probe the raw value\n // captured in the `options` hook instead.\n const externalizedModules = moduleNames.filter(name =>\n typeof rollupOptions.external === 'function'\n ? rollupOptions.external(name, undefined, false)\n : rawExternal != null && rawExternalMatchesModule(rawExternal, name),\n );\n if (externalizedModules.length > 0) {\n this.warn(externalizedModulesWarning(externalizedModules));\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAwBA,SAAS,yBAAyB,UAA0B,MAAuB;CACjF,IAAI,OAAO,aAAa,YACtB,OAAO,CAAC,CAAC,SAAS,MAAM,KAAA,GAAW,KAAK;CAG1C,QADgB,MAAM,QAAQ,QAAQ,IAAI,WAAW,CAAC,QAAQ,EAAA,CAC/C,MAAK,UAClB,OAAO,UAAU,WAAWA,gBAAAA,2BAA2B,OAAO,IAAI,IAAI,MAAM,KAAK,IAAI,CACvF;AACF;;;;;;;AAiBA,SAAgB,yBAAiD;CAC/D,OAAO;EACL,wBAAuB,QAAA,GAAOC,YAAAA,UAAAA,CAAU,EAAE,IAAI,OAAO;EACrD,iBAAgB,OAAM,EAAA,GAACA,YAAAA,UAAAA,CAAU,EAAE;CAC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}
|
|
15
|
+
},
|
|
16
|
+
"decisions.create": { operation: "decide" }
|
|
16
17
|
};
|
|
17
18
|
const GOOGLE_GENAI_SYSTEM_NAME = "google_genai";
|
|
18
19
|
export { GOOGLE_GENAI_INTEGRATION_NAME, GOOGLE_GENAI_METHOD_REGISTRY, GOOGLE_GENAI_SYSTEM_NAME };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.js","names":[],"sources":["../../../../src/ai/google-genai/constants.ts"],"sourcesContent":["import type { InstrumentedMethodRegistry } from '../core/utils';\n\nexport const GOOGLE_GENAI_INTEGRATION_NAME = 'Google_GenAI' as const;\n\n// https://ai.google.dev/api/rest/v1/models/generateContent\n// https://ai.google.dev/api/rest/v1/chats/sendMessage\n// https://googleapis.github.io/js-genai/release_docs/classes/models.Models.html#generatecontentstream\n// https://googleapis.github.io/js-genai/release_docs/classes/chats.Chat.html#sendmessagestream\nexport const GOOGLE_GENAI_METHOD_REGISTRY = {\n 'models.generateContent': { operation: 'generate_content' },\n 'models.generateContentStream': { operation: 'generate_content', streaming: true },\n 'models.embedContent': { operation: 'embeddings' },\n 'chats.create': { proxyResultPath: 'chat' },\n 'chat.sendMessage': { operation: 'chat' },\n 'chat.sendMessageStream': { operation: 'chat', streaming: true },\n} as const satisfies InstrumentedMethodRegistry;\n\n// Constants for internal use\nexport const GOOGLE_GENAI_SYSTEM_NAME = 'google_genai';\n"],"mappings":";AAEA,MAAa,gCAAgC;
|
|
1
|
+
{"version":3,"file":"constants.js","names":[],"sources":["../../../../src/ai/google-genai/constants.ts"],"sourcesContent":["import type { InstrumentedMethodRegistry } from '../core/utils';\n\nexport const GOOGLE_GENAI_INTEGRATION_NAME = 'Google_GenAI' as const;\n\n// https://ai.google.dev/api/rest/v1/models/generateContent\n// https://ai.google.dev/api/rest/v1/chats/sendMessage\n// https://googleapis.github.io/js-genai/release_docs/classes/models.Models.html#generatecontentstream\n// https://googleapis.github.io/js-genai/release_docs/classes/chats.Chat.html#sendmessagestream\n// https://ai.google.dev/api/decisions\nexport const GOOGLE_GENAI_METHOD_REGISTRY = {\n 'models.generateContent': { operation: 'generate_content' },\n 'models.generateContentStream': { operation: 'generate_content', streaming: true },\n 'models.embedContent': { operation: 'embeddings' },\n 'chats.create': { proxyResultPath: 'chat' },\n 'chat.sendMessage': { operation: 'chat' },\n 'chat.sendMessageStream': { operation: 'chat', streaming: true },\n 'decisions.create': { operation: 'decide' },\n} as const satisfies InstrumentedMethodRegistry;\n\n// Constants for internal use\nexport const GOOGLE_GENAI_SYSTEM_NAME = 'google_genai';\n"],"mappings":";AAEA,MAAa,gCAAgC;AAO7C,MAAa,+BAA+B;CAC1C,0BAA0B,EAAE,WAAW,mBAAmB;CAC1D,gCAAgC;EAAE,WAAW;EAAoB,WAAW;CAAK;CACjF,uBAAuB,EAAE,WAAW,aAAa;CACjD,gBAAgB,EAAE,iBAAiB,OAAO;CAC1C,oBAAoB,EAAE,WAAW,OAAO;CACxC,0BAA0B;EAAE,WAAW;EAAQ,WAAW;CAAK;CAC/D,oBAAoB,EAAE,WAAW,SAAS;AAC5C;AAGA,MAAa,2BAA2B"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { getEvaluationInputMessages, getEvaluationOutputMessages, getTokenUsageAttributes } from "../core/utils.js";
|
|
2
|
+
import { GEN_AI_OUTPUT_MESSAGES } from "@sentry/conventions/attributes";
|
|
3
|
+
import { isObjectLike } from "@sentry/core";
|
|
4
|
+
// src/ai/google-genai/decisions.ts
|
|
5
|
+
/**
|
|
6
|
+
* Serialize a decisions request. Its evidence is `input` where Jev's is `state`; it is recorded as `state`
|
|
7
|
+
* so both render the same.
|
|
8
|
+
*/
|
|
9
|
+
function getDecisionInputMessages(params) {
|
|
10
|
+
return getEvaluationInputMessages({
|
|
11
|
+
state: params.input,
|
|
12
|
+
questions: params.questions
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
function addDecisionResponseAttributes(span, response, recordOutputs) {
|
|
16
|
+
if (!isObjectLike(response)) return;
|
|
17
|
+
if (isObjectLike(response.usage)) {
|
|
18
|
+
const usage = response.usage;
|
|
19
|
+
span.setAttributes(getTokenUsageAttributes(usage.total_input_tokens, usage.total_output_tokens, void 0, usage.total_cached_tokens, usage.total_tokens));
|
|
20
|
+
}
|
|
21
|
+
if (recordOutputs && response.answers !== void 0) span.setAttribute(GEN_AI_OUTPUT_MESSAGES, getEvaluationOutputMessages(response.answers));
|
|
22
|
+
}
|
|
23
|
+
export { addDecisionResponseAttributes, getDecisionInputMessages };
|
|
24
|
+
|
|
25
|
+
//# sourceMappingURL=decisions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"decisions.js","names":[],"sources":["../../../../src/ai/google-genai/decisions.ts"],"sourcesContent":["// Google's questions and answers already use Jev's layout, so only the evaluated input is renamed.\nimport { GEN_AI_OUTPUT_MESSAGES } from '@sentry/conventions/attributes';\nimport type { Span } from '@sentry/core';\nimport { isObjectLike } from '@sentry/core';\nimport { getEvaluationInputMessages, getEvaluationOutputMessages, getTokenUsageAttributes } from '../core/utils';\n\n/**\n * Serialize a decisions request. Its evidence is `input` where Jev's is `state`; it is recorded as `state`\n * so both render the same.\n */\nexport function getDecisionInputMessages(params: Record<string, unknown>): string | undefined {\n return getEvaluationInputMessages({ state: params.input, questions: params.questions });\n}\n\nexport function addDecisionResponseAttributes(span: Span, response: unknown, recordOutputs: boolean): void {\n if (!isObjectLike(response)) {\n return;\n }\n\n if (isObjectLike(response.usage)) {\n const usage = response.usage as Record<string, number | undefined>;\n span.setAttributes(\n getTokenUsageAttributes(\n usage.total_input_tokens,\n usage.total_output_tokens,\n undefined,\n usage.total_cached_tokens,\n usage.total_tokens,\n ),\n );\n }\n\n if (recordOutputs && response.answers !== undefined) {\n span.setAttribute(GEN_AI_OUTPUT_MESSAGES, getEvaluationOutputMessages(response.answers));\n }\n}\n"],"mappings":";;;;;;;;AAUA,SAAgB,yBAAyB,QAAqD;CAC5F,OAAO,2BAA2B;EAAE,OAAO,OAAO;EAAO,WAAW,OAAO;CAAU,CAAC;AACxF;AAEA,SAAgB,8BAA8B,MAAY,UAAmB,eAA8B;CACzG,IAAI,CAAC,aAAa,QAAQ,GACxB;CAGF,IAAI,aAAa,SAAS,KAAK,GAAG;EAChC,MAAM,QAAQ,SAAS;EACvB,KAAK,cACH,wBACE,MAAM,oBACN,MAAM,qBACN,KAAA,GACA,MAAM,qBACN,MAAM,YACR,CACF;CACF;CAEA,IAAI,iBAAiB,SAAS,YAAY,KAAA,GACxC,KAAK,aAAa,wBAAwB,4BAA4B,SAAS,OAAO,CAAC;AAE3F"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { buildMethodPath, getErrorStatus, getGenAiSpanOp, getTokenUsageAttributes, resolveAIRecordingOptions } from "../core/utils.js";
|
|
1
|
+
import { buildMethodPath, getErrorStatus, getGenAiSpanOp, getRequestSignal, getTokenUsageAttributes, resolveAIRecordingOptions } from "../core/utils.js";
|
|
2
2
|
import { GOOGLE_GENAI_METHOD_REGISTRY, GOOGLE_GENAI_SYSTEM_NAME } from "./constants.js";
|
|
3
|
+
import { addDecisionResponseAttributes, getDecisionInputMessages } from "./decisions.js";
|
|
3
4
|
import { instrumentStream } from "./streaming.js";
|
|
4
5
|
import { candidatesToMessageParts, contentUnionToMessages, setOutputMessagesAttribute, systemInstructionToText } from "./utils.js";
|
|
5
6
|
import { GEN_AI_EMBEDDINGS_INPUT, GEN_AI_INPUT_MESSAGES, GEN_AI_OPERATION_NAME, GEN_AI_PROVIDER_NAME, GEN_AI_REQUEST_FREQUENCY_PENALTY, GEN_AI_REQUEST_MAX_TOKENS, GEN_AI_REQUEST_MODEL, GEN_AI_REQUEST_PRESENCE_PENALTY, GEN_AI_REQUEST_TEMPERATURE, GEN_AI_REQUEST_TOP_K, GEN_AI_REQUEST_TOP_P, GEN_AI_RESPONSE_MODEL, GEN_AI_RESPONSE_TEXT, GEN_AI_RESPONSE_TOOL_CALLS, GEN_AI_SYSTEM_INSTRUCTIONS, GEN_AI_TOOL_DEFINITIONS, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
|
|
@@ -51,6 +52,8 @@ function extractRequestAttributes(operationName, params, context, recordInputs =
|
|
|
51
52
|
attributes[GEN_AI_TOOL_DEFINITIONS] = JSON.stringify(functionDeclarations);
|
|
52
53
|
}
|
|
53
54
|
}
|
|
55
|
+
const decisionInput = recordInputs && operationName === "decide" ? getDecisionInputMessages(params) : void 0;
|
|
56
|
+
if (decisionInput) attributes[GEN_AI_INPUT_MESSAGES] = decisionInput;
|
|
54
57
|
} else attributes[GEN_AI_REQUEST_MODEL] = extractModel({}, context);
|
|
55
58
|
return attributes;
|
|
56
59
|
}
|
|
@@ -82,8 +85,12 @@ function addPrivateRequestAttributes(span, params, operationName) {
|
|
|
82
85
|
* Add response attributes from the Google GenAI response
|
|
83
86
|
* @see https://github.com/googleapis/js-genai/blob/v1.19.0/src/types.ts#L2313
|
|
84
87
|
*/
|
|
85
|
-
function addResponseAttributes(span, response, recordOutputs) {
|
|
88
|
+
function addResponseAttributes(span, response, recordOutputs, operationName) {
|
|
86
89
|
if (!response || typeof response !== "object") return;
|
|
90
|
+
if (operationName === "decide") {
|
|
91
|
+
addDecisionResponseAttributes(span, response, !!recordOutputs);
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
87
94
|
if (response.modelVersion) span.setAttribute(GEN_AI_RESPONSE_MODEL, response.modelVersion);
|
|
88
95
|
if (response.usageMetadata && typeof response.usageMetadata === "object") {
|
|
89
96
|
const usage = response.usageMetadata;
|
|
@@ -132,6 +139,10 @@ function resolveChatParams(operationName, params, context) {
|
|
|
132
139
|
function getAbortSignal(params) {
|
|
133
140
|
return (params?.config)?.abortSignal;
|
|
134
141
|
}
|
|
142
|
+
/** `decisions.create` takes its abort signal in its request options, not in a `config`. */
|
|
143
|
+
function getCallAbortSignal(operationName, params, requestOptions) {
|
|
144
|
+
return operationName === "decide" ? getRequestSignal(requestOptions) : getAbortSignal(params);
|
|
145
|
+
}
|
|
135
146
|
/**
|
|
136
147
|
* Instrument any async or synchronous genai method with Sentry spans
|
|
137
148
|
* Handles operations like models.generateContent and chat.sendMessage and chats.create
|
|
@@ -143,7 +154,7 @@ function instrumentMethod(originalMethod, methodPath, instrumentedMethod, contex
|
|
|
143
154
|
const operationName = instrumentedMethod.operation || "unknown";
|
|
144
155
|
const params = args[0];
|
|
145
156
|
const attributeParams = resolveChatParams(operationName, params, context);
|
|
146
|
-
const abortSignal =
|
|
157
|
+
const abortSignal = getCallAbortSignal(operationName, attributeParams, args[1]);
|
|
147
158
|
const requestAttributes = extractRequestAttributes(operationName, attributeParams, context, !!options.recordInputs);
|
|
148
159
|
const model = requestAttributes[GEN_AI_REQUEST_MODEL] || "unknown";
|
|
149
160
|
const client = getClient();
|
|
@@ -170,7 +181,7 @@ function instrumentMethod(originalMethod, methodPath, instrumentedMethod, contex
|
|
|
170
181
|
}, (span) => {
|
|
171
182
|
if (options.recordInputs && attributeParams) addPrivateRequestAttributes(span, attributeParams, operationName);
|
|
172
183
|
return handleCallbackErrors(() => target.apply(context, args), () => span.setStatus(getErrorStatus(abortSignal)), () => {}, (result) => {
|
|
173
|
-
if (!isEmbeddings) addResponseAttributes(span, result, options.recordOutputs);
|
|
184
|
+
if (!isEmbeddings) addResponseAttributes(span, result, options.recordOutputs, operationName);
|
|
174
185
|
});
|
|
175
186
|
});
|
|
176
187
|
} });
|
|
@@ -254,6 +265,6 @@ function createDeepProxy(target, currentPath = "", options) {
|
|
|
254
265
|
function instrumentGoogleGenAIClient(client, options) {
|
|
255
266
|
return createDeepProxy(client, "", resolveAIRecordingOptions(options));
|
|
256
267
|
}
|
|
257
|
-
export { addPrivateRequestAttributes, addResponseAttributes, extractModel, extractRequestAttributes, getAbortSignal, instrumentGoogleGenAIClient, resolveChatParams };
|
|
268
|
+
export { addPrivateRequestAttributes, addResponseAttributes, extractModel, extractRequestAttributes, getAbortSignal, getCallAbortSignal, instrumentGoogleGenAIClient, resolveChatParams };
|
|
258
269
|
|
|
259
270
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/ai/google-genai/index.ts"],"sourcesContent":["/* eslint-disable typescript-eslint/no-deprecated */\n/* eslint-disable max-lines */\nimport {\n getClient,\n handleCallbackErrors,\n hasSpanStreamingEnabled,\n startSpan,\n startSpanManual,\n stringify,\n} from '@sentry/core';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_FREQUENCY_PENALTY,\n GEN_AI_REQUEST_MAX_TOKENS,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_REQUEST_PRESENCE_PENALTY,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_K,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_DEFINITIONS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport type { InstrumentedMethodEntry } from '../core/utils';\nimport {\n buildMethodPath,\n getErrorStatus,\n getGenAiSpanOp,\n getTokenUsageAttributes,\n resolveAIRecordingOptions,\n} from '../core/utils';\nimport { GOOGLE_GENAI_METHOD_REGISTRY, GOOGLE_GENAI_SYSTEM_NAME } from './constants';\nimport { instrumentStream } from './streaming';\nimport type { Candidate, ContentPart, GoogleGenAIOptions, GoogleGenAIResponse } from './types';\nimport type { ContentListUnion, Message, PartListUnion } from './utils';\nimport {\n candidatesToMessageParts,\n contentUnionToMessages,\n setOutputMessagesAttribute,\n systemInstructionToText,\n} from './utils';\n\n/**\n * Extract model from parameters or chat context object\n * For chat instances, the model is available on the chat object as 'model' (older versions) or 'modelVersion' (newer versions)\n */\nexport function extractModel(params: Record<string, unknown>, context?: unknown): string {\n if ('model' in params && typeof params.model === 'string') {\n return params.model;\n }\n\n // Try to get model from chat context object (chat instance has model property)\n if (context && typeof context === 'object') {\n const contextObj = context as Record<string, unknown>;\n\n // Check for 'model' property (older versions, and streaming)\n if ('model' in contextObj && typeof contextObj.model === 'string') {\n return contextObj.model;\n }\n\n // Check for 'modelVersion' property (newer versions)\n if ('modelVersion' in contextObj && typeof contextObj.modelVersion === 'string') {\n return contextObj.modelVersion;\n }\n }\n\n return 'unknown';\n}\n\n/**\n * Extract generation config parameters\n */\nfunction extractConfigAttributes(config: Record<string, unknown>): Record<string, SpanAttributeValue> {\n const attributes: Record<string, SpanAttributeValue> = {};\n\n if ('temperature' in config && typeof config.temperature === 'number') {\n attributes[GEN_AI_REQUEST_TEMPERATURE] = config.temperature;\n }\n if ('topP' in config && typeof config.topP === 'number') {\n attributes[GEN_AI_REQUEST_TOP_P] = config.topP;\n }\n if ('topK' in config && typeof config.topK === 'number') {\n attributes[GEN_AI_REQUEST_TOP_K] = config.topK;\n }\n if ('maxOutputTokens' in config && typeof config.maxOutputTokens === 'number') {\n attributes[GEN_AI_REQUEST_MAX_TOKENS] = config.maxOutputTokens;\n }\n if ('frequencyPenalty' in config && typeof config.frequencyPenalty === 'number') {\n attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY] = config.frequencyPenalty;\n }\n if ('presencePenalty' in config && typeof config.presencePenalty === 'number') {\n attributes[GEN_AI_REQUEST_PRESENCE_PENALTY] = config.presencePenalty;\n }\n\n return attributes;\n}\n\n/**\n * Extract request attributes from method arguments\n * Builds the base attributes for span creation including system info, model, and config\n */\nexport function extractRequestAttributes(\n operationName: string,\n params?: Record<string, unknown>,\n context?: unknown,\n recordInputs = true,\n): Record<string, SpanAttributeValue> {\n const attributes: Record<string, SpanAttributeValue> = {\n [GEN_AI_PROVIDER_NAME]: GOOGLE_GENAI_SYSTEM_NAME,\n [GEN_AI_OPERATION_NAME]: operationName,\n [SENTRY_ORIGIN]: 'auto.ai.google_genai',\n };\n\n if (params) {\n attributes[GEN_AI_REQUEST_MODEL] = extractModel(params, context);\n\n // Extract generation config parameters\n if ('config' in params && typeof params.config === 'object' && params.config) {\n const config = params.config as Record<string, unknown>;\n Object.assign(attributes, extractConfigAttributes(config));\n\n // Extract available tools from config\n if (recordInputs && 'tools' in config && Array.isArray(config.tools)) {\n const functionDeclarations = config.tools.flatMap(\n (tool: { functionDeclarations: unknown[] }) => tool.functionDeclarations,\n );\n attributes[GEN_AI_TOOL_DEFINITIONS] = JSON.stringify(functionDeclarations);\n }\n }\n } else {\n attributes[GEN_AI_REQUEST_MODEL] = extractModel({}, context);\n }\n\n return attributes;\n}\n\n/**\n * Add private request attributes to spans.\n * This is only recorded if recordInputs is true.\n * Handles different parameter formats for different Google GenAI methods.\n */\nexport function addPrivateRequestAttributes(span: Span, params: Record<string, unknown>, operationName: string): void {\n if (operationName === 'embeddings') {\n const contents = params.contents;\n if (contents != null) {\n span.setAttribute(GEN_AI_EMBEDDINGS_INPUT, stringify(contents, String));\n }\n return;\n }\n\n // config.systemInstruction: ContentUnion. It has its own attribute, so it never joins the message list.\n if (\n 'config' in params &&\n params.config &&\n typeof params.config === 'object' &&\n 'systemInstruction' in params.config &&\n params.config.systemInstruction\n ) {\n const systemInstructions = systemInstructionToText(params.config.systemInstruction);\n if (systemInstructions) {\n span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS, JSON.stringify([{ type: 'text', content: systemInstructions }]));\n }\n }\n\n const messages: Message[] = [];\n\n // For chats.create: history contains the conversation history\n if ('history' in params) {\n messages.push(...contentUnionToMessages(params.history as PartListUnion, 'user'));\n }\n\n // For models.generateContent: ContentListUnion\n if ('contents' in params) {\n messages.push(...contentUnionToMessages(params.contents as ContentListUnion, 'user'));\n }\n\n // For chat.sendMessage: message can be PartListUnion\n if ('message' in params) {\n messages.push(...contentUnionToMessages(params.message as PartListUnion, 'user'));\n }\n\n if (messages.length) {\n span.setAttributes({\n [GEN_AI_INPUT_MESSAGES]: stringify(messages),\n });\n }\n}\n\n/**\n * Add response attributes from the Google GenAI response\n * @see https://github.com/googleapis/js-genai/blob/v1.19.0/src/types.ts#L2313\n */\nexport function addResponseAttributes(span: Span, response: GoogleGenAIResponse, recordOutputs?: boolean): void {\n if (!response || typeof response !== 'object') return;\n\n if (response.modelVersion) {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, response.modelVersion);\n }\n\n // Add usage metadata if present\n if (response.usageMetadata && typeof response.usageMetadata === 'object') {\n const usage = response.usageMetadata;\n const hasOutput = typeof usage.candidatesTokenCount === 'number' || typeof usage.thoughtsTokenCount === 'number';\n span.setAttributes(\n getTokenUsageAttributes(\n typeof usage.promptTokenCount === 'number'\n ? usage.promptTokenCount + (usage.toolUsePromptTokenCount ?? 0)\n : undefined,\n hasOutput ? (usage.candidatesTokenCount ?? 0) + (usage.thoughtsTokenCount ?? 0) : undefined,\n undefined,\n usage.cachedContentTokenCount,\n usage.totalTokenCount,\n ),\n );\n if (typeof usage.thoughtsTokenCount === 'number') {\n span.setAttribute(GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, usage.thoughtsTokenCount);\n }\n }\n\n if (recordOutputs) {\n setOutputMessagesAttribute(span, candidatesToMessageParts(response.candidates));\n }\n\n // Add response text if recordOutputs is enabled\n if (recordOutputs && Array.isArray(response.candidates) && response.candidates.length > 0) {\n const responseTexts = response.candidates\n .map((candidate: Candidate) => {\n if (candidate.content?.parts && Array.isArray(candidate.content.parts)) {\n return candidate.content.parts\n .map((part: ContentPart) => (typeof part.text === 'string' ? part.text : ''))\n .filter((text: string) => text.length > 0)\n .join('');\n }\n return '';\n })\n .filter((text: string) => text.length > 0);\n\n if (responseTexts.length > 0) {\n span.setAttributes({\n [GEN_AI_RESPONSE_TEXT]: responseTexts.join(''),\n });\n }\n }\n\n // Add tool calls if recordOutputs is enabled\n if (recordOutputs && response.functionCalls) {\n const functionCalls = response.functionCalls;\n if (Array.isArray(functionCalls) && functionCalls.length > 0) {\n span.setAttributes({\n [GEN_AI_RESPONSE_TOOL_CALLS]: JSON.stringify(functionCalls),\n });\n }\n }\n}\n\n/**\n * Recover the config a chat message sends but does not carry in its own arguments.\n *\n * `chats.create()` takes a config that `@google/genai` reuses for every message, resolving each\n * request as `params.config ?? chat.config`. A per-message config therefore replaces the chat\n * config rather than merging into it, and the chat config applies only when the message omits one.\n * That config lives on the chat instance, which both instrumentation paths already hold: the client\n * proxy passes it as the method's `context`, the diagnostics-channel path as `data.self`.\n *\n * The chat `history` stays off the message spans. The SDK does send it, folded into `contents`, and\n * the instance carries the whole transcript, but repeating every past turn on every message span\n * duplicates what earlier spans already reported and grows without bound.\n */\nexport function resolveChatParams(\n operationName: string,\n params: Record<string, unknown> | undefined,\n context: unknown,\n): Record<string, unknown> | undefined {\n // `!= null` mirrors the SDK's `??`: an explicit `null` config falls back to the chat's.\n if (operationName !== 'chat' || params?.config != null || !context || typeof context !== 'object') {\n return params;\n }\n\n const chatConfig = (context as Record<string, unknown>).config;\n if (!chatConfig || typeof chatConfig !== 'object') {\n return params;\n }\n\n return { ...params, config: chatConfig };\n}\n\n/**\n * Reads the caller's `config.abortSignal` from params resolved by `resolveChatParams`.\n */\nexport function getAbortSignal(params: Record<string, unknown> | undefined): AbortSignal | undefined {\n return (params?.config as { abortSignal?: AbortSignal } | undefined)?.abortSignal;\n}\n\n/**\n * Instrument any async or synchronous genai method with Sentry spans\n * Handles operations like models.generateContent and chat.sendMessage and chats.create\n * @see https://docs.sentry.io/platforms/javascript/guides/node/tracing/instrumentation/ai-agents-module/#manual-instrumentation\n */\nfunction instrumentMethod<T extends unknown[], R>(\n originalMethod: (...args: T) => R | Promise<R>,\n methodPath: string,\n instrumentedMethod: InstrumentedMethodEntry,\n context: unknown,\n options: GoogleGenAIOptions,\n): (...args: T) => R | Promise<R> {\n const isEmbeddings = instrumentedMethod.operation === 'embeddings';\n\n return new Proxy(originalMethod, {\n apply(target, _, args: T): R | Promise<R> {\n const operationName = instrumentedMethod.operation || 'unknown';\n const params = args[0] as Record<string, unknown> | undefined;\n const attributeParams = resolveChatParams(operationName, params, context);\n const abortSignal = getAbortSignal(attributeParams);\n const requestAttributes = extractRequestAttributes(\n operationName,\n attributeParams,\n context,\n !!options.recordInputs,\n );\n const model = requestAttributes[GEN_AI_REQUEST_MODEL] || 'unknown';\n const client = getClient();\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n const spanName =\n (typeof model === 'string' && model !== 'unknown') || !(client && hasSpanStreamingEnabled(client))\n ? `${operationName} ${model}`\n : operationName;\n\n // Check if this is a streaming method\n if (instrumentedMethod.streaming) {\n // Use startSpanManual for streaming methods to control span lifecycle\n return startSpanManual(\n {\n name: spanName,\n op: getGenAiSpanOp(operationName),\n attributes: requestAttributes,\n },\n async (span: Span) => {\n try {\n if (options.recordInputs && attributeParams) {\n addPrivateRequestAttributes(span, attributeParams, operationName);\n }\n const stream = await target.apply(context, args);\n return instrumentStream(stream, span, Boolean(options.recordOutputs), abortSignal) as R;\n } catch (error) {\n span.setStatus(getErrorStatus(abortSignal));\n span.end();\n throw error;\n }\n },\n );\n }\n // Single span for both sync and async operations\n return startSpan(\n {\n name: spanName,\n op: getGenAiSpanOp(operationName),\n attributes: requestAttributes,\n },\n (span: Span) => {\n if (options.recordInputs && attributeParams) {\n addPrivateRequestAttributes(span, attributeParams, operationName);\n }\n\n // The rejection is rethrown to the caller. `startSpan` keeps the status set here.\n return handleCallbackErrors(\n () => target.apply(context, args),\n () => span.setStatus(getErrorStatus(abortSignal)),\n () => {},\n result => {\n // Only add response attributes for content-producing methods, not for embeddings\n if (!isEmbeddings) {\n addResponseAttributes(span, result, options.recordOutputs);\n }\n },\n );\n },\n );\n },\n });\n}\n\n/**\n * Create a deep proxy for Google GenAI client instrumentation\n * Recursively instruments methods and handles special cases like chats.create\n */\nfunction createDeepProxy<T extends object>(target: T, currentPath = '', options: GoogleGenAIOptions): T {\n const propertyCache = new Map<PropertyKey, { original: unknown; wrapped: unknown }>();\n\n return new Proxy(target, {\n get: (t, prop, receiver) => {\n const value = Reflect.get(t, prop, receiver);\n const cachedEntry = propertyCache.get(prop);\n if (cachedEntry) {\n if (cachedEntry.original === value) {\n return cachedEntry.wrapped;\n }\n propertyCache.delete(prop);\n }\n\n const methodPath = buildMethodPath(currentPath, String(prop));\n\n const instrumentedMethod: InstrumentedMethodEntry | undefined =\n GOOGLE_GENAI_METHOD_REGISTRY[methodPath as keyof typeof GOOGLE_GENAI_METHOD_REGISTRY];\n if (typeof value === 'function' && instrumentedMethod) {\n // If an operation is specified, we need to instrument the method itself\n const wrappedMethod = instrumentedMethod.operation\n ? instrumentMethod(value as (...args: unknown[]) => unknown, methodPath, instrumentedMethod, t, options)\n : value.bind(t);\n\n if (!instrumentedMethod.proxyResultPath) {\n propertyCache.set(prop, { original: value, wrapped: wrappedMethod });\n return wrappedMethod;\n }\n\n // If a proxyResultPath is specified, we need to proxy the result of the method.\n // Note: This currently only properly handles synchronous methods. For async methods,\n // the Promise itself would be proxied instead of the resolved value. Currently we\n // don't have a case where this is needed, so I'll keep it simple for now.\n const methodWithProxiedResult = function (...args: unknown[]): unknown {\n const result = wrappedMethod(...args);\n if (result && typeof result === 'object') {\n return createDeepProxy(result as object, instrumentedMethod.proxyResultPath, options);\n }\n return result;\n };\n propertyCache.set(prop, { original: value, wrapped: methodWithProxiedResult });\n return methodWithProxiedResult;\n }\n\n if (typeof value === 'function') {\n // Bind non-instrumented functions to preserve the original `this` context\n const boundMethod = value.bind(t);\n propertyCache.set(prop, { original: value, wrapped: boundMethod });\n return boundMethod;\n }\n\n if (value && typeof value === 'object') {\n const nestedProxy = createDeepProxy(value, methodPath, options);\n propertyCache.set(prop, { original: value, wrapped: nestedProxy });\n return nestedProxy;\n }\n\n return value;\n },\n });\n}\n\n/**\n * Instrument a Google GenAI client with Sentry tracing\n * Can be used across Node.js, Cloudflare Workers, and Vercel Edge\n *\n * @template T - The type of the client that extends client object\n * @param client - The Google GenAI client to instrument\n * @param options - Optional configuration for recording inputs and outputs\n * @returns The instrumented client with the same type as the input\n *\n * @example\n * ```typescript\n * import { GoogleGenAI } from '@google/genai';\n * import { instrumentGoogleGenAIClient } from '@sentry/node';\n *\n * const genAI = new GoogleGenAI({ apiKey: process.env.GOOGLE_GENAI_API_KEY });\n * const instrumentedClient = instrumentGoogleGenAIClient(genAI);\n *\n * // Now both chats.create and sendMessage will be instrumented\n * const chat = instrumentedClient.chats.create({ model: 'gemini-1.5-pro' });\n * const response = await chat.sendMessage({ message: 'Hello' });\n * ```\n */\nexport function instrumentGoogleGenAIClient<T extends object>(client: T, options?: GoogleGenAIOptions): T {\n return createDeepProxy(client, '', resolveAIRecordingOptions(options));\n}\n"],"mappings":";;;;;;;;;;;AAsDA,SAAgB,aAAa,QAAiC,SAA2B;CACvF,IAAI,WAAW,UAAU,OAAO,OAAO,UAAU,UAC/C,OAAO,OAAO;CAIhB,IAAI,WAAW,OAAO,YAAY,UAAU;EAC1C,MAAM,aAAa;EAGnB,IAAI,WAAW,cAAc,OAAO,WAAW,UAAU,UACvD,OAAO,WAAW;EAIpB,IAAI,kBAAkB,cAAc,OAAO,WAAW,iBAAiB,UACrE,OAAO,WAAW;CAEtB;CAEA,OAAO;AACT;;;;AAKA,SAAS,wBAAwB,QAAqE;CACpG,MAAM,aAAiD,CAAC;CAExD,IAAI,iBAAiB,UAAU,OAAO,OAAO,gBAAgB,UAC3D,WAAW,8BAA8B,OAAO;CAElD,IAAI,UAAU,UAAU,OAAO,OAAO,SAAS,UAC7C,WAAW,wBAAwB,OAAO;CAE5C,IAAI,UAAU,UAAU,OAAO,OAAO,SAAS,UAC7C,WAAW,wBAAwB,OAAO;CAE5C,IAAI,qBAAqB,UAAU,OAAO,OAAO,oBAAoB,UACnE,WAAW,6BAA6B,OAAO;C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AM,KAAK,CAAC;GAEhB,IAAI,CAAC,mBAAmB,iBAAiB;IACvC,cAAc,IAAI,MAAM;KAAE,UAAU;KAAO,SAAS;IAAc,CAAC;IACnE,OAAO;GACT;GAMA,MAAM,0BAA0B,SAAU,GAAG,MAA0B;IACrE,MAAM,SAAS,cAAc,GAAG,IAAI;IACpC,IAAI,UAAU,OAAO,WAAW,UAC9B,OAAO,gBAAgB,QAAkB,mBAAmB,iBAAiB,OAAO;IAEtF,OAAO;GACT;GACA,cAAc,IAAI,MAAM;IAAE,UAAU;IAAO,SAAS;GAAwB,CAAC;GAC7E,OAAO;EACT;EAEA,IAAI,OAAO,UAAU,YAAY;GAE/B,MAAM,cAAc,MAAM,KAAK,CAAC;GAChC,cAAc,IAAI,MAAM;IAAE,UAAU;IAAO,SAAS;GAAY,CAAC;GACjE,OAAO;EACT;EAEA,IAAI,SAAS,OAAO,UAAU,UAAU;GACtC,MAAM,cAAc,gBAAgB,OAAO,YAAY,OAAO;GAC9D,cAAc,IAAI,MAAM;IAAE,UAAU;IAAO,SAAS;GAAY,CAAC;GACjE,OAAO;EACT;EAEA,OAAO;CACT,EACF,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,4BAA8C,QAAW,SAAiC;CACxG,OAAO,gBAAgB,QAAQ,IAAI,0BAA0B,OAAO,CAAC;AACvE"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/ai/google-genai/index.ts"],"sourcesContent":["/* eslint-disable typescript-eslint/no-deprecated */\n/* eslint-disable max-lines */\nimport {\n getClient,\n handleCallbackErrors,\n hasSpanStreamingEnabled,\n startSpan,\n startSpanManual,\n stringify,\n} from '@sentry/core';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_REQUEST_FREQUENCY_PENALTY,\n GEN_AI_REQUEST_MAX_TOKENS,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_REQUEST_PRESENCE_PENALTY,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_K,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_DEFINITIONS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport type { InstrumentedMethodEntry } from '../core/utils';\nimport {\n buildMethodPath,\n getErrorStatus,\n getGenAiSpanOp,\n getRequestSignal,\n getTokenUsageAttributes,\n resolveAIRecordingOptions,\n} from '../core/utils';\nimport { GOOGLE_GENAI_METHOD_REGISTRY, GOOGLE_GENAI_SYSTEM_NAME } from './constants';\nimport { addDecisionResponseAttributes, getDecisionInputMessages } from './decisions';\nimport { instrumentStream } from './streaming';\nimport type { Candidate, ContentPart, GoogleGenAIOptions, GoogleGenAIResponse } from './types';\nimport type { ContentListUnion, Message, PartListUnion } from './utils';\nimport {\n candidatesToMessageParts,\n contentUnionToMessages,\n setOutputMessagesAttribute,\n systemInstructionToText,\n} from './utils';\n\n/**\n * Extract model from parameters or chat context object\n * For chat instances, the model is available on the chat object as 'model' (older versions) or 'modelVersion' (newer versions)\n */\nexport function extractModel(params: Record<string, unknown>, context?: unknown): string {\n if ('model' in params && typeof params.model === 'string') {\n return params.model;\n }\n\n // Try to get model from chat context object (chat instance has model property)\n if (context && typeof context === 'object') {\n const contextObj = context as Record<string, unknown>;\n\n // Check for 'model' property (older versions, and streaming)\n if ('model' in contextObj && typeof contextObj.model === 'string') {\n return contextObj.model;\n }\n\n // Check for 'modelVersion' property (newer versions)\n if ('modelVersion' in contextObj && typeof contextObj.modelVersion === 'string') {\n return contextObj.modelVersion;\n }\n }\n\n return 'unknown';\n}\n\n/**\n * Extract generation config parameters\n */\nfunction extractConfigAttributes(config: Record<string, unknown>): Record<string, SpanAttributeValue> {\n const attributes: Record<string, SpanAttributeValue> = {};\n\n if ('temperature' in config && typeof config.temperature === 'number') {\n attributes[GEN_AI_REQUEST_TEMPERATURE] = config.temperature;\n }\n if ('topP' in config && typeof config.topP === 'number') {\n attributes[GEN_AI_REQUEST_TOP_P] = config.topP;\n }\n if ('topK' in config && typeof config.topK === 'number') {\n attributes[GEN_AI_REQUEST_TOP_K] = config.topK;\n }\n if ('maxOutputTokens' in config && typeof config.maxOutputTokens === 'number') {\n attributes[GEN_AI_REQUEST_MAX_TOKENS] = config.maxOutputTokens;\n }\n if ('frequencyPenalty' in config && typeof config.frequencyPenalty === 'number') {\n attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY] = config.frequencyPenalty;\n }\n if ('presencePenalty' in config && typeof config.presencePenalty === 'number') {\n attributes[GEN_AI_REQUEST_PRESENCE_PENALTY] = config.presencePenalty;\n }\n\n return attributes;\n}\n\n/**\n * Extract request attributes from method arguments\n * Builds the base attributes for span creation including system info, model, and config\n */\nexport function extractRequestAttributes(\n operationName: string,\n params?: Record<string, unknown>,\n context?: unknown,\n recordInputs = true,\n): Record<string, SpanAttributeValue> {\n const attributes: Record<string, SpanAttributeValue> = {\n [GEN_AI_PROVIDER_NAME]: GOOGLE_GENAI_SYSTEM_NAME,\n [GEN_AI_OPERATION_NAME]: operationName,\n [SENTRY_ORIGIN]: 'auto.ai.google_genai',\n };\n\n if (params) {\n attributes[GEN_AI_REQUEST_MODEL] = extractModel(params, context);\n\n // Extract generation config parameters\n if ('config' in params && typeof params.config === 'object' && params.config) {\n const config = params.config as Record<string, unknown>;\n Object.assign(attributes, extractConfigAttributes(config));\n\n // Extract available tools from config\n if (recordInputs && 'tools' in config && Array.isArray(config.tools)) {\n const functionDeclarations = config.tools.flatMap(\n (tool: { functionDeclarations: unknown[] }) => tool.functionDeclarations,\n );\n attributes[GEN_AI_TOOL_DEFINITIONS] = JSON.stringify(functionDeclarations);\n }\n }\n\n const decisionInput = recordInputs && operationName === 'decide' ? getDecisionInputMessages(params) : undefined;\n if (decisionInput) {\n attributes[GEN_AI_INPUT_MESSAGES] = decisionInput;\n }\n } else {\n attributes[GEN_AI_REQUEST_MODEL] = extractModel({}, context);\n }\n\n return attributes;\n}\n\n/**\n * Add private request attributes to spans.\n * This is only recorded if recordInputs is true.\n * Handles different parameter formats for different Google GenAI methods.\n */\nexport function addPrivateRequestAttributes(span: Span, params: Record<string, unknown>, operationName: string): void {\n if (operationName === 'embeddings') {\n const contents = params.contents;\n if (contents != null) {\n span.setAttribute(GEN_AI_EMBEDDINGS_INPUT, stringify(contents, String));\n }\n return;\n }\n\n // config.systemInstruction: ContentUnion. It has its own attribute, so it never joins the message list.\n if (\n 'config' in params &&\n params.config &&\n typeof params.config === 'object' &&\n 'systemInstruction' in params.config &&\n params.config.systemInstruction\n ) {\n const systemInstructions = systemInstructionToText(params.config.systemInstruction);\n if (systemInstructions) {\n span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS, JSON.stringify([{ type: 'text', content: systemInstructions }]));\n }\n }\n\n const messages: Message[] = [];\n\n // For chats.create: history contains the conversation history\n if ('history' in params) {\n messages.push(...contentUnionToMessages(params.history as PartListUnion, 'user'));\n }\n\n // For models.generateContent: ContentListUnion\n if ('contents' in params) {\n messages.push(...contentUnionToMessages(params.contents as ContentListUnion, 'user'));\n }\n\n // For chat.sendMessage: message can be PartListUnion\n if ('message' in params) {\n messages.push(...contentUnionToMessages(params.message as PartListUnion, 'user'));\n }\n\n if (messages.length) {\n span.setAttributes({\n [GEN_AI_INPUT_MESSAGES]: stringify(messages),\n });\n }\n}\n\n/**\n * Add response attributes from the Google GenAI response\n * @see https://github.com/googleapis/js-genai/blob/v1.19.0/src/types.ts#L2313\n */\nexport function addResponseAttributes(\n span: Span,\n response: GoogleGenAIResponse,\n recordOutputs?: boolean,\n operationName?: string,\n): void {\n if (!response || typeof response !== 'object') return;\n\n if (operationName === 'decide') {\n addDecisionResponseAttributes(span, response, !!recordOutputs);\n return;\n }\n\n if (response.modelVersion) {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, response.modelVersion);\n }\n\n // Add usage metadata if present\n if (response.usageMetadata && typeof response.usageMetadata === 'object') {\n const usage = response.usageMetadata;\n const hasOutput = typeof usage.candidatesTokenCount === 'number' || typeof usage.thoughtsTokenCount === 'number';\n span.setAttributes(\n getTokenUsageAttributes(\n typeof usage.promptTokenCount === 'number'\n ? usage.promptTokenCount + (usage.toolUsePromptTokenCount ?? 0)\n : undefined,\n hasOutput ? (usage.candidatesTokenCount ?? 0) + (usage.thoughtsTokenCount ?? 0) : undefined,\n undefined,\n usage.cachedContentTokenCount,\n usage.totalTokenCount,\n ),\n );\n if (typeof usage.thoughtsTokenCount === 'number') {\n span.setAttribute(GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, usage.thoughtsTokenCount);\n }\n }\n\n if (recordOutputs) {\n setOutputMessagesAttribute(span, candidatesToMessageParts(response.candidates));\n }\n\n // Add response text if recordOutputs is enabled\n if (recordOutputs && Array.isArray(response.candidates) && response.candidates.length > 0) {\n const responseTexts = response.candidates\n .map((candidate: Candidate) => {\n if (candidate.content?.parts && Array.isArray(candidate.content.parts)) {\n return candidate.content.parts\n .map((part: ContentPart) => (typeof part.text === 'string' ? part.text : ''))\n .filter((text: string) => text.length > 0)\n .join('');\n }\n return '';\n })\n .filter((text: string) => text.length > 0);\n\n if (responseTexts.length > 0) {\n span.setAttributes({\n [GEN_AI_RESPONSE_TEXT]: responseTexts.join(''),\n });\n }\n }\n\n // Add tool calls if recordOutputs is enabled\n if (recordOutputs && response.functionCalls) {\n const functionCalls = response.functionCalls;\n if (Array.isArray(functionCalls) && functionCalls.length > 0) {\n span.setAttributes({\n [GEN_AI_RESPONSE_TOOL_CALLS]: JSON.stringify(functionCalls),\n });\n }\n }\n}\n\n/**\n * Recover the config a chat message sends but does not carry in its own arguments.\n *\n * `chats.create()` takes a config that `@google/genai` reuses for every message, resolving each\n * request as `params.config ?? chat.config`. A per-message config therefore replaces the chat\n * config rather than merging into it, and the chat config applies only when the message omits one.\n * That config lives on the chat instance, which both instrumentation paths already hold: the client\n * proxy passes it as the method's `context`, the diagnostics-channel path as `data.self`.\n *\n * The chat `history` stays off the message spans. The SDK does send it, folded into `contents`, and\n * the instance carries the whole transcript, but repeating every past turn on every message span\n * duplicates what earlier spans already reported and grows without bound.\n */\nexport function resolveChatParams(\n operationName: string,\n params: Record<string, unknown> | undefined,\n context: unknown,\n): Record<string, unknown> | undefined {\n // `!= null` mirrors the SDK's `??`: an explicit `null` config falls back to the chat's.\n if (operationName !== 'chat' || params?.config != null || !context || typeof context !== 'object') {\n return params;\n }\n\n const chatConfig = (context as Record<string, unknown>).config;\n if (!chatConfig || typeof chatConfig !== 'object') {\n return params;\n }\n\n return { ...params, config: chatConfig };\n}\n\n/**\n * Reads the caller's `config.abortSignal` from params resolved by `resolveChatParams`.\n */\nexport function getAbortSignal(params: Record<string, unknown> | undefined): AbortSignal | undefined {\n return (params?.config as { abortSignal?: AbortSignal } | undefined)?.abortSignal;\n}\n\n/** `decisions.create` takes its abort signal in its request options, not in a `config`. */\nexport function getCallAbortSignal(\n operationName: string,\n params: Record<string, unknown> | undefined,\n requestOptions: unknown,\n): AbortSignal | undefined {\n return operationName === 'decide' ? getRequestSignal(requestOptions) : getAbortSignal(params);\n}\n\n/**\n * Instrument any async or synchronous genai method with Sentry spans\n * Handles operations like models.generateContent and chat.sendMessage and chats.create\n * @see https://docs.sentry.io/platforms/javascript/guides/node/tracing/instrumentation/ai-agents-module/#manual-instrumentation\n */\nfunction instrumentMethod<T extends unknown[], R>(\n originalMethod: (...args: T) => R | Promise<R>,\n methodPath: string,\n instrumentedMethod: InstrumentedMethodEntry,\n context: unknown,\n options: GoogleGenAIOptions,\n): (...args: T) => R | Promise<R> {\n const isEmbeddings = instrumentedMethod.operation === 'embeddings';\n\n return new Proxy(originalMethod, {\n apply(target, _, args: T): R | Promise<R> {\n const operationName = instrumentedMethod.operation || 'unknown';\n const params = args[0] as Record<string, unknown> | undefined;\n const attributeParams = resolveChatParams(operationName, params, context);\n const abortSignal = getCallAbortSignal(operationName, attributeParams, args[1]);\n const requestAttributes = extractRequestAttributes(\n operationName,\n attributeParams,\n context,\n !!options.recordInputs,\n );\n const model = requestAttributes[GEN_AI_REQUEST_MODEL] || 'unknown';\n const client = getClient();\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n const spanName =\n (typeof model === 'string' && model !== 'unknown') || !(client && hasSpanStreamingEnabled(client))\n ? `${operationName} ${model}`\n : operationName;\n\n // Check if this is a streaming method\n if (instrumentedMethod.streaming) {\n // Use startSpanManual for streaming methods to control span lifecycle\n return startSpanManual(\n {\n name: spanName,\n op: getGenAiSpanOp(operationName),\n attributes: requestAttributes,\n },\n async (span: Span) => {\n try {\n if (options.recordInputs && attributeParams) {\n addPrivateRequestAttributes(span, attributeParams, operationName);\n }\n const stream = await target.apply(context, args);\n return instrumentStream(stream, span, Boolean(options.recordOutputs), abortSignal) as R;\n } catch (error) {\n span.setStatus(getErrorStatus(abortSignal));\n span.end();\n throw error;\n }\n },\n );\n }\n // Single span for both sync and async operations\n return startSpan(\n {\n name: spanName,\n op: getGenAiSpanOp(operationName),\n attributes: requestAttributes,\n },\n (span: Span) => {\n if (options.recordInputs && attributeParams) {\n addPrivateRequestAttributes(span, attributeParams, operationName);\n }\n\n // The rejection is rethrown to the caller. `startSpan` keeps the status set here.\n return handleCallbackErrors(\n () => target.apply(context, args),\n () => span.setStatus(getErrorStatus(abortSignal)),\n () => {},\n result => {\n // Only add response attributes for content-producing methods, not for embeddings\n if (!isEmbeddings) {\n addResponseAttributes(span, result, options.recordOutputs, operationName);\n }\n },\n );\n },\n );\n },\n });\n}\n\n/**\n * Create a deep proxy for Google GenAI client instrumentation\n * Recursively instruments methods and handles special cases like chats.create\n */\nfunction createDeepProxy<T extends object>(target: T, currentPath = '', options: GoogleGenAIOptions): T {\n const propertyCache = new Map<PropertyKey, { original: unknown; wrapped: unknown }>();\n\n return new Proxy(target, {\n get: (t, prop, receiver) => {\n const value = Reflect.get(t, prop, receiver);\n const cachedEntry = propertyCache.get(prop);\n if (cachedEntry) {\n if (cachedEntry.original === value) {\n return cachedEntry.wrapped;\n }\n propertyCache.delete(prop);\n }\n\n const methodPath = buildMethodPath(currentPath, String(prop));\n\n const instrumentedMethod: InstrumentedMethodEntry | undefined =\n GOOGLE_GENAI_METHOD_REGISTRY[methodPath as keyof typeof GOOGLE_GENAI_METHOD_REGISTRY];\n if (typeof value === 'function' && instrumentedMethod) {\n // If an operation is specified, we need to instrument the method itself\n const wrappedMethod = instrumentedMethod.operation\n ? instrumentMethod(value as (...args: unknown[]) => unknown, methodPath, instrumentedMethod, t, options)\n : value.bind(t);\n\n if (!instrumentedMethod.proxyResultPath) {\n propertyCache.set(prop, { original: value, wrapped: wrappedMethod });\n return wrappedMethod;\n }\n\n // If a proxyResultPath is specified, we need to proxy the result of the method.\n // Note: This currently only properly handles synchronous methods. For async methods,\n // the Promise itself would be proxied instead of the resolved value. Currently we\n // don't have a case where this is needed, so I'll keep it simple for now.\n const methodWithProxiedResult = function (...args: unknown[]): unknown {\n const result = wrappedMethod(...args);\n if (result && typeof result === 'object') {\n return createDeepProxy(result as object, instrumentedMethod.proxyResultPath, options);\n }\n return result;\n };\n propertyCache.set(prop, { original: value, wrapped: methodWithProxiedResult });\n return methodWithProxiedResult;\n }\n\n if (typeof value === 'function') {\n // Bind non-instrumented functions to preserve the original `this` context\n const boundMethod = value.bind(t);\n propertyCache.set(prop, { original: value, wrapped: boundMethod });\n return boundMethod;\n }\n\n if (value && typeof value === 'object') {\n const nestedProxy = createDeepProxy(value, methodPath, options);\n propertyCache.set(prop, { original: value, wrapped: nestedProxy });\n return nestedProxy;\n }\n\n return value;\n },\n });\n}\n\n/**\n * Instrument a Google GenAI client with Sentry tracing\n * Can be used across Node.js, Cloudflare Workers, and Vercel Edge\n *\n * @template T - The type of the client that extends client object\n * @param client - The Google GenAI client to instrument\n * @param options - Optional configuration for recording inputs and outputs\n * @returns The instrumented client with the same type as the input\n *\n * @example\n * ```typescript\n * import { GoogleGenAI } from '@google/genai';\n * import { instrumentGoogleGenAIClient } from '@sentry/node';\n *\n * const genAI = new GoogleGenAI({ apiKey: process.env.GOOGLE_GENAI_API_KEY });\n * const instrumentedClient = instrumentGoogleGenAIClient(genAI);\n *\n * // Now both chats.create and sendMessage will be instrumented\n * const chat = instrumentedClient.chats.create({ model: 'gemini-1.5-pro' });\n * const response = await chat.sendMessage({ message: 'Hello' });\n * ```\n */\nexport function instrumentGoogleGenAIClient<T extends object>(client: T, options?: GoogleGenAIOptions): T {\n return createDeepProxy(client, '', resolveAIRecordingOptions(options));\n}\n"],"mappings":";;;;;;;;;;;;AAwDA,SAAgB,aAAa,QAAiC,SAA2B;CACvF,IAAI,WAAW,UAAU,OAAO,OAAO,UAAU,UAC/C,OAAO,OAAO;CAIhB,IAAI,WAAW,OAAO,YAAY,UAAU;EAC1C,MAAM,aAAa;EAGnB,IAAI,WAAW,cAAc,OAAO,WAAW,UAAU,UACvD,OAAO,WAAW;EAIpB,IAAI,kBAAkB,cAAc,OAAO,WAAW,iBAAiB,UACrE,OAAO,WAAW;CAEtB;CAEA,OAAO;AACT;;;;AAKA,SAAS,wBAAwB,QAAqE;CACpG,MAAM,aAAiD,CAAC;CAExD,IAAI,iBAAiB,UAAU,OAAO,OAAO,gBAAgB,UAC3D,WAAW,8BAA8B,OAAO;CAElD,IAAI,UAAU,UAAU,OAAO,OAAO,SAAS,UAC7C,WAAW,wBAAwB,OAAO;CAE5C,IAAI,UAAU,UAAU,OAAO,OAAO,SAAS,UAC7C,WAAW,wBAAwB,OAAO;CAE5C,IAAI,qBAAqB,UAAU,OAAO,OAAO,oBAAoB,UACnE,WAAW,6BAA6B,OAAO;CAEjD,IAAI,sBAAsB,UAAU,OAAO,OAAO,qBAAqB,UACrE,WAAW,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OAC3B,OAAO,YAAY;GAErB,cAAc,OAAO,IAAI;EAC3B;EAEA,MAAM,aAAa,gBAAgB,aAAa,OAAO,IAAI,CAAC;EAE5D,MAAM,qBACJ,6BAA6B;EAC/B,IAAI,OAAO,UAAU,cAAc,oBAAoB;GAErD,MAAM,gBAAgB,mBAAmB,YACrC,iBAAiB,OAA0C,YAAY,oBAAoB,GAAG,OAAO,IACrG,MAAM,KAAK,CAAC;GAEhB,IAAI,CAAC,mBAAmB,iBAAiB;IACvC,cAAc,IAAI,MAAM;KAAE,UAAU;KAAO,SAAS;IAAc,CAAC;IACnE,OAAO;GACT;GAMA,MAAM,0BAA0B,SAAU,GAAG,MAA0B;IACrE,MAAM,SAAS,cAAc,GAAG,IAAI;IACpC,IAAI,UAAU,OAAO,WAAW,UAC9B,OAAO,gBAAgB,QAAkB,mBAAmB,iBAAiB,OAAO;IAEtF,OAAO;GACT;GACA,cAAc,IAAI,MAAM;IAAE,UAAU;IAAO,SAAS;GAAwB,CAAC;GAC7E,OAAO;EACT;EAEA,IAAI,OAAO,UAAU,YAAY;GAE/B,MAAM,cAAc,MAAM,KAAK,CAAC;GAChC,cAAc,IAAI,MAAM;IAAE,UAAU;IAAO,SAAS;GAAY,CAAC;GACjE,OAAO;EACT;EAEA,IAAI,SAAS,OAAO,UAAU,UAAU;GACtC,MAAM,cAAc,gBAAgB,OAAO,YAAY,OAAO;GAC9D,cAAc,IAAI,MAAM;IAAE,UAAU;IAAO,SAAS;GAAY,CAAC;GACjE,OAAO;EACT;EAEA,OAAO;CACT,EACF,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,4BAA8C,QAAW,SAAiC;CACxG,OAAO,gBAAgB,QAAQ,IAAI,0BAA0B,OAAO,CAAC;AACvE"}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { buildMethodPath, extractSystemInstructions, getGenAiSpanOp, resolveAIRecordingOptions, wrapPromiseWithMethods } from "../core/utils.js";
|
|
1
|
+
import { buildMethodPath, extractSystemInstructions, getErrorStatus, getGenAiSpanOp, resolveAIRecordingOptions, wrapPromiseWithMethods } from "../core/utils.js";
|
|
2
2
|
import { GEN_AI_REQUEST_STREAM_ATTRIBUTE } from "../core/gen-ai-attributes.js";
|
|
3
3
|
import { MISTRAL_METHOD_REGISTRY, MISTRAL_ORIGIN, MISTRAL_PROVIDER_NAME } from "./constants.js";
|
|
4
4
|
import { instrumentEventStream } from "./streaming.js";
|
|
5
|
-
import { addResponseAttributes, extractRequestParameters, getSpanName } from "./utils.js";
|
|
5
|
+
import { addResponseAttributes, extractRequestParameters, getMistralRequestSignal, getSpanName } from "./utils.js";
|
|
6
6
|
import { GEN_AI_AGENT_NAME, GEN_AI_EMBEDDINGS_INPUT, GEN_AI_INPUT_MESSAGES, GEN_AI_OPERATION_NAME, GEN_AI_PROVIDER_NAME, GEN_AI_SYSTEM_INSTRUCTIONS, GEN_AI_TOOL_DEFINITIONS, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
|
|
7
|
-
import {
|
|
7
|
+
import { startSpan, startSpanManual, stringify } from "@sentry/core";
|
|
8
8
|
// src/ai/mistral/index.ts
|
|
9
9
|
/**
|
|
10
10
|
* Serialize tool definitions from request parameters, if present.
|
|
@@ -62,6 +62,7 @@ function instrumentMethod(originalMethod, instrumentedMethod, context, options)
|
|
|
62
62
|
const isStreamRequested = !!instrumentedMethod.streaming;
|
|
63
63
|
const requestAttributes = extractRequestAttributes(args, operationName, !!options.recordInputs, isStreamRequested);
|
|
64
64
|
const params = args[0];
|
|
65
|
+
const abortSignal = getMistralRequestSignal(args[1]);
|
|
65
66
|
const spanConfig = {
|
|
66
67
|
name: getSpanName(operationName, requestAttributes),
|
|
67
68
|
op: getGenAiSpanOp(operationName),
|
|
@@ -73,13 +74,10 @@ function instrumentMethod(originalMethod, instrumentedMethod, context, options)
|
|
|
73
74
|
originalResult = originalMethod.apply(context, args);
|
|
74
75
|
if (options.recordInputs && params) addRequestAttributes(span, params, operationName);
|
|
75
76
|
return originalResult.then((result) => {
|
|
76
|
-
if (!instrumentEventStream(result, span, options.recordOutputs ?? false)) span.end();
|
|
77
|
+
if (!instrumentEventStream(result, span, options.recordOutputs ?? false, abortSignal)) span.end();
|
|
77
78
|
return result;
|
|
78
79
|
}, (error) => {
|
|
79
|
-
span.setStatus(
|
|
80
|
-
code: SPAN_STATUS_ERROR,
|
|
81
|
-
message: "internal_error"
|
|
82
|
-
});
|
|
80
|
+
span.setStatus(getErrorStatus(abortSignal));
|
|
83
81
|
span.end();
|
|
84
82
|
throw error;
|
|
85
83
|
});
|
|
@@ -93,6 +91,9 @@ function instrumentMethod(originalMethod, instrumentedMethod, context, options)
|
|
|
93
91
|
return originalResult.then((result) => {
|
|
94
92
|
addResponseAttributes(span, result, options.recordOutputs);
|
|
95
93
|
return result;
|
|
94
|
+
}, (error) => {
|
|
95
|
+
span.setStatus(getErrorStatus(abortSignal));
|
|
96
|
+
throw error;
|
|
96
97
|
});
|
|
97
98
|
});
|
|
98
99
|
return wrapPromiseWithMethods(originalResult, instrumentedPromise);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../src/ai/mistral/index.ts"],"sourcesContent":["import { SPAN_STATUS_ERROR, startSpan, startSpanManual, stringify } from '@sentry/core';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_AGENT_NAME,\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_DEFINITIONS,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport type { InstrumentedMethodEntry } from '../core/utils';\nimport {\n buildMethodPath,\n extractSystemInstructions,\n getGenAiSpanOp,\n resolveAIRecordingOptions,\n wrapPromiseWithMethods,\n} from '../core/utils';\nimport { GEN_AI_REQUEST_STREAM_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport { MISTRAL_METHOD_REGISTRY, MISTRAL_ORIGIN, MISTRAL_PROVIDER_NAME } from './constants';\nimport { instrumentEventStream } from './streaming';\nimport type { MistralOptions } from './types';\nimport { addResponseAttributes, extractRequestParameters, getSpanName } from './utils';\n\n/**\n * Serialize tool definitions from request parameters, if present.\n */\nfunction extractToolDefinitions(params: Record<string, unknown>): string | undefined {\n if (!Array.isArray(params.tools) || params.tools.length === 0) {\n return undefined;\n }\n return stringify(params.tools);\n}\n\n/**\n * Extract request attributes from method arguments.\n *\n * `streaming` comes from the called method, not the request: v2 streams only through the dedicated\n * `*.stream` methods, and their `stream` request field is optional, so a params-derived value would\n * be missing on most streaming calls.\n */\nexport function extractRequestAttributes(\n args: unknown[],\n operationName: string,\n recordInputs: boolean,\n streaming: boolean,\n): Record<string, unknown> {\n const attributes: Record<string, unknown> = {\n [GEN_AI_PROVIDER_NAME]: MISTRAL_PROVIDER_NAME,\n [GEN_AI_OPERATION_NAME]: operationName,\n [SENTRY_ORIGIN]: MISTRAL_ORIGIN,\n [GEN_AI_REQUEST_STREAM_ATTRIBUTE]: streaming,\n };\n\n if (args.length > 0 && typeof args[0] === 'object' && args[0] !== null) {\n const params = args[0] as Record<string, unknown>;\n\n if (operationName === 'invoke_agent' && typeof params.agentId === 'string') {\n attributes[GEN_AI_AGENT_NAME] = params.agentId;\n }\n\n const tools = recordInputs ? extractToolDefinitions(params) : undefined;\n if (tools) {\n attributes[GEN_AI_TOOL_DEFINITIONS] = tools;\n }\n\n Object.assign(attributes, extractRequestParameters(params));\n }\n\n return attributes;\n}\n\n/**\n * Record AI request inputs on the span, if recording is enabled.\n */\nexport function addRequestAttributes(span: Span, params: Record<string, unknown>, operationName: string): void {\n if (operationName === 'embeddings') {\n const input = params.inputs;\n if (input == null || (typeof input === 'string' && input.length === 0) || (Array.isArray(input) && !input.length)) {\n return;\n }\n span.setAttribute(GEN_AI_EMBEDDINGS_INPUT, stringify(input, String));\n return;\n }\n\n const src = 'messages' in params ? params.messages : undefined;\n if (!src || (Array.isArray(src) && src.length === 0)) {\n return;\n }\n\n const { systemInstructions, filteredMessages } = extractSystemInstructions(src);\n if (systemInstructions) {\n span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS, systemInstructions);\n }\n span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify(filteredMessages));\n}\n\n/**\n * Instrument a single Mistral SDK method with a gen_ai span.\n * @see https://docs.sentry.io/platforms/javascript/guides/node/tracing/instrumentation/ai-agents-module/#manual-instrumentation\n */\nfunction instrumentMethod<T extends unknown[], R>(\n originalMethod: (...args: T) => Promise<R>,\n instrumentedMethod: InstrumentedMethodEntry,\n context: unknown,\n options: MistralOptions,\n): (...args: T) => Promise<R> {\n return function instrumentedCall(...args: T): Promise<R> {\n const operationName = instrumentedMethod.operation || 'unknown';\n const isStreamRequested = !!instrumentedMethod.streaming;\n const requestAttributes = extractRequestAttributes(args, operationName, !!options.recordInputs, isStreamRequested);\n\n const params = args[0] as Record<string, unknown> | undefined;\n\n const spanConfig = {\n name: getSpanName(operationName, requestAttributes),\n op: getGenAiSpanOp(operationName),\n attributes: requestAttributes as Record<string, SpanAttributeValue>,\n };\n\n if (isStreamRequested) {\n let originalResult!: Promise<R>;\n\n const instrumentedPromise = startSpanManual(spanConfig, (span: Span) => {\n originalResult = originalMethod.apply(context, args);\n\n if (options.recordInputs && params) {\n addRequestAttributes(span, params, operationName);\n }\n\n return originalResult.then(\n result => {\n // Patched in place so the caller keeps the real `EventStream`; `instrumentEventStream`\n // takes over ending the span once the stream is drained.\n if (!instrumentEventStream(result, span, options.recordOutputs ?? false)) {\n span.end();\n }\n return result;\n },\n error => {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n span.end();\n throw error;\n },\n );\n });\n\n return wrapPromiseWithMethods(originalResult, instrumentedPromise);\n }\n\n let originalResult!: Promise<R>;\n\n const instrumentedPromise = startSpan(spanConfig, (span: Span) => {\n originalResult = originalMethod.apply(context, args);\n\n if (options.recordInputs && params) {\n addRequestAttributes(span, params, operationName);\n }\n\n return originalResult.then(result => {\n addResponseAttributes(span, result, options.recordOutputs);\n return result;\n });\n });\n\n return wrapPromiseWithMethods(originalResult, instrumentedPromise);\n };\n}\n\n/**\n * Create a deep proxy for Mistral client instrumentation.\n */\nfunction createDeepProxy<T extends object>(target: T, currentPath = '', options: MistralOptions): T {\n return new Proxy(target, {\n get(obj: object, prop: string): unknown {\n const value = (obj as Record<string, unknown>)[prop];\n const methodPath = buildMethodPath(currentPath, String(prop));\n\n const instrumentedMethod = MISTRAL_METHOD_REGISTRY[methodPath as keyof typeof MISTRAL_METHOD_REGISTRY];\n if (typeof value === 'function' && instrumentedMethod) {\n return instrumentMethod(value as (...args: unknown[]) => Promise<unknown>, instrumentedMethod, obj, options);\n }\n\n if (typeof value === 'function') {\n // Preserve the original `this` for uninstrumented methods (private class fields).\n return value.bind(obj);\n }\n\n if (value && typeof value === 'object') {\n return createDeepProxy(value, methodPath, options);\n }\n\n return value;\n },\n }) as T;\n}\n\n/**\n * Instrument a Mistral client with Sentry tracing.\n * Can be used across Node.js, Cloudflare Workers, and Vercel Edge.\n */\nexport function instrumentMistralAiClient<T extends object>(client: T, options?: MistralOptions): T {\n return createDeepProxy(client, '', resolveAIRecordingOptions(options));\n}\n"],"mappings":";;;;;;;;;;;AA6BA,SAAS,uBAAuB,QAAqD;CACnF,IAAI,CAAC,MAAM,QAAQ,OAAO,KAAK,KAAK,OAAO,MAAM,WAAW,GAC1D;CAEF,OAAO,UAAU,OAAO,KAAK;AAC/B;;;;;;;;AASA,SAAgB,yBACd,MACA,eACA,cACA,WACyB;CACzB,MAAM,aAAsC;GACzC,uBAAuB;GACvB,wBAAwB;GACxB,gBAAgB;GAChB,kCAAkC;CACrC;CAEA,IAAI,KAAK,SAAS,KAAK,OAAO,KAAK,OAAO,YAAY,KAAK,OAAO,MAAM;EACtE,MAAM,SAAS,KAAK;EAEpB,IAAI,kBAAkB,k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src/ai/mistral/index.ts"],"sourcesContent":["import { startSpan, startSpanManual, stringify } from '@sentry/core';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport {\n GEN_AI_AGENT_NAME,\n GEN_AI_EMBEDDINGS_INPUT,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_PROVIDER_NAME,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_DEFINITIONS,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport type { InstrumentedMethodEntry } from '../core/utils';\nimport {\n buildMethodPath,\n extractSystemInstructions,\n getErrorStatus,\n getGenAiSpanOp,\n resolveAIRecordingOptions,\n wrapPromiseWithMethods,\n} from '../core/utils';\nimport { GEN_AI_REQUEST_STREAM_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport { MISTRAL_METHOD_REGISTRY, MISTRAL_ORIGIN, MISTRAL_PROVIDER_NAME } from './constants';\nimport { instrumentEventStream } from './streaming';\nimport type { MistralOptions } from './types';\nimport { addResponseAttributes, extractRequestParameters, getMistralRequestSignal, getSpanName } from './utils';\n\n/**\n * Serialize tool definitions from request parameters, if present.\n */\nfunction extractToolDefinitions(params: Record<string, unknown>): string | undefined {\n if (!Array.isArray(params.tools) || params.tools.length === 0) {\n return undefined;\n }\n return stringify(params.tools);\n}\n\n/**\n * Extract request attributes from method arguments.\n *\n * `streaming` comes from the called method, not the request: v2 streams only through the dedicated\n * `*.stream` methods, and their `stream` request field is optional, so a params-derived value would\n * be missing on most streaming calls.\n */\nexport function extractRequestAttributes(\n args: unknown[],\n operationName: string,\n recordInputs: boolean,\n streaming: boolean,\n): Record<string, unknown> {\n const attributes: Record<string, unknown> = {\n [GEN_AI_PROVIDER_NAME]: MISTRAL_PROVIDER_NAME,\n [GEN_AI_OPERATION_NAME]: operationName,\n [SENTRY_ORIGIN]: MISTRAL_ORIGIN,\n [GEN_AI_REQUEST_STREAM_ATTRIBUTE]: streaming,\n };\n\n if (args.length > 0 && typeof args[0] === 'object' && args[0] !== null) {\n const params = args[0] as Record<string, unknown>;\n\n if (operationName === 'invoke_agent' && typeof params.agentId === 'string') {\n attributes[GEN_AI_AGENT_NAME] = params.agentId;\n }\n\n const tools = recordInputs ? extractToolDefinitions(params) : undefined;\n if (tools) {\n attributes[GEN_AI_TOOL_DEFINITIONS] = tools;\n }\n\n Object.assign(attributes, extractRequestParameters(params));\n }\n\n return attributes;\n}\n\n/**\n * Record AI request inputs on the span, if recording is enabled.\n */\nexport function addRequestAttributes(span: Span, params: Record<string, unknown>, operationName: string): void {\n if (operationName === 'embeddings') {\n const input = params.inputs;\n if (input == null || (typeof input === 'string' && input.length === 0) || (Array.isArray(input) && !input.length)) {\n return;\n }\n span.setAttribute(GEN_AI_EMBEDDINGS_INPUT, stringify(input, String));\n return;\n }\n\n const src = 'messages' in params ? params.messages : undefined;\n if (!src || (Array.isArray(src) && src.length === 0)) {\n return;\n }\n\n const { systemInstructions, filteredMessages } = extractSystemInstructions(src);\n if (systemInstructions) {\n span.setAttribute(GEN_AI_SYSTEM_INSTRUCTIONS, systemInstructions);\n }\n span.setAttribute(GEN_AI_INPUT_MESSAGES, stringify(filteredMessages));\n}\n\n/**\n * Instrument a single Mistral SDK method with a gen_ai span.\n * @see https://docs.sentry.io/platforms/javascript/guides/node/tracing/instrumentation/ai-agents-module/#manual-instrumentation\n */\nfunction instrumentMethod<T extends unknown[], R>(\n originalMethod: (...args: T) => Promise<R>,\n instrumentedMethod: InstrumentedMethodEntry,\n context: unknown,\n options: MistralOptions,\n): (...args: T) => Promise<R> {\n return function instrumentedCall(...args: T): Promise<R> {\n const operationName = instrumentedMethod.operation || 'unknown';\n const isStreamRequested = !!instrumentedMethod.streaming;\n const requestAttributes = extractRequestAttributes(args, operationName, !!options.recordInputs, isStreamRequested);\n\n const params = args[0] as Record<string, unknown> | undefined;\n const abortSignal = getMistralRequestSignal(args[1]);\n\n const spanConfig = {\n name: getSpanName(operationName, requestAttributes),\n op: getGenAiSpanOp(operationName),\n attributes: requestAttributes as Record<string, SpanAttributeValue>,\n };\n\n if (isStreamRequested) {\n let originalResult!: Promise<R>;\n\n const instrumentedPromise = startSpanManual(spanConfig, (span: Span) => {\n originalResult = originalMethod.apply(context, args);\n\n if (options.recordInputs && params) {\n addRequestAttributes(span, params, operationName);\n }\n\n return originalResult.then(\n result => {\n // Patched in place so the caller keeps the real `EventStream`; `instrumentEventStream`\n // takes over ending the span once the stream is drained.\n if (!instrumentEventStream(result, span, options.recordOutputs ?? false, abortSignal)) {\n span.end();\n }\n return result;\n },\n error => {\n span.setStatus(getErrorStatus(abortSignal));\n span.end();\n throw error;\n },\n );\n });\n\n return wrapPromiseWithMethods(originalResult, instrumentedPromise);\n }\n\n let originalResult!: Promise<R>;\n\n const instrumentedPromise = startSpan(spanConfig, (span: Span) => {\n originalResult = originalMethod.apply(context, args);\n\n if (options.recordInputs && params) {\n addRequestAttributes(span, params, operationName);\n }\n\n return originalResult.then(\n result => {\n addResponseAttributes(span, result, options.recordOutputs);\n return result;\n },\n error => {\n span.setStatus(getErrorStatus(abortSignal));\n throw error;\n },\n );\n });\n\n return wrapPromiseWithMethods(originalResult, instrumentedPromise);\n };\n}\n\n/**\n * Create a deep proxy for Mistral client instrumentation.\n */\nfunction createDeepProxy<T extends object>(target: T, currentPath = '', options: MistralOptions): T {\n return new Proxy(target, {\n get(obj: object, prop: string): unknown {\n const value = (obj as Record<string, unknown>)[prop];\n const methodPath = buildMethodPath(currentPath, String(prop));\n\n const instrumentedMethod = MISTRAL_METHOD_REGISTRY[methodPath as keyof typeof MISTRAL_METHOD_REGISTRY];\n if (typeof value === 'function' && instrumentedMethod) {\n return instrumentMethod(value as (...args: unknown[]) => Promise<unknown>, instrumentedMethod, obj, options);\n }\n\n if (typeof value === 'function') {\n // Preserve the original `this` for uninstrumented methods (private class fields).\n return value.bind(obj);\n }\n\n if (value && typeof value === 'object') {\n return createDeepProxy(value, methodPath, options);\n }\n\n return value;\n },\n }) as T;\n}\n\n/**\n * Instrument a Mistral client with Sentry tracing.\n * Can be used across Node.js, Cloudflare Workers, and Vercel Edge.\n */\nexport function instrumentMistralAiClient<T extends object>(client: T, options?: MistralOptions): T {\n return createDeepProxy(client, '', resolveAIRecordingOptions(options));\n}\n"],"mappings":";;;;;;;;;;;AA8BA,SAAS,uBAAuB,QAAqD;CACnF,IAAI,CAAC,MAAM,QAAQ,OAAO,KAAK,KAAK,OAAO,MAAM,WAAW,GAC1D;CAEF,OAAO,UAAU,OAAO,KAAK;AAC/B;;;;;;;;AASA,SAAgB,yBACd,MACA,eACA,cACA,WACyB;CACzB,MAAM,aAAsC;GACzC,uBAAuB;GACvB,wBAAwB;GACxB,gBAAgB;GAChB,kCAAkC;CACrC;CAEA,IAAI,KAAK,SAAS,KAAK,OAAO,KAAK,OAAO,YAAY,KAAK,OAAO,MAAM;EACtE,MAAM,SAAS,KAAK;EAEpB,IAAI,kBAAkB,kBAAkB,OAAO,OAAO,YAAY,UAChE,WAAW,qBAAqB,OAAO;EAGzC,MAAM,QAAQ,eAAe,uBAAuB,MAAM,IAAI,KAAA;EAC9D,IAAI,OACF,WAAW,2BAA2B;EAGxC,OAAO,OAAO,YAAY,yBAAyB,MAAM,CAAC;CAC5D;CAEA,OAAO;AACT;;;;AAKA,SAAgB,qBAAqB,MAAY,QAAiC,eAA6B;CAC7G,IAAI,kBAAkB,cAAc;EAClC,MAAM,QAAQ,OAAO;EACrB,IAAI,SAAS,QAAS,OAAO,UAAU,YAAY,MAAM,WAAW,KAAO,MAAM,QAAQ,KAAK,KAAK,CAAC,MAAM,QACxG;EAEF,KAAK,aAAa,yBAAyB,UAAU,OAAO,MAAM,CAAC;EACnE;CACF;CAEA,MAAM,MAAM,cAAc,SAAS,OAAO,WAAW,KAAA;CACrD,IAAI,CAAC,OAAQ,MAAM,QAAQ,GAAG,KAAK,IAAI,WAAW,GAChD;CAGF,MAAM,EAAE,oBAAoB,qBAAqB,0BAA0B,GAAG;CAC9E,IAAI,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;GACR,CACF;EACF,CAAC;EAED,OAAO,uBAAuB,gBAAgB,mBAAmB;CACnE;AACF;;;;AAKA,SAAS,gBAAkC,QAAW,cAAc,IAAI,SAA4B;CAClG,OAAO,IAAI,MAAM,QAAQ,EACvB,IAAI,KAAa,MAAuB;EACtC,MAAM,QAAS,IAAgC;EAC/C,MAAM,aAAa,gBAAgB,aAAa,OAAO,IAAI,CAAC;EAE5D,MAAM,qBAAqB,wBAAwB;EACnD,IAAI,OAAO,UAAU,cAAc,oBACjC,OAAO,iBAAiB,OAAmD,oBAAoB,KAAK,OAAO;EAG7G,IAAI,OAAO,UAAU,YAEnB,OAAO,MAAM,KAAK,GAAG;EAGvB,IAAI,SAAS,OAAO,UAAU,UAC5B,OAAO,gBAAgB,OAAO,YAAY,OAAO;EAGnD,OAAO;CACT,EACF,CAAC;AACH;;;;;AAMA,SAAgB,0BAA4C,QAAW,SAA6B;CAClG,OAAO,gBAAgB,QAAQ,IAAI,0BAA0B,OAAO,CAAC;AACvE"}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import { endStreamSpan, setOutputMessagesAttribute } from "../core/utils.js";
|
|
1
|
+
import { endStreamSpan, getErrorStatus, setOutputMessagesAttribute } from "../core/utils.js";
|
|
2
2
|
import { contentToString } from "./utils.js";
|
|
3
|
-
import { SPAN_STATUS_ERROR } from "@sentry/core";
|
|
4
3
|
// src/ai/mistral/streaming.ts
|
|
5
4
|
/** Whether a value can be drained with `for await`. */
|
|
6
5
|
function isAsyncIterable(value) {
|
|
@@ -141,7 +140,7 @@ function instrumentedSource(readable) {
|
|
|
141
140
|
*
|
|
142
141
|
* Returns `false` for a value that is not a stream, leaving it untouched.
|
|
143
142
|
*/
|
|
144
|
-
function instrumentEventStream(stream, span, recordOutputs) {
|
|
143
|
+
function instrumentEventStream(stream, span, recordOutputs, abortSignal) {
|
|
145
144
|
if (!isAsyncIterable(stream)) return false;
|
|
146
145
|
const state = createStreamingState();
|
|
147
146
|
let consumer;
|
|
@@ -157,10 +156,7 @@ function instrumentEventStream(stream, span, recordOutputs) {
|
|
|
157
156
|
const settle = (error) => {
|
|
158
157
|
if (settled) return;
|
|
159
158
|
settled = true;
|
|
160
|
-
if (error !== void 0 && !cancelled) span.setStatus(
|
|
161
|
-
code: SPAN_STATUS_ERROR,
|
|
162
|
-
message: "internal_error"
|
|
163
|
-
});
|
|
159
|
+
if (error !== void 0 && !cancelled) span.setStatus(getErrorStatus(abortSignal));
|
|
164
160
|
const toolCalls = Object.values(state.toolCalls);
|
|
165
161
|
if (recordOutputs) setOutputMessagesAttribute(span, {
|
|
166
162
|
responseText: state.responseTexts.join(""),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"streaming.js","names":[],"sources":["../../../../src/ai/mistral/streaming.ts"],"sourcesContent":["import type { Span } from '@sentry/core';\nimport { SPAN_STATUS_ERROR } from '@sentry/core';\nimport { endStreamSpan, setOutputMessagesAttribute } from '../core/utils';\nimport type { MistralCompletionChunk, MistralToolCall } from './types';\nimport { contentToString } from './utils';\n\n/**\n * State accumulated while consuming a Mistral event stream.\n */\ninterface StreamingState {\n responseTexts: string[];\n finishReasons: string[];\n responseId: string;\n responseModel: string;\n promptTokens: number | undefined;\n completionTokens: number | undefined;\n totalTokens: number | undefined;\n /** Tool calls accumulated by their delta `index`; `function.arguments` arrives fragmented. */\n toolCalls: Record<number, MistralToolCall>;\n}\n\n/** Which drain path owns accumulation. See {@link instrumentEventStream}. */\ntype StreamConsumer = 'iterator' | 'reader';\n\ntype AsyncIterableStream = { [Symbol.asyncIterator]: () => AsyncIterator<unknown> };\n\ninterface StreamReaderLike {\n read: () => Promise<{ done: boolean; value?: unknown }>;\n cancel?: (reason?: unknown) => Promise<unknown>;\n}\n\ninterface ReadableStreamLike {\n getReader?: (...args: unknown[]) => StreamReaderLike;\n cancel?: (reason?: unknown) => Promise<unknown>;\n tee?: () => unknown;\n pipeTo?: (destination: unknown, options?: unknown) => Promise<unknown>;\n pipeThrough?: (transform: unknown, options?: unknown) => unknown;\n}\n\n/** Whether a value can be drained with `for await`. */\nexport function isAsyncIterable(value: unknown): value is AsyncIterableStream {\n return !!value && typeof (value as AsyncIterableStream)[Symbol.asyncIterator] === 'function';\n}\n\nfunction createStreamingState(): StreamingState {\n return {\n responseTexts: [],\n finishReasons: [],\n responseId: '',\n responseModel: '',\n promptTokens: undefined,\n completionTokens: undefined,\n totalTokens: undefined,\n toolCalls: {},\n };\n}\n\nfunction processToolCalls(toolCalls: MistralToolCall[], state: StreamingState): void {\n for (const toolCall of toolCalls) {\n const index = toolCall.index;\n if (index === undefined || !toolCall.function) {\n continue;\n }\n\n const existing = state.toolCalls[index];\n if (!existing) {\n state.toolCalls[index] = {\n ...toolCall,\n function: { name: toolCall.function.name, arguments: toolCall.function.arguments ?? '' },\n };\n } else if (toolCall.function.arguments && existing.function) {\n existing.function.arguments = `${existing.function.arguments}${toolCall.function.arguments}`;\n }\n }\n}\n\nfunction processChunk(chunk: MistralCompletionChunk, state: StreamingState, recordOutputs: boolean): void {\n state.responseId = chunk.id ?? state.responseId;\n state.responseModel = chunk.model ?? state.responseModel;\n\n if (chunk.usage) {\n // Input tokens stay constant across the stream; output tokens are only finalized in the last\n // event, so we overwrite on every event that carries usage to guarantee the totals are set.\n state.promptTokens = chunk.usage.promptTokens;\n state.completionTokens = chunk.usage.completionTokens;\n state.totalTokens = chunk.usage.totalTokens;\n }\n\n for (const choice of chunk.choices ?? []) {\n if (recordOutputs) {\n // Deltas carry either a plain string or the same content-chunk array the non-streaming\n // responses use, so both go through `contentToString`.\n const content = contentToString(choice.delta?.content);\n if (content) {\n state.responseTexts.push(content);\n }\n if (choice.delta?.toolCalls) {\n processToolCalls(choice.delta.toolCalls, state);\n }\n }\n if (choice.finishReason) {\n state.finishReasons.push(choice.finishReason);\n }\n }\n}\n\n/** Mistral yields `CompletionEvent` objects that wrap the chunk under `data`. */\nfunction processEvent(event: unknown, state: StreamingState, recordOutputs: boolean): void {\n const chunk = (event as { data?: MistralCompletionChunk } | undefined)?.data;\n if (chunk && typeof chunk === 'object') {\n processChunk(chunk, state, recordOutputs);\n }\n}\n\nasync function* instrumentIterator(\n iterate: () => AsyncIterator<unknown>,\n state: StreamingState,\n recordOutputs: boolean,\n claim: (consumer: StreamConsumer) => boolean,\n settle: (error?: unknown) => void,\n): AsyncGenerator<unknown, void, unknown> {\n try {\n for await (const event of { [Symbol.asyncIterator]: iterate }) {\n if (claim('iterator')) {\n processEvent(event, state, recordOutputs);\n }\n yield event;\n }\n } catch (error) {\n settle(error);\n throw error;\n } finally {\n settle();\n }\n}\n\nfunction wrapReader(\n reader: StreamReaderLike,\n state: StreamingState,\n recordOutputs: boolean,\n claim: (consumer: StreamConsumer) => boolean,\n settle: (error?: unknown) => void,\n markCancelled: () => void,\n): StreamReaderLike {\n // Captured before the proxy exists so the wrappers below call the real reader, not themselves.\n const originalRead = reader.read;\n const originalCancel = reader.cancel;\n const read = (): Promise<{ done: boolean; value?: unknown }> => originalRead.call(reader);\n const cancel =\n typeof originalCancel === 'function'\n ? (reason?: unknown): Promise<unknown> => originalCancel.call(reader, reason)\n : undefined;\n\n return new Proxy(reader, {\n get(target: StreamReaderLike, prop: string | symbol): unknown {\n if (prop === 'read') {\n return async (): Promise<{ done: boolean; value?: unknown }> => {\n try {\n const result = await read();\n if (result.done) {\n settle();\n } else if (claim('reader')) {\n processEvent(result.value, state, recordOutputs);\n }\n return result;\n } catch (error) {\n settle(error);\n throw error;\n }\n };\n }\n\n if (prop === 'cancel' && cancel) {\n return async (reason?: unknown): Promise<unknown> => {\n markCancelled();\n try {\n return await cancel(reason);\n } finally {\n settle();\n }\n };\n }\n\n const value = Reflect.get(target, prop, target) as unknown;\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n}\n\n/**\n * A stream that pulls through `readable`'s instrumented reader.\n *\n * `tee`, `pipeTo` and `pipeThrough` acquire their reader through internal slots rather than by\n * calling the public `getReader`, so patching that method alone leaves them uninstrumented: the\n * chunks bypass accumulation and the span is never ended. Handing them this stream instead routes\n * them back through the wrapped reader, so there is still exactly one accumulating consumer.\n *\n * Same idea as `monitorStream` in `@sentry/deno`, with two deliberate differences: chunks are pulled\n * on demand rather than drained in a `start` loop, so backpressure still reaches the source, and\n * `cancel` is forwarded (the hole #24054 fixed there) so the source stops producing when the\n * consumer disconnects.\n */\nfunction instrumentedSource(readable: ReadableStreamLike): ReadableStream<unknown> {\n // The patched `getReader`, so reads are accumulated and the span is ended by the shared logic.\n const reader = readable.getReader!();\n\n return new ReadableStream({\n async pull(controller) {\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n return;\n }\n controller.enqueue(value);\n },\n async cancel(reason) {\n await reader.cancel?.(reason);\n },\n });\n}\n\n/**\n * Instrument a Mistral event stream in place: accumulate response attributes as it is drained and\n * end `span` when it finishes.\n *\n * The stream is patched rather than replaced because `EventStream` extends `ReadableStream`, so\n * handing back a bare async generator would drop `getReader`, `tee`, `pipeTo` and the rest of the\n * `ReadableStream` API the caller is entitled to.\n *\n * Both `for await` and `getReader()` are valid ways to drain a `ReadableStream`, and the SDK's\n * iterator polyfill reads through `getReader()`, so both are wrapped. The first path to see a chunk\n * claims accumulation and the other stays a pass-through, which keeps a chunk from being counted\n * twice when one path drives the other.\n *\n * Returns `false` for a value that is not a stream, leaving it untouched.\n */\nexport function instrumentEventStream(stream: unknown, span: Span, recordOutputs: boolean): boolean {\n if (!isAsyncIterable(stream)) {\n return false;\n }\n\n const state = createStreamingState();\n let consumer: StreamConsumer | undefined;\n let settled = false;\n let cancelled = false;\n\n const claim = (candidate: StreamConsumer): boolean => {\n consumer ??= candidate;\n return consumer === candidate;\n };\n\n // Set synchronously when the caller asks to cancel, before the underlying cancel is awaited.\n // Cancelling can reject an in-flight `read()` (it aborts the HTTP body the stream reads from), and\n // that rejection would otherwise reach `settle` first and record a deliberate abort as a failure.\n const markCancelled = (): void => {\n cancelled = true;\n };\n\n const settle = (error?: unknown): void => {\n if (settled) {\n return;\n }\n settled = true;\n if (error !== undefined && !cancelled) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n\n const toolCalls = Object.values(state.toolCalls);\n\n if (recordOutputs) {\n // Set the authoritative `gen_ai.output.messages` alongside the deprecated response attributes\n // `endStreamSpan` writes, so tool calls survive Relay's lossy migration. A stream is a single\n // assistant turn, so the accumulated fragments make up one message.\n setOutputMessagesAttribute(span, {\n responseText: state.responseTexts.join(''),\n toolCalls,\n finishReason: state.finishReasons[0],\n });\n }\n\n endStreamSpan(span, { ...state, toolCalls }, recordOutputs);\n };\n\n const iterate = stream[Symbol.asyncIterator].bind(stream);\n const instrumented = instrumentIterator(iterate, state, recordOutputs, claim, settle);\n stream[Symbol.asyncIterator] = () => instrumented;\n\n const readable = stream as ReadableStreamLike;\n\n if (typeof readable.getReader === 'function') {\n const getReader = readable.getReader.bind(readable);\n readable.getReader = (...args: unknown[]) =>\n wrapReader(getReader(...args), state, recordOutputs, claim, settle, markCancelled);\n }\n\n if (typeof readable.cancel === 'function') {\n const cancel = readable.cancel.bind(readable);\n readable.cancel = async (reason?: unknown): Promise<unknown> => {\n markCancelled();\n try {\n return await cancel(reason);\n } finally {\n settle();\n }\n };\n }\n\n // Only patched when `getReader` is present, since that is what `instrumentedSource` pulls through.\n if (typeof readable.getReader === 'function') {\n if (typeof readable.tee === 'function') {\n readable.tee = () => instrumentedSource(readable).tee();\n }\n\n if (typeof readable.pipeTo === 'function') {\n readable.pipeTo = (destination: unknown, options?: unknown) =>\n instrumentedSource(readable).pipeTo(destination as WritableStream<unknown>, options as StreamPipeOptions);\n }\n\n if (typeof readable.pipeThrough === 'function') {\n readable.pipeThrough = (transform: unknown, options?: unknown) =>\n instrumentedSource(readable).pipeThrough(\n transform as ReadableWritablePair<unknown, unknown>,\n options as StreamPipeOptions,\n );\n }\n }\n\n return true;\n}\n"],"mappings":";;;;;AAwCA,SAAgB,gBAAgB,OAA8C;CAC5E,OAAO,CAAC,CAAC,SAAS,OAAQ,MAA8B,OAAO,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C;GAC9D,cAAc;GACd,IAAI;IACF,OAAO,MAAM,OAAO,MAAM;GAC5B,UAAU;IACR,OAAO;GACT;EACF;CACF;CAGA,IAAI,OAAO,SAAS,cAAc,YAAY;EAC5C,IAAI,OAAO,SAAS,QAAQ,YAC1B,SAAS,YAAY,mBAAmB,QAAQ,CAAC,CAAC,IAAI;EAGxD,IAAI,OAAO,SAAS,WAAW,YAC7B,SAAS,UAAU,aAAsB,YACvC,mBAAmB,QAAQ,CAAC,CAAC,OAAO,aAAwC,OAA4B;EAG5G,IAAI,OAAO,SAAS,gBAAgB,YAClC,SAAS,eAAe,WAAoB,YAC1C,mBAAmB,QAAQ,CAAC,CAAC,YAC3B,WACA,OACF;CAEN;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"streaming.js","names":[],"sources":["../../../../src/ai/mistral/streaming.ts"],"sourcesContent":["import type { Span } from '@sentry/core';\nimport { endStreamSpan, getErrorStatus, setOutputMessagesAttribute } from '../core/utils';\nimport type { MistralCompletionChunk, MistralToolCall } from './types';\nimport { contentToString } from './utils';\n\n/**\n * State accumulated while consuming a Mistral event stream.\n */\ninterface StreamingState {\n responseTexts: string[];\n finishReasons: string[];\n responseId: string;\n responseModel: string;\n promptTokens: number | undefined;\n completionTokens: number | undefined;\n totalTokens: number | undefined;\n /** Tool calls accumulated by their delta `index`; `function.arguments` arrives fragmented. */\n toolCalls: Record<number, MistralToolCall>;\n}\n\n/** Which drain path owns accumulation. See {@link instrumentEventStream}. */\ntype StreamConsumer = 'iterator' | 'reader';\n\ntype AsyncIterableStream = { [Symbol.asyncIterator]: () => AsyncIterator<unknown> };\n\ninterface StreamReaderLike {\n read: () => Promise<{ done: boolean; value?: unknown }>;\n cancel?: (reason?: unknown) => Promise<unknown>;\n}\n\ninterface ReadableStreamLike {\n getReader?: (...args: unknown[]) => StreamReaderLike;\n cancel?: (reason?: unknown) => Promise<unknown>;\n tee?: () => unknown;\n pipeTo?: (destination: unknown, options?: unknown) => Promise<unknown>;\n pipeThrough?: (transform: unknown, options?: unknown) => unknown;\n}\n\n/** Whether a value can be drained with `for await`. */\nexport function isAsyncIterable(value: unknown): value is AsyncIterableStream {\n return !!value && typeof (value as AsyncIterableStream)[Symbol.asyncIterator] === 'function';\n}\n\nfunction createStreamingState(): StreamingState {\n return {\n responseTexts: [],\n finishReasons: [],\n responseId: '',\n responseModel: '',\n promptTokens: undefined,\n completionTokens: undefined,\n totalTokens: undefined,\n toolCalls: {},\n };\n}\n\nfunction processToolCalls(toolCalls: MistralToolCall[], state: StreamingState): void {\n for (const toolCall of toolCalls) {\n const index = toolCall.index;\n if (index === undefined || !toolCall.function) {\n continue;\n }\n\n const existing = state.toolCalls[index];\n if (!existing) {\n state.toolCalls[index] = {\n ...toolCall,\n function: { name: toolCall.function.name, arguments: toolCall.function.arguments ?? '' },\n };\n } else if (toolCall.function.arguments && existing.function) {\n existing.function.arguments = `${existing.function.arguments}${toolCall.function.arguments}`;\n }\n }\n}\n\nfunction processChunk(chunk: MistralCompletionChunk, state: StreamingState, recordOutputs: boolean): void {\n state.responseId = chunk.id ?? state.responseId;\n state.responseModel = chunk.model ?? state.responseModel;\n\n if (chunk.usage) {\n // Input tokens stay constant across the stream; output tokens are only finalized in the last\n // event, so we overwrite on every event that carries usage to guarantee the totals are set.\n state.promptTokens = chunk.usage.promptTokens;\n state.completionTokens = chunk.usage.completionTokens;\n state.totalTokens = chunk.usage.totalTokens;\n }\n\n for (const choice of chunk.choices ?? []) {\n if (recordOutputs) {\n // Deltas carry either a plain string or the same content-chunk array the non-streaming\n // responses use, so both go through `contentToString`.\n const content = contentToString(choice.delta?.content);\n if (content) {\n state.responseTexts.push(content);\n }\n if (choice.delta?.toolCalls) {\n processToolCalls(choice.delta.toolCalls, state);\n }\n }\n if (choice.finishReason) {\n state.finishReasons.push(choice.finishReason);\n }\n }\n}\n\n/** Mistral yields `CompletionEvent` objects that wrap the chunk under `data`. */\nfunction processEvent(event: unknown, state: StreamingState, recordOutputs: boolean): void {\n const chunk = (event as { data?: MistralCompletionChunk } | undefined)?.data;\n if (chunk && typeof chunk === 'object') {\n processChunk(chunk, state, recordOutputs);\n }\n}\n\nasync function* instrumentIterator(\n iterate: () => AsyncIterator<unknown>,\n state: StreamingState,\n recordOutputs: boolean,\n claim: (consumer: StreamConsumer) => boolean,\n settle: (error?: unknown) => void,\n): AsyncGenerator<unknown, void, unknown> {\n try {\n for await (const event of { [Symbol.asyncIterator]: iterate }) {\n if (claim('iterator')) {\n processEvent(event, state, recordOutputs);\n }\n yield event;\n }\n } catch (error) {\n settle(error);\n throw error;\n } finally {\n settle();\n }\n}\n\nfunction wrapReader(\n reader: StreamReaderLike,\n state: StreamingState,\n recordOutputs: boolean,\n claim: (consumer: StreamConsumer) => boolean,\n settle: (error?: unknown) => void,\n markCancelled: () => void,\n): StreamReaderLike {\n // Captured before the proxy exists so the wrappers below call the real reader, not themselves.\n const originalRead = reader.read;\n const originalCancel = reader.cancel;\n const read = (): Promise<{ done: boolean; value?: unknown }> => originalRead.call(reader);\n const cancel =\n typeof originalCancel === 'function'\n ? (reason?: unknown): Promise<unknown> => originalCancel.call(reader, reason)\n : undefined;\n\n return new Proxy(reader, {\n get(target: StreamReaderLike, prop: string | symbol): unknown {\n if (prop === 'read') {\n return async (): Promise<{ done: boolean; value?: unknown }> => {\n try {\n const result = await read();\n if (result.done) {\n settle();\n } else if (claim('reader')) {\n processEvent(result.value, state, recordOutputs);\n }\n return result;\n } catch (error) {\n settle(error);\n throw error;\n }\n };\n }\n\n if (prop === 'cancel' && cancel) {\n return async (reason?: unknown): Promise<unknown> => {\n markCancelled();\n try {\n return await cancel(reason);\n } finally {\n settle();\n }\n };\n }\n\n const value = Reflect.get(target, prop, target) as unknown;\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n}\n\n/**\n * A stream that pulls through `readable`'s instrumented reader.\n *\n * `tee`, `pipeTo` and `pipeThrough` acquire their reader through internal slots rather than by\n * calling the public `getReader`, so patching that method alone leaves them uninstrumented: the\n * chunks bypass accumulation and the span is never ended. Handing them this stream instead routes\n * them back through the wrapped reader, so there is still exactly one accumulating consumer.\n *\n * Same idea as `monitorStream` in `@sentry/deno`, with two deliberate differences: chunks are pulled\n * on demand rather than drained in a `start` loop, so backpressure still reaches the source, and\n * `cancel` is forwarded (the hole #24054 fixed there) so the source stops producing when the\n * consumer disconnects.\n */\nfunction instrumentedSource(readable: ReadableStreamLike): ReadableStream<unknown> {\n // The patched `getReader`, so reads are accumulated and the span is ended by the shared logic.\n const reader = readable.getReader!();\n\n return new ReadableStream({\n async pull(controller) {\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n return;\n }\n controller.enqueue(value);\n },\n async cancel(reason) {\n await reader.cancel?.(reason);\n },\n });\n}\n\n/**\n * Instrument a Mistral event stream in place: accumulate response attributes as it is drained and\n * end `span` when it finishes.\n *\n * The stream is patched rather than replaced because `EventStream` extends `ReadableStream`, so\n * handing back a bare async generator would drop `getReader`, `tee`, `pipeTo` and the rest of the\n * `ReadableStream` API the caller is entitled to.\n *\n * Both `for await` and `getReader()` are valid ways to drain a `ReadableStream`, and the SDK's\n * iterator polyfill reads through `getReader()`, so both are wrapped. The first path to see a chunk\n * claims accumulation and the other stays a pass-through, which keeps a chunk from being counted\n * twice when one path drives the other.\n *\n * Returns `false` for a value that is not a stream, leaving it untouched.\n */\nexport function instrumentEventStream(\n stream: unknown,\n span: Span,\n recordOutputs: boolean,\n abortSignal?: AbortSignal,\n): boolean {\n if (!isAsyncIterable(stream)) {\n return false;\n }\n\n const state = createStreamingState();\n let consumer: StreamConsumer | undefined;\n let settled = false;\n let cancelled = false;\n\n const claim = (candidate: StreamConsumer): boolean => {\n consumer ??= candidate;\n return consumer === candidate;\n };\n\n // Set synchronously when the caller asks to cancel, before the underlying cancel is awaited.\n // Cancelling can reject an in-flight `read()` (it aborts the HTTP body the stream reads from), and\n // that rejection would otherwise reach `settle` first and record a deliberate abort as a failure.\n const markCancelled = (): void => {\n cancelled = true;\n };\n\n const settle = (error?: unknown): void => {\n if (settled) {\n return;\n }\n settled = true;\n if (error !== undefined && !cancelled) {\n span.setStatus(getErrorStatus(abortSignal));\n }\n\n const toolCalls = Object.values(state.toolCalls);\n\n if (recordOutputs) {\n // Set the authoritative `gen_ai.output.messages` alongside the deprecated response attributes\n // `endStreamSpan` writes, so tool calls survive Relay's lossy migration. A stream is a single\n // assistant turn, so the accumulated fragments make up one message.\n setOutputMessagesAttribute(span, {\n responseText: state.responseTexts.join(''),\n toolCalls,\n finishReason: state.finishReasons[0],\n });\n }\n\n endStreamSpan(span, { ...state, toolCalls }, recordOutputs);\n };\n\n const iterate = stream[Symbol.asyncIterator].bind(stream);\n const instrumented = instrumentIterator(iterate, state, recordOutputs, claim, settle);\n stream[Symbol.asyncIterator] = () => instrumented;\n\n const readable = stream as ReadableStreamLike;\n\n if (typeof readable.getReader === 'function') {\n const getReader = readable.getReader.bind(readable);\n readable.getReader = (...args: unknown[]) =>\n wrapReader(getReader(...args), state, recordOutputs, claim, settle, markCancelled);\n }\n\n if (typeof readable.cancel === 'function') {\n const cancel = readable.cancel.bind(readable);\n readable.cancel = async (reason?: unknown): Promise<unknown> => {\n markCancelled();\n try {\n return await cancel(reason);\n } finally {\n settle();\n }\n };\n }\n\n // Only patched when `getReader` is present, since that is what `instrumentedSource` pulls through.\n if (typeof readable.getReader === 'function') {\n if (typeof readable.tee === 'function') {\n readable.tee = () => instrumentedSource(readable).tee();\n }\n\n if (typeof readable.pipeTo === 'function') {\n readable.pipeTo = (destination: unknown, options?: unknown) =>\n instrumentedSource(readable).pipeTo(destination as WritableStream<unknown>, options as StreamPipeOptions);\n }\n\n if (typeof readable.pipeThrough === 'function') {\n readable.pipeThrough = (transform: unknown, options?: unknown) =>\n instrumentedSource(readable).pipeThrough(\n transform as ReadableWritablePair<unknown, unknown>,\n options as StreamPipeOptions,\n );\n }\n }\n\n return true;\n}\n"],"mappings":";;;;AAuCA,SAAgB,gBAAgB,OAA8C;CAC5E,OAAO,CAAC,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O,WAAuC;GAC9D,cAAc;GACd,IAAI;IACF,OAAO,MAAM,OAAO,MAAM;GAC5B,UAAU;IACR,OAAO;GACT;EACF;CACF;CAGA,IAAI,OAAO,SAAS,cAAc,YAAY;EAC5C,IAAI,OAAO,SAAS,QAAQ,YAC1B,SAAS,YAAY,mBAAmB,QAAQ,CAAC,CAAC,IAAI;EAGxD,IAAI,OAAO,SAAS,WAAW,YAC7B,SAAS,UAAU,aAAsB,YACvC,mBAAmB,QAAQ,CAAC,CAAC,OAAO,aAAwC,OAA4B;EAG5G,IAAI,OAAO,SAAS,gBAAgB,YAClC,SAAS,eAAe,WAAoB,YAC1C,mBAAmB,QAAQ,CAAC,CAAC,YAC3B,WACA,OACF;CAEN;CAEA,OAAO;AACT"}
|
|
@@ -19,6 +19,14 @@ function getSpanName(operationName, attributes) {
|
|
|
19
19
|
return `${operationName} ${model}`;
|
|
20
20
|
}
|
|
21
21
|
/**
|
|
22
|
+
* Reads the caller's signal from Mistral's request options. The SDK spreads `options` over
|
|
23
|
+
* `options.fetchOptions`, so a top-level `signal` wins.
|
|
24
|
+
*/
|
|
25
|
+
function getMistralRequestSignal(requestOptions) {
|
|
26
|
+
const options = requestOptions;
|
|
27
|
+
return options?.signal ?? options?.fetchOptions?.signal;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
22
30
|
* Extract request parameters. Mistral request fields are camelCase.
|
|
23
31
|
*/
|
|
24
32
|
function extractRequestParameters(params) {
|
|
@@ -71,6 +79,6 @@ function addResponseAttributes(span, result, recordOutputs) {
|
|
|
71
79
|
span.setAttributes(attrs);
|
|
72
80
|
if (recordOutputs) setOutputMessagesAttribute(span, outputMessages);
|
|
73
81
|
}
|
|
74
|
-
export { addResponseAttributes, contentToString, extractRequestParameters, getSpanName };
|
|
82
|
+
export { addResponseAttributes, contentToString, extractRequestParameters, getMistralRequestSignal, getSpanName };
|
|
75
83
|
|
|
76
84
|
//# sourceMappingURL=utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":[],"sources":["../../../../src/ai/mistral/utils.ts"],"sourcesContent":["/* eslint-disable typescript-eslint/no-deprecated */\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport type { GenAiOutputMessage } from '../core/utils';\nimport { setOutputMessagesAttribute } from '../core/utils';\nimport {\n GEN_AI_REQUEST_FREQUENCY_PENALTY,\n GEN_AI_REQUEST_MAX_TOKENS,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_REQUEST_PRESENCE_PENALTY,\n GEN_AI_REQUEST_SEED,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n} from '@sentry/conventions/attributes';\n\n/**\n * Turn a Mistral message content (string or content-chunk array) into a plain string.\n */\nexport function contentToString(content: unknown): string {\n if (typeof content === 'string') {\n return content;\n }\n if (Array.isArray(content)) {\n return content\n .map(part =>\n part && typeof part === 'object' && typeof (part as { text?: unknown }).text === 'string'\n ? (part as { text: string }).text\n : '',\n )\n .join('');\n }\n return '';\n}\n\n/**\n * Build the span name for an instrumented Mistral call. Agent ids and a missing model are left out\n * to keep the name low cardinality.\n */\nexport function getSpanName(operationName: string, attributes: Record<string, unknown>): string {\n const model = attributes[GEN_AI_REQUEST_MODEL];\n\n if (operationName === 'invoke_agent' || typeof model !== 'string') {\n return operationName;\n }\n\n return `${operationName} ${model}`;\n}\n\n/**\n * Extract request parameters. Mistral request fields are camelCase.\n */\nexport function extractRequestParameters(params: Record<string, unknown>): Record<string, unknown> {\n const attributes: Record<string, unknown> = {};\n\n if (params.model != null) attributes[GEN_AI_REQUEST_MODEL] = params.model;\n if ('temperature' in params) attributes[GEN_AI_REQUEST_TEMPERATURE] = params.temperature;\n if ('topP' in params) attributes[GEN_AI_REQUEST_TOP_P] = params.topP;\n if ('maxTokens' in params) attributes[GEN_AI_REQUEST_MAX_TOKENS] = params.maxTokens;\n if ('frequencyPenalty' in params) attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY] = params.frequencyPenalty;\n if ('presencePenalty' in params) attributes[GEN_AI_REQUEST_PRESENCE_PENALTY] = params.presencePenalty;\n if ('randomSeed' in params) attributes[GEN_AI_REQUEST_SEED] = params.randomSeed;\n\n return attributes;\n}\n\n/**\n * Add response attributes to a span using duck-typing. Mistral responses are camelCase\n * (`choices[].message`, `usage.promptTokens`), matching the SDK's deserialized objects.\n */\nexport function addResponseAttributes(span: Span, result: unknown, recordOutputs?: boolean): void {\n if (!result || typeof result !== 'object') return;\n\n const response = result as Record<string, unknown>;\n const attrs: Record<string, SpanAttributeValue> = {};\n\n if (typeof response.id === 'string') {\n attrs[GEN_AI_RESPONSE_ID] = response.id;\n }\n\n if (typeof response.model === 'string') {\n attrs[GEN_AI_RESPONSE_MODEL] = response.model;\n }\n\n if (response.usage && typeof response.usage === 'object') {\n const usage = response.usage as Record<string, unknown>;\n if (typeof usage.promptTokens === 'number') attrs[GEN_AI_USAGE_INPUT_TOKENS] = usage.promptTokens;\n if (typeof usage.completionTokens === 'number') attrs[GEN_AI_USAGE_OUTPUT_TOKENS] = usage.completionTokens;\n if (typeof usage.totalTokens === 'number') attrs[GEN_AI_USAGE_TOTAL_TOKENS] = usage.totalTokens;\n }\n\n let outputMessages: GenAiOutputMessage[] = [];\n\n if (Array.isArray(response.choices)) {\n const choices = response.choices as Array<Record<string, unknown>>;\n\n const finishReasons = choices\n .map(choice => choice.finishReason)\n .filter((reason): reason is string => typeof reason === 'string');\n if (finishReasons.length > 0) {\n attrs[GEN_AI_RESPONSE_FINISH_REASONS] = JSON.stringify(finishReasons);\n }\n\n if (recordOutputs) {\n // One entry per choice: Mistral can return several when `n` > 1, and both attributes are\n // specified as arrays of messages rather than one merged blob.\n outputMessages = choices.map(choice => {\n const message = choice.message as Record<string, unknown> | undefined;\n return {\n responseText: contentToString(message?.content),\n toolCalls: Array.isArray(message?.toolCalls) ? message.toolCalls : undefined,\n finishReason: typeof choice.finishReason === 'string' ? choice.finishReason : undefined,\n };\n });\n\n const responseTexts = outputMessages.map(message => message.responseText).filter(Boolean);\n if (responseTexts.length > 0) {\n attrs[GEN_AI_RESPONSE_TEXT] = JSON.stringify(responseTexts);\n }\n\n const toolCalls = outputMessages.flatMap(message => message.toolCalls ?? []);\n if (toolCalls.length > 0) {\n attrs[GEN_AI_RESPONSE_TOOL_CALLS] = JSON.stringify(toolCalls);\n }\n }\n }\n\n span.setAttributes(attrs);\n\n if (recordOutputs) {\n setOutputMessagesAttribute(span, outputMessages);\n }\n}\n"],"mappings":";;;;;;AAyBA,SAAgB,gBAAgB,SAA0B;CACxD,IAAI,OAAO,YAAY,UACrB,OAAO;CAET,IAAI,MAAM,QAAQ,OAAO,GACvB,OAAO,QACJ,KAAI,SACH,QAAQ,OAAO,SAAS,YAAY,OAAQ,KAA4B,SAAS,WAC5E,KAA0B,OAC3B,EACN,CAAC,CACA,KAAK,EAAE;CAEZ,OAAO;AACT;;;;;AAMA,SAAgB,YAAY,eAAuB,YAA6C;CAC9F,MAAM,QAAQ,WAAW;CAEzB,IAAI,kBAAkB,kBAAkB,OAAO,UAAU,UACvD,OAAO;CAGT,OAAO,GAAG,cAAc,GAAG;AAC7B;;;;AAKA,SAAgB,yBAAyB,QAA0D;CACjG,MAAM,aAAsC,CAAC;CAE7C,IAAI,OAAO,SAAS,MAAM,WAAW,wBAAwB,OAAO;CACpE,IAAI,iBAAiB,QAAQ,WAAW,8BAA8B,OAAO;CAC7E,IAAI,UAAU,QAAQ,WAAW,wBAAwB,OAAO;CAChE,IAAI,eAAe,QAAQ,WAAW,6BAA6B,OAAO;CAC1E,IAAI,sBAAsB,QAAQ,WAAW,oCAAoC,OA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SAAS,GACzB,MAAM,wBAAwB,KAAK,UAAU,aAAa;GAG5D,MAAM,YAAY,eAAe,SAAQ,YAAW,QAAQ,aAAa,CAAC,CAAC;GAC3E,IAAI,UAAU,SAAS,GACrB,MAAM,8BAA8B,KAAK,UAAU,SAAS;EAEhE;CACF;CAEA,KAAK,cAAc,KAAK;CAExB,IAAI,eACF,2BAA2B,MAAM,cAAc;AAEnD"}
|
|
1
|
+
{"version":3,"file":"utils.js","names":[],"sources":["../../../../src/ai/mistral/utils.ts"],"sourcesContent":["/* eslint-disable typescript-eslint/no-deprecated */\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport type { GenAiOutputMessage } from '../core/utils';\nimport { setOutputMessagesAttribute } from '../core/utils';\nimport {\n GEN_AI_REQUEST_FREQUENCY_PENALTY,\n GEN_AI_REQUEST_MAX_TOKENS,\n GEN_AI_REQUEST_MODEL,\n GEN_AI_REQUEST_PRESENCE_PENALTY,\n GEN_AI_REQUEST_SEED,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_P,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_ID,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n} from '@sentry/conventions/attributes';\n\n/**\n * Turn a Mistral message content (string or content-chunk array) into a plain string.\n */\nexport function contentToString(content: unknown): string {\n if (typeof content === 'string') {\n return content;\n }\n if (Array.isArray(content)) {\n return content\n .map(part =>\n part && typeof part === 'object' && typeof (part as { text?: unknown }).text === 'string'\n ? (part as { text: string }).text\n : '',\n )\n .join('');\n }\n return '';\n}\n\n/**\n * Build the span name for an instrumented Mistral call. Agent ids and a missing model are left out\n * to keep the name low cardinality.\n */\nexport function getSpanName(operationName: string, attributes: Record<string, unknown>): string {\n const model = attributes[GEN_AI_REQUEST_MODEL];\n\n if (operationName === 'invoke_agent' || typeof model !== 'string') {\n return operationName;\n }\n\n return `${operationName} ${model}`;\n}\n\n/**\n * Reads the caller's signal from Mistral's request options. The SDK spreads `options` over\n * `options.fetchOptions`, so a top-level `signal` wins.\n */\nexport function getMistralRequestSignal(requestOptions: unknown): AbortSignal | undefined {\n const options = requestOptions as { signal?: AbortSignal; fetchOptions?: { signal?: AbortSignal } } | undefined;\n return options?.signal ?? options?.fetchOptions?.signal;\n}\n\n/**\n * Extract request parameters. Mistral request fields are camelCase.\n */\nexport function extractRequestParameters(params: Record<string, unknown>): Record<string, unknown> {\n const attributes: Record<string, unknown> = {};\n\n if (params.model != null) attributes[GEN_AI_REQUEST_MODEL] = params.model;\n if ('temperature' in params) attributes[GEN_AI_REQUEST_TEMPERATURE] = params.temperature;\n if ('topP' in params) attributes[GEN_AI_REQUEST_TOP_P] = params.topP;\n if ('maxTokens' in params) attributes[GEN_AI_REQUEST_MAX_TOKENS] = params.maxTokens;\n if ('frequencyPenalty' in params) attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY] = params.frequencyPenalty;\n if ('presencePenalty' in params) attributes[GEN_AI_REQUEST_PRESENCE_PENALTY] = params.presencePenalty;\n if ('randomSeed' in params) attributes[GEN_AI_REQUEST_SEED] = params.randomSeed;\n\n return attributes;\n}\n\n/**\n * Add response attributes to a span using duck-typing. Mistral responses are camelCase\n * (`choices[].message`, `usage.promptTokens`), matching the SDK's deserialized objects.\n */\nexport function addResponseAttributes(span: Span, result: unknown, recordOutputs?: boolean): void {\n if (!result || typeof result !== 'object') return;\n\n const response = result as Record<string, unknown>;\n const attrs: Record<string, SpanAttributeValue> = {};\n\n if (typeof response.id === 'string') {\n attrs[GEN_AI_RESPONSE_ID] = response.id;\n }\n\n if (typeof response.model === 'string') {\n attrs[GEN_AI_RESPONSE_MODEL] = response.model;\n }\n\n if (response.usage && typeof response.usage === 'object') {\n const usage = response.usage as Record<string, unknown>;\n if (typeof usage.promptTokens === 'number') attrs[GEN_AI_USAGE_INPUT_TOKENS] = usage.promptTokens;\n if (typeof usage.completionTokens === 'number') attrs[GEN_AI_USAGE_OUTPUT_TOKENS] = usage.completionTokens;\n if (typeof usage.totalTokens === 'number') attrs[GEN_AI_USAGE_TOTAL_TOKENS] = usage.totalTokens;\n }\n\n let outputMessages: GenAiOutputMessage[] = [];\n\n if (Array.isArray(response.choices)) {\n const choices = response.choices as Array<Record<string, unknown>>;\n\n const finishReasons = choices\n .map(choice => choice.finishReason)\n .filter((reason): reason is string => typeof reason === 'string');\n if (finishReasons.length > 0) {\n attrs[GEN_AI_RESPONSE_FINISH_REASONS] = JSON.stringify(finishReasons);\n }\n\n if (recordOutputs) {\n // One entry per choice: Mistral can return several when `n` > 1, and both attributes are\n // specified as arrays of messages rather than one merged blob.\n outputMessages = choices.map(choice => {\n const message = choice.message as Record<string, unknown> | undefined;\n return {\n responseText: contentToString(message?.content),\n toolCalls: Array.isArray(message?.toolCalls) ? message.toolCalls : undefined,\n finishReason: typeof choice.finishReason === 'string' ? choice.finishReason : undefined,\n };\n });\n\n const responseTexts = outputMessages.map(message => message.responseText).filter(Boolean);\n if (responseTexts.length > 0) {\n attrs[GEN_AI_RESPONSE_TEXT] = JSON.stringify(responseTexts);\n }\n\n const toolCalls = outputMessages.flatMap(message => message.toolCalls ?? []);\n if (toolCalls.length > 0) {\n attrs[GEN_AI_RESPONSE_TOOL_CALLS] = JSON.stringify(toolCalls);\n }\n }\n }\n\n span.setAttributes(attrs);\n\n if (recordOutputs) {\n setOutputMessagesAttribute(span, outputMessages);\n }\n}\n"],"mappings":";;;;;;AAyBA,SAAgB,gBAAgB,SAA0B;CACxD,IAAI,OAAO,YAAY,UACrB,OAAO;CAET,IAAI,MAAM,QAAQ,OAAO,GACvB,OAAO,QACJ,KAAI,SACH,QAAQ,OAAO,SAAS,YAAY,OAAQ,KAA4B,SAAS,WAC5E,KAA0B,OAC3B,EACN,CAAC,CACA,KAA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