@sentry/server-utils 11.14.0 → 11.15.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/exports.js +526 -217
- package/build/cjs/chunks/exports.js.map +1 -1
- package/build/cjs/index.js +1028 -120
- package/build/cjs/index.js.map +1 -1
- package/build/esm/ai/anthropic-ai/index.js +32 -56
- package/build/esm/ai/anthropic-ai/index.js.map +1 -1
- package/build/esm/ai/anthropic-ai/streaming.js +10 -6
- package/build/esm/ai/anthropic-ai/streaming.js.map +1 -1
- package/build/esm/ai/anthropic-ai/tool-runner.js +18 -3
- package/build/esm/ai/anthropic-ai/tool-runner.js.map +1 -1
- package/build/esm/ai/anthropic-ai/utils.js +41 -3
- package/build/esm/ai/anthropic-ai/utils.js.map +1 -1
- package/build/esm/ai/core/span-hooks.js +23 -0
- package/build/esm/ai/core/span-hooks.js.map +1 -0
- package/build/esm/ai/core/time-to-first-chunk.js +14 -0
- package/build/esm/ai/core/time-to-first-chunk.js.map +1 -0
- package/build/esm/ai/core/utils.js +29 -3
- package/build/esm/ai/core/utils.js.map +1 -1
- package/build/esm/ai/flue/index.js +15 -12
- package/build/esm/ai/flue/index.js.map +1 -1
- package/build/esm/ai/flue/utils.js +24 -17
- package/build/esm/ai/flue/utils.js.map +1 -1
- package/build/esm/ai/google-genai/index.js +21 -8
- package/build/esm/ai/google-genai/index.js.map +1 -1
- package/build/esm/ai/google-genai/streaming.js +6 -2
- package/build/esm/ai/google-genai/streaming.js.map +1 -1
- package/build/esm/ai/langchain/embeddings.js +5 -2
- package/build/esm/ai/langchain/embeddings.js.map +1 -1
- package/build/esm/ai/langchain/index.js +82 -24
- package/build/esm/ai/langchain/index.js.map +1 -1
- package/build/esm/ai/langchain/utils.js +9 -1
- package/build/esm/ai/langchain/utils.js.map +1 -1
- package/build/esm/ai/langgraph/agent-span.js +13 -5
- package/build/esm/ai/langgraph/agent-span.js.map +1 -1
- package/build/esm/ai/langgraph/index.js +13 -15
- package/build/esm/ai/langgraph/index.js.map +1 -1
- package/build/esm/ai/langgraph/stream.js +4 -3
- package/build/esm/ai/langgraph/stream.js.map +1 -1
- package/build/esm/ai/langgraph/utils.js +17 -8
- package/build/esm/ai/langgraph/utils.js.map +1 -1
- package/build/esm/ai/mastra/classifier-evaluation.js.map +1 -1
- package/build/esm/ai/mastra/index.js +33 -16
- package/build/esm/ai/mastra/index.js.map +1 -1
- package/build/esm/ai/mastra/utils.js +3 -5
- package/build/esm/ai/mastra/utils.js.map +1 -1
- package/build/esm/ai/mistral/index.js +21 -7
- package/build/esm/ai/mistral/index.js.map +1 -1
- package/build/esm/ai/mistral/streaming.js +4 -2
- package/build/esm/ai/mistral/streaming.js.map +1 -1
- package/build/esm/ai/openai/index.js +19 -8
- package/build/esm/ai/openai/index.js.map +1 -1
- package/build/esm/ai/openai/streaming.js +7 -2
- package/build/esm/ai/openai/streaming.js.map +1 -1
- package/build/esm/ai/pi-ai/chat.js +18 -1
- package/build/esm/ai/pi-ai/chat.js.map +1 -1
- package/build/esm/ai/pi-ai/recording.js +34 -15
- package/build/esm/ai/pi-ai/recording.js.map +1 -1
- package/build/esm/ai/pi-durable/index.js +7 -2
- package/build/esm/ai/pi-durable/index.js.map +1 -1
- package/build/esm/ai/pi-durable/runs.js.map +1 -1
- package/build/esm/ai/pi-durable/tools.js +18 -3
- package/build/esm/ai/pi-durable/tools.js.map +1 -1
- package/build/esm/ai/typesafe/index.js +14 -6
- package/build/esm/ai/typesafe/index.js.map +1 -1
- package/build/esm/ai/workers-ai/index.js +26 -9
- package/build/esm/ai/workers-ai/index.js.map +1 -1
- package/build/esm/ai/workers-ai/streaming.js +6 -4
- package/build/esm/ai/workers-ai/streaming.js.map +1 -1
- package/build/esm/cron/common.js +16 -0
- package/build/esm/cron/common.js.map +1 -0
- package/build/esm/cron/cron.js +82 -0
- package/build/esm/cron/cron.js.map +1 -0
- package/build/esm/cron/index.js +13 -0
- package/build/esm/cron/index.js.map +1 -0
- package/build/esm/cron/node-cron.js +66 -0
- package/build/esm/cron/node-cron.js.map +1 -0
- package/build/esm/cron/node-schedule.js +43 -0
- package/build/esm/cron/node-schedule.js.map +1 -0
- package/build/esm/index.js +6 -2
- package/build/esm/index.js.map +1 -1
- package/build/esm/integrations/anthropic.js +25 -16
- package/build/esm/integrations/anthropic.js.map +1 -1
- package/build/esm/integrations/aws-sdk/index.js +1 -0
- package/build/esm/integrations/aws-sdk/index.js.map +1 -1
- package/build/esm/integrations/aws-sdk/services/ServicesExtensions.js +3 -0
- package/build/esm/integrations/aws-sdk/services/ServicesExtensions.js.map +1 -1
- package/build/esm/integrations/aws-sdk/services/bedrock-runtime.js +45 -12
- package/build/esm/integrations/aws-sdk/services/bedrock-runtime.js.map +1 -1
- package/build/esm/integrations/bullmq/contextManager.js +45 -0
- package/build/esm/integrations/bullmq/contextManager.js.map +1 -0
- package/build/esm/integrations/bullmq/index.js +44 -0
- package/build/esm/integrations/bullmq/index.js.map +1 -0
- package/build/esm/integrations/bullmq/meter.js +86 -0
- package/build/esm/integrations/bullmq/meter.js.map +1 -0
- package/build/esm/integrations/bullmq/span.js +114 -0
- package/build/esm/integrations/bullmq/span.js.map +1 -0
- package/build/esm/integrations/bullmq/tracer.js +62 -0
- package/build/esm/integrations/bullmq/tracer.js.map +1 -0
- package/build/esm/integrations/express/instrumentation.js +10 -1
- package/build/esm/integrations/express/instrumentation.js.map +1 -1
- package/build/esm/integrations/google-genai.js +17 -9
- package/build/esm/integrations/google-genai.js.map +1 -1
- package/build/esm/integrations/langgraph.js +5 -7
- package/build/esm/integrations/langgraph.js.map +1 -1
- package/build/esm/integrations/mastra-classifier.js +1 -1
- package/build/esm/integrations/mastra-classifier.js.map +1 -1
- package/build/esm/integrations/mistral.js +13 -4
- package/build/esm/integrations/mistral.js.map +1 -1
- package/build/esm/integrations/openai-compatible.js +16 -8
- package/build/esm/integrations/openai-compatible.js.map +1 -1
- package/build/esm/integrations/openai.js +16 -8
- package/build/esm/integrations/openai.js.map +1 -1
- package/build/esm/integrations/pi-ai.js +39 -18
- package/build/esm/integrations/pi-ai.js.map +1 -1
- package/build/esm/integrations/pino.js +131 -0
- package/build/esm/integrations/pino.js.map +1 -0
- package/build/esm/integrations/typesafe.js +17 -3
- package/build/esm/integrations/typesafe.js.map +1 -1
- package/build/esm/integrations/vercel-ai/index.js.map +1 -1
- package/build/esm/integrations/vercel-ai/util.js +3 -2
- package/build/esm/integrations/vercel-ai/util.js.map +1 -1
- package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +44 -17
- package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
- package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js +22 -16
- package/build/esm/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.js.map +1 -1
- package/build/esm/integrations/winston.js +90 -0
- package/build/esm/integrations/winston.js.map +1 -0
- package/build/esm/orchestrion/detect.js +1 -1
- package/build/esm/orchestrion/detect.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/types/ai/anthropic-ai/index.d.ts +1 -5
- package/build/types/ai/anthropic-ai/index.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/streaming.d.ts +3 -2
- package/build/types/ai/anthropic-ai/streaming.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/tool-runner.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/types.d.ts +24 -3
- package/build/types/ai/anthropic-ai/types.d.ts.map +1 -1
- package/build/types/ai/anthropic-ai/utils.d.ts +2 -3
- package/build/types/ai/anthropic-ai/utils.d.ts.map +1 -1
- package/build/types/ai/core/span-hooks.d.ts +31 -0
- package/build/types/ai/core/span-hooks.d.ts.map +1 -0
- package/build/types/ai/core/time-to-first-chunk.d.ts +7 -0
- package/build/types/ai/core/time-to-first-chunk.d.ts.map +1 -0
- package/build/types/ai/core/utils.d.ts +30 -1
- package/build/types/ai/core/utils.d.ts.map +1 -1
- package/build/types/ai/flue/index.d.ts +13 -5
- package/build/types/ai/flue/index.d.ts.map +1 -1
- package/build/types/ai/flue/types.d.ts +20 -2
- package/build/types/ai/flue/types.d.ts.map +1 -1
- package/build/types/ai/flue/utils.d.ts +5 -9
- package/build/types/ai/flue/utils.d.ts.map +1 -1
- package/build/types/ai/google-genai/index.d.ts.map +1 -1
- package/build/types/ai/google-genai/streaming.d.ts +2 -1
- package/build/types/ai/google-genai/streaming.d.ts.map +1 -1
- package/build/types/ai/google-genai/types.d.ts +17 -3
- package/build/types/ai/google-genai/types.d.ts.map +1 -1
- package/build/types/ai/langchain/index.d.ts.map +1 -1
- package/build/types/ai/langchain/types.d.ts +49 -3
- package/build/types/ai/langchain/types.d.ts.map +1 -1
- package/build/types/ai/langchain/utils.d.ts +6 -0
- package/build/types/ai/langchain/utils.d.ts.map +1 -1
- package/build/types/ai/langgraph/agent-span.d.ts +4 -1
- package/build/types/ai/langgraph/agent-span.d.ts.map +1 -1
- package/build/types/ai/langgraph/index.d.ts +1 -1
- package/build/types/ai/langgraph/index.d.ts.map +1 -1
- package/build/types/ai/langgraph/stream.d.ts.map +1 -1
- package/build/types/ai/langgraph/types.d.ts +14 -3
- package/build/types/ai/langgraph/types.d.ts.map +1 -1
- package/build/types/ai/langgraph/utils.d.ts +3 -0
- package/build/types/ai/langgraph/utils.d.ts.map +1 -1
- package/build/types/ai/mastra/classifier-evaluation.d.ts +3 -3
- package/build/types/ai/mastra/classifier-evaluation.d.ts.map +1 -1
- package/build/types/ai/mastra/index.d.ts +17 -3
- package/build/types/ai/mastra/index.d.ts.map +1 -1
- package/build/types/ai/mastra/types.d.ts +2 -0
- package/build/types/ai/mastra/types.d.ts.map +1 -1
- package/build/types/ai/mastra/utils.d.ts.map +1 -1
- package/build/types/ai/mistral/index.d.ts.map +1 -1
- package/build/types/ai/mistral/streaming.d.ts +2 -1
- package/build/types/ai/mistral/streaming.d.ts.map +1 -1
- package/build/types/ai/mistral/types.d.ts +14 -3
- package/build/types/ai/mistral/types.d.ts.map +1 -1
- package/build/types/ai/openai/index.d.ts.map +1 -1
- package/build/types/ai/openai/streaming.d.ts +3 -1
- package/build/types/ai/openai/streaming.d.ts.map +1 -1
- package/build/types/ai/openai/types.d.ts +14 -3
- package/build/types/ai/openai/types.d.ts.map +1 -1
- package/build/types/ai/pi-ai/chat.d.ts +7 -1
- package/build/types/ai/pi-ai/chat.d.ts.map +1 -1
- package/build/types/ai/pi-ai/recording.d.ts +21 -9
- package/build/types/ai/pi-ai/recording.d.ts.map +1 -1
- package/build/types/ai/pi-ai/types.d.ts +16 -0
- package/build/types/ai/pi-ai/types.d.ts.map +1 -1
- package/build/types/ai/pi-durable/index.d.ts +12 -3
- package/build/types/ai/pi-durable/index.d.ts.map +1 -1
- package/build/types/ai/pi-durable/runs.d.ts +2 -0
- package/build/types/ai/pi-durable/runs.d.ts.map +1 -1
- package/build/types/ai/pi-durable/tools.d.ts +4 -3
- package/build/types/ai/pi-durable/tools.d.ts.map +1 -1
- package/build/types/ai/pi-durable/types.d.ts +15 -0
- package/build/types/ai/pi-durable/types.d.ts.map +1 -1
- package/build/types/ai/typesafe/index.d.ts +10 -2
- package/build/types/ai/typesafe/index.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 +2 -1
- package/build/types/ai/workers-ai/streaming.d.ts.map +1 -1
- package/build/types/ai/workers-ai/types.d.ts +18 -3
- package/build/types/ai/workers-ai/types.d.ts.map +1 -1
- package/build/types/cron/common.d.ts +8 -0
- package/build/types/cron/common.d.ts.map +1 -0
- package/build/types/cron/cron.d.ts +45 -0
- package/build/types/cron/cron.d.ts.map +1 -0
- package/build/types/cron/index.d.ts +10 -0
- package/build/types/cron/index.d.ts.map +1 -0
- package/build/types/cron/node-cron.d.ts +33 -0
- package/build/types/cron/node-cron.d.ts.map +1 -0
- package/build/types/cron/node-schedule.d.ts +19 -0
- package/build/types/cron/node-schedule.d.ts.map +1 -0
- package/build/types/index.d.ts +5 -2
- package/build/types/index.d.ts.map +1 -1
- package/build/types/integrations/anthropic.d.ts +2 -1
- package/build/types/integrations/anthropic.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/index.d.ts +3 -3
- package/build/types/integrations/aws-sdk/index.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/services/ServiceExtension.d.ts +1 -0
- package/build/types/integrations/aws-sdk/services/ServiceExtension.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/services/ServicesExtensions.d.ts +3 -2
- package/build/types/integrations/aws-sdk/services/ServicesExtensions.d.ts.map +1 -1
- package/build/types/integrations/aws-sdk/services/bedrock-runtime.d.ts +25 -4
- package/build/types/integrations/aws-sdk/services/bedrock-runtime.d.ts.map +1 -1
- package/build/types/integrations/bullmq/contextManager.d.ts +13 -0
- package/build/types/integrations/bullmq/contextManager.d.ts.map +1 -0
- package/build/types/integrations/bullmq/index.d.ts +43 -0
- package/build/types/integrations/bullmq/index.d.ts.map +1 -0
- package/build/types/integrations/bullmq/meter.d.ts +7 -0
- package/build/types/integrations/bullmq/meter.d.ts.map +1 -0
- package/build/types/integrations/bullmq/span.d.ts +35 -0
- package/build/types/integrations/bullmq/span.d.ts.map +1 -0
- package/build/types/integrations/bullmq/tracer.d.ts +5 -0
- package/build/types/integrations/bullmq/tracer.d.ts.map +1 -0
- package/build/types/integrations/bullmq/types.d.ts +72 -0
- package/build/types/integrations/bullmq/types.d.ts.map +1 -0
- package/build/types/integrations/express/types.d.ts +1 -0
- package/build/types/integrations/express/types.d.ts.map +1 -1
- package/build/types/integrations/flue.d.ts +2 -1
- package/build/types/integrations/flue.d.ts.map +1 -1
- package/build/types/integrations/google-genai.d.ts +2 -1
- package/build/types/integrations/google-genai.d.ts.map +1 -1
- package/build/types/integrations/groq.d.ts +1 -1
- package/build/types/integrations/langchain.d.ts +2 -1
- package/build/types/integrations/langchain.d.ts.map +1 -1
- package/build/types/integrations/langgraph.d.ts +2 -1
- package/build/types/integrations/langgraph.d.ts.map +1 -1
- package/build/types/integrations/mistral.d.ts +2 -1
- package/build/types/integrations/mistral.d.ts.map +1 -1
- package/build/types/integrations/openai-compatible.d.ts.map +1 -1
- package/build/types/integrations/openai.d.ts +2 -1
- package/build/types/integrations/openai.d.ts.map +1 -1
- package/build/types/integrations/pi-ai.d.ts +6 -3
- package/build/types/integrations/pi-ai.d.ts.map +1 -1
- package/build/types/integrations/pi-durable.d.ts +2 -1
- package/build/types/integrations/pi-durable.d.ts.map +1 -1
- package/build/types/integrations/pino.d.ts +61 -0
- package/build/types/integrations/pino.d.ts.map +1 -0
- package/build/types/integrations/together-ai.d.ts +1 -1
- package/build/types/integrations/typesafe.d.ts +2 -2
- package/build/types/integrations/typesafe.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/index.d.ts +3 -3
- package/build/types/integrations/vercel-ai/index.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/util.d.ts +2 -1
- package/build/types/integrations/vercel-ai/util.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts +20 -4
- package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/vercel-ai-orchestrion-subscriber.d.ts.map +1 -1
- package/build/types/integrations/winston.d.ts +55 -0
- package/build/types/integrations/winston.d.ts.map +1 -0
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":["resultObj"],"sources":["../../../../src/ai/langgraph/utils.ts"],"sourcesContent":["/* eslint-disable typescript-eslint/no-deprecated */\nimport { SPAN_STATUS_ERROR, startSpan, stringify } from '@sentry/core';\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport {\n GEN_AI_AGENT_NAME,\n GEN_AI_OPERATION_NAME,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_EXECUTE_TOOL } from '@sentry/conventions/op';\nimport { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport { setOutputMessagesAttribute } from '../core/utils';\nimport type { BaseChatModel, LangChainMessage } from '../langchain/types';\nimport {\n extractMessageTokenUsageAttributes,\n getConversationIdFromMetadata,\n normalizeLangChainMessages,\n} from '../langchain/utils';\nimport { LANGGRAPH_ORIGIN } from './constants';\nimport type { CompiledGraph, LangGraphOptions, LangGraphTool } from './types';\n\n/**\n * Extract LLM model object from createReactAgent params\n */\nexport function extractLLMFromParams(args: unknown[]): BaseChatModel | null {\n const arg = args[0];\n if (typeof arg !== 'object' || !arg || !('llm' in arg) || !arg.llm || typeof arg.llm !== 'object') {\n return null;\n }\n const llm = arg.llm as BaseChatModel;\n if (typeof llm.modelName !== 'string' && typeof llm.model !== 'string') {\n return null;\n }\n return llm;\n}\n\n/**\n * Extract agent name from createReactAgent params\n */\nexport function extractAgentNameFromParams(args: unknown[]): string | null {\n const arg = args[0];\n if (typeof arg === 'object' && !!arg && 'name' in arg && typeof arg.name === 'string') {\n return arg.name;\n }\n return null;\n}\n\n/**\n * Wraps an array of LangChain tools so each invocation creates a gen_ai.execute_tool span.\n *\n * Wraps each tool's invoke() method in place. A marker prevents double-wrapping.\n */\nexport function wrapToolsWithSpans(tools: unknown[], options: LangGraphOptions, agentName?: string): unknown[] {\n const SENTRY_WRAPPED = '__sentry_tool_wrapped__';\n\n for (const tool of tools) {\n if (!tool || typeof tool !== 'object') {\n continue;\n }\n\n const t = tool as Record<string, unknown>;\n const originalInvoke = t.invoke;\n if (typeof originalInvoke !== 'function' || Object.prototype.hasOwnProperty.call(t, SENTRY_WRAPPED)) {\n continue;\n }\n\n const toolName = typeof t.name === 'string' ? t.name : 'unknown_tool';\n const toolDescription = typeof t.description === 'string' ? t.description : undefined;\n\n const wrappedInvoke = new Proxy(originalInvoke as (...args: unknown[]) => unknown, {\n apply(target, thisArg, args: unknown[]): unknown {\n const spanAttributes: SpanAttributes = {\n [SENTRY_ORIGIN]: LANGGRAPH_ORIGIN,\n [SENTRY_OP]: GEN_AI_EXECUTE_TOOL,\n [GEN_AI_OPERATION_NAME]: 'execute_tool',\n [GEN_AI_TOOL_NAME]: toolName,\n };\n\n // Read agent name from LangChain's propagated config metadata at call time,\n // so shared tools get the correct agent name for each invocation\n const callConfig = args[1] as Record<string, unknown> | undefined;\n const callAgentName = (callConfig?.metadata as Record<string, unknown>)?.lc_agent_name ?? agentName;\n if (typeof callAgentName === 'string') {\n spanAttributes[GEN_AI_AGENT_NAME] = callAgentName;\n }\n Object.assign(spanAttributes, getConversationIdFromMetadata(callConfig?.metadata as Record<string, unknown>));\n\n if (toolDescription) {\n spanAttributes[GEN_AI_TOOL_DESCRIPTION] = toolDescription;\n }\n\n // LangGraph ToolNode passes { name, args, id, type: \"tool_call\" }\n const input = args[0] as Record<string, unknown> | undefined;\n if (typeof input === 'object' && !!input) {\n if ('id' in input && typeof input.id === 'string') {\n spanAttributes[GEN_AI_TOOL_CALL_ID_ATTRIBUTE] = input.id;\n }\n\n if (options.recordInputs) {\n const toolArgs = 'args' in input && typeof input.args === 'object' ? input.args : input;\n try {\n spanAttributes[GEN_AI_TOOL_CALL_ARGUMENTS] = JSON.stringify(toolArgs);\n } catch {\n // skip if not serializable\n }\n }\n }\n\n return startSpan(\n {\n name: `execute_tool ${toolName}`,\n attributes: spanAttributes,\n },\n async span => {\n try {\n const result = await Reflect.apply(target, thisArg, args);\n\n if (options.recordOutputs) {\n try {\n // ToolMessage objects wrap the result in .content\n const resultObj = result as Record<string, unknown> | undefined;\n const content =\n resultObj && typeof resultObj === 'object' && 'content' in resultObj ? resultObj.content : result;\n span.setAttribute(\n GEN_AI_TOOL_CALL_RESULT,\n typeof content === 'string' ? content : JSON.stringify(content),\n );\n } catch {\n // skip if not serializable\n }\n }\n\n return result;\n } catch (error) {\n // The error is rethrown to the caller (invoke() rejects), so we only mark the span\n // failed and do not record it.\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n throw error;\n }\n },\n );\n },\n });\n\n t.invoke = wrappedInvoke;\n Object.defineProperty(t, SENTRY_WRAPPED, { value: true, enumerable: false });\n }\n\n return tools;\n}\n\n/**\n * Extract tool calls from messages\n */\nexport function extractToolCalls(messages: Array<Record<string, unknown>> | null): unknown[] | null {\n if (!messages || messages.length === 0) {\n return null;\n }\n\n const toolCalls: unknown[] = [];\n\n for (const message of messages) {\n if (message && typeof message === 'object') {\n const msgToolCalls = message.tool_calls;\n if (msgToolCalls && Array.isArray(msgToolCalls)) {\n toolCalls.push(...msgToolCalls);\n }\n }\n }\n\n return toolCalls.length > 0 ? toolCalls : null;\n}\n\n/**\n * Extract token usage from a message's usage_metadata or response_metadata\n * Returns token counts without setting span attributes\n */\nexport function extractTokenUsageFromMessage(message: LangChainMessage): {\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n cacheCreationInputTokens?: number;\n cacheReadInputTokens?: number;\n} {\n const attributes = extractMessageTokenUsageAttributes(message);\n return {\n inputTokens: attributes[GEN_AI_USAGE_INPUT_TOKENS] ?? 0,\n outputTokens: attributes[GEN_AI_USAGE_OUTPUT_TOKENS] ?? 0,\n totalTokens: attributes[GEN_AI_USAGE_TOTAL_TOKENS] ?? 0,\n cacheCreationInputTokens: attributes[GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS],\n cacheReadInputTokens: attributes[GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS],\n };\n}\n\n/**\n * Extract model and finish reason from a message's response_metadata\n */\nexport function extractModelMetadata(span: Span, message: LangChainMessage): void {\n const msg = message as Record<string, unknown>;\n\n if (msg.response_metadata && typeof msg.response_metadata === 'object') {\n const metadata = msg.response_metadata as Record<string, unknown>;\n\n if (metadata.model_name && typeof metadata.model_name === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, metadata.model_name);\n }\n\n if (metadata.finish_reason && typeof metadata.finish_reason === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, JSON.stringify([metadata.finish_reason]));\n }\n }\n}\n\n/**\n * Extract tools from compiled graph structure\n *\n * Tools are stored in: compiledGraph.builder.nodes.tools.runnable.tools\n */\nexport function extractToolsFromCompiledGraph(compiledGraph: CompiledGraph): unknown[] | null {\n if (!compiledGraph.builder?.nodes?.tools?.runnable?.tools) {\n return null;\n }\n\n const tools = compiledGraph.builder?.nodes?.tools?.runnable?.tools;\n\n if (!tools || !Array.isArray(tools) || tools.length === 0) {\n return null;\n }\n\n // Extract name, description, and schema from each tool's lc_kwargs\n return tools.map((tool: LangGraphTool) => ({\n name: tool.lc_kwargs?.name,\n description: tool.lc_kwargs?.description,\n schema: tool.lc_kwargs?.schema,\n }));\n}\n\n/**\n * Set response attributes on the span\n */\nexport function setResponseAttributes(span: Span, inputMessages: LangChainMessage[] | null, result: unknown): void {\n // Extract messages from result\n const resultObj = result as { messages?: LangChainMessage[] } | undefined;\n const outputMessages = resultObj?.messages;\n\n if (!outputMessages || !Array.isArray(outputMessages)) {\n // Custom state annotations have no `messages` array, the whole state is recorded instead.\n if (result && typeof result === 'object') {\n const serializedState = stringify(result);\n // `gen_ai.output.messages` is what the product reads first; `gen_ai.response.text` is kept for\n // back-compat (Relay still migrates it).\n setOutputMessagesAttribute(span, { responseText: serializedState });\n span.setAttribute(GEN_AI_RESPONSE_TEXT, stringify([{ role: 'assistant', content: serializedState }]));\n }\n return;\n }\n\n // Get new messages (delta between input and output)\n const inputCount = inputMessages?.length ?? 0;\n const newMessages = outputMessages.length > inputCount ? outputMessages.slice(inputCount) : [];\n\n if (newMessages.length === 0) {\n return;\n }\n\n // Extract and set tool calls from new messages BEFORE normalization\n // (normalization strips tool_calls, so we need to extract them first)\n const toolCalls = extractToolCalls(newMessages);\n if (toolCalls) {\n span.setAttribute(GEN_AI_RESPONSE_TOOL_CALLS, JSON.stringify(toolCalls));\n }\n\n // Normalize the new messages\n const normalizedNewMessages = normalizeLangChainMessages(newMessages);\n span.setAttribute(GEN_AI_RESPONSE_TEXT, JSON.stringify(normalizedNewMessages));\n\n // Accumulate token usage across all messages\n let totalInputTokens = 0;\n let totalOutputTokens = 0;\n let totalTokens = 0;\n let cacheCreationInputTokens: number | undefined;\n let cacheReadInputTokens: number | undefined;\n\n // Extract metadata from messages\n for (const message of newMessages) {\n // Accumulate token usage\n const tokens = extractTokenUsageFromMessage(message);\n totalInputTokens += tokens.inputTokens;\n totalOutputTokens += tokens.outputTokens;\n totalTokens += tokens.totalTokens;\n if (tokens.cacheCreationInputTokens !== undefined) {\n cacheCreationInputTokens = (cacheCreationInputTokens ?? 0) + tokens.cacheCreationInputTokens;\n }\n if (tokens.cacheReadInputTokens !== undefined) {\n cacheReadInputTokens = (cacheReadInputTokens ?? 0) + tokens.cacheReadInputTokens;\n }\n\n // Extract model metadata (last message's metadata wins for model/finish_reason)\n extractModelMetadata(span, message);\n }\n\n // Set accumulated token usage on span\n if (totalInputTokens > 0) {\n span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, totalInputTokens);\n }\n if (totalOutputTokens > 0) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, totalOutputTokens);\n }\n if (totalTokens > 0) {\n span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, totalTokens);\n }\n if (cacheCreationInputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheCreationInputTokens);\n }\n if (cacheReadInputTokens !== undefined) {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,SAAS;GAAgB,CAAC,CAAC,CAAC;EACtG;EACA;CACF;CAGA,MAAM,aAAa,eAAe,UAAU;CAC5C,MAAM,cAAc,eAAe,SAAS,aAAa,eAAe,MAAM,UAAU,IAAI,CAAC;CAE7F,IAAI,YAAY,WAAW,GACzB;CAKF,MAAM,YAAY,iBAAiB,WAAW;CAC9C,IAAI,WACF,KAAK,aAAa,4BAA4B,KAAK,UAAU,SAAS,CAAC;CAIzE,MAAM,wBAAwB,2BAA2B,WAAW;CACpE,KAAK,aAAa,sBAAsB,KAAK,UAAU,qBAAqB,CAAC;CAG7E,IAAI,mBAAmB;CACvB,IAAI,oBAAoB;CACxB,IAAI,cAAc;CAClB,IAAI;CACJ,IAAI;CAGJ,KAAK,MAAM,WAAW,aAAa;EAEjC,MAAM,SAAS,6BAA6B,OAAO;EACnD,oBAAoB,OAAO;EAC3B,qBAAqB,OAAO;EAC5B,eAAe,OAAO;EACtB,IAAI,OAAO,6BAA6B,KAAA,GACtC,4BAA4B,4BAA4B,KAAK,OAAO;EAEtE,IAAI,OAAO,yBAAyB,KAAA,GAClC,wBAAwB,wBAAwB,KAAK,OAAO;EAI9D,qBAAqB,MAAM,OAAO;CACpC;CAGA,IAAI,mBAAmB,GACrB,KAAK,aAAa,2BAA2B,gBAAgB;CAE/D,IAAI,oBAAoB,GACtB,KAAK,aAAa,4BAA4B,iBAAiB;CAEjE,IAAI,cAAc,GAChB,KAAK,aAAa,2BAA2B,WAAW;CAE1D,IAAI,6BAA6B,KAAA,GAC/B,KAAK,aAAa,0CAA0C,wBAAwB;CAEtF,IAAI,yBAAyB,KAAA,GAC3B,KAAK,aAAa,sCAAsC,oBAAoB;AAEhF"}
|
|
1
|
+
{"version":3,"file":"utils.js","names":["resultObj"],"sources":["../../../../src/ai/langgraph/utils.ts"],"sourcesContent":["/* eslint-disable typescript-eslint/no-deprecated */\nimport { SPAN_STATUS_ERROR, startSpan, stringify } from '@sentry/core';\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport {\n GEN_AI_AGENT_NAME,\n GEN_AI_OPERATION_NAME,\n GEN_AI_RESPONSE_FINISH_REASONS,\n GEN_AI_RESPONSE_MODEL,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_RESPONSE_TOOL_CALLS,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { GEN_AI_EXECUTE_TOOL } from '@sentry/conventions/op';\nimport { GEN_AI_TOOL_CALL_ID_ATTRIBUTE } from '../core/gen-ai-attributes';\nimport { resolveAIRecordingOptions, setOutputMessagesAttribute } from '../core/utils';\nimport type { GenAiOptions } from '../core/utils';\nimport type { BaseChatModel, LangChainMessage } from '../langchain/types';\nimport {\n extractMessageTokenUsageAttributes,\n getConversationIdFromMetadata,\n getLangGraphRunRecording,\n normalizeLangChainMessages,\n} from '../langchain/utils';\nimport { LANGGRAPH_ORIGIN } from './constants';\nimport type { CompiledGraph, LangGraphOptions, LangGraphTool } from './types';\n\n/**\n * Extract LLM model object from createReactAgent params\n */\nexport function extractLLMFromParams(args: unknown[]): BaseChatModel | null {\n const arg = args[0];\n if (typeof arg !== 'object' || !arg || !('llm' in arg) || !arg.llm || typeof arg.llm !== 'object') {\n return null;\n }\n const llm = arg.llm as BaseChatModel;\n if (typeof llm.modelName !== 'string' && typeof llm.model !== 'string') {\n return null;\n }\n return llm;\n}\n\n/**\n * Extract agent name from createReactAgent params\n */\nexport function extractAgentNameFromParams(args: unknown[]): string | null {\n const arg = args[0];\n if (typeof arg === 'object' && !!arg && 'name' in arg && typeof arg.name === 'string') {\n return arg.name;\n }\n return null;\n}\n\n/** The options that hold outside a graph run, where no `invoke()`/`stream()` call decided: a function needs the graph input. */\nexport function getBooleanRecordingOptions(options: LangGraphOptions): GenAiOptions {\n const { recordInputs, recordOutputs } = options;\n return {\n recordInputs: typeof recordInputs === 'boolean' ? recordInputs : undefined,\n recordOutputs: typeof recordOutputs === 'boolean' ? recordOutputs : undefined,\n };\n}\n\n/**\n * Wraps an array of LangChain tools so each invocation creates a gen_ai.execute_tool span.\n *\n * Wraps each tool's invoke() method in place. A marker prevents double-wrapping.\n */\nexport function wrapToolsWithSpans(tools: unknown[], options: LangGraphOptions, agentName?: string): unknown[] {\n const SENTRY_WRAPPED = '__sentry_tool_wrapped__';\n\n for (const tool of tools) {\n if (!tool || typeof tool !== 'object') {\n continue;\n }\n\n const t = tool as Record<string, unknown>;\n const originalInvoke = t.invoke;\n if (typeof originalInvoke !== 'function' || Object.prototype.hasOwnProperty.call(t, SENTRY_WRAPPED)) {\n continue;\n }\n\n const toolName = typeof t.name === 'string' ? t.name : 'unknown_tool';\n const toolDescription = typeof t.description === 'string' ? t.description : undefined;\n\n const wrappedInvoke = new Proxy(originalInvoke as (...args: unknown[]) => unknown, {\n apply(target, thisArg, args: unknown[]): unknown {\n const spanAttributes: SpanAttributes = {\n [SENTRY_ORIGIN]: LANGGRAPH_ORIGIN,\n [SENTRY_OP]: GEN_AI_EXECUTE_TOOL,\n [GEN_AI_OPERATION_NAME]: 'execute_tool',\n [GEN_AI_TOOL_NAME]: toolName,\n };\n\n // Read agent name from LangChain's propagated config metadata at call time,\n // so shared tools get the correct agent name for each invocation\n const callConfig = args[1] as Record<string, unknown> | undefined;\n const metadata = callConfig?.metadata as Record<string, unknown> | undefined;\n const { recordInputs, recordOutputs } =\n getLangGraphRunRecording(metadata) ?? resolveAIRecordingOptions(getBooleanRecordingOptions(options));\n const callAgentName = metadata?.lc_agent_name ?? agentName;\n if (typeof callAgentName === 'string') {\n spanAttributes[GEN_AI_AGENT_NAME] = callAgentName;\n }\n Object.assign(spanAttributes, getConversationIdFromMetadata(metadata));\n\n if (toolDescription) {\n spanAttributes[GEN_AI_TOOL_DESCRIPTION] = toolDescription;\n }\n\n // LangGraph ToolNode passes { name, args, id, type: \"tool_call\" }\n const input = args[0] as Record<string, unknown> | undefined;\n if (typeof input === 'object' && !!input) {\n if ('id' in input && typeof input.id === 'string') {\n spanAttributes[GEN_AI_TOOL_CALL_ID_ATTRIBUTE] = input.id;\n }\n\n if (recordInputs) {\n const toolArgs = 'args' in input && typeof input.args === 'object' ? input.args : input;\n try {\n spanAttributes[GEN_AI_TOOL_CALL_ARGUMENTS] = JSON.stringify(toolArgs);\n } catch {\n // skip if not serializable\n }\n }\n }\n\n return startSpan(\n {\n name: `execute_tool ${toolName}`,\n attributes: spanAttributes,\n },\n async span => {\n try {\n const result = await Reflect.apply(target, thisArg, args);\n\n if (recordOutputs) {\n try {\n // ToolMessage objects wrap the result in .content\n const resultObj = result as Record<string, unknown> | undefined;\n const content =\n resultObj && typeof resultObj === 'object' && 'content' in resultObj ? resultObj.content : result;\n span.setAttribute(\n GEN_AI_TOOL_CALL_RESULT,\n typeof content === 'string' ? content : JSON.stringify(content),\n );\n } catch {\n // skip if not serializable\n }\n }\n\n return result;\n } catch (error) {\n // The error is rethrown to the caller (invoke() rejects), so we only mark the span\n // failed and do not record it.\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n throw error;\n }\n },\n );\n },\n });\n\n t.invoke = wrappedInvoke;\n Object.defineProperty(t, SENTRY_WRAPPED, { value: true, enumerable: false });\n }\n\n return tools;\n}\n\n/**\n * Extract tool calls from messages\n */\nexport function extractToolCalls(messages: Array<Record<string, unknown>> | null): unknown[] | null {\n if (!messages || messages.length === 0) {\n return null;\n }\n\n const toolCalls: unknown[] = [];\n\n for (const message of messages) {\n if (message && typeof message === 'object') {\n const msgToolCalls = message.tool_calls;\n if (msgToolCalls && Array.isArray(msgToolCalls)) {\n toolCalls.push(...msgToolCalls);\n }\n }\n }\n\n return toolCalls.length > 0 ? toolCalls : null;\n}\n\n/**\n * Extract token usage from a message's usage_metadata or response_metadata\n * Returns token counts without setting span attributes\n */\nexport function extractTokenUsageFromMessage(message: LangChainMessage): {\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n cacheCreationInputTokens?: number;\n cacheReadInputTokens?: number;\n} {\n const attributes = extractMessageTokenUsageAttributes(message);\n return {\n inputTokens: attributes[GEN_AI_USAGE_INPUT_TOKENS] ?? 0,\n outputTokens: attributes[GEN_AI_USAGE_OUTPUT_TOKENS] ?? 0,\n totalTokens: attributes[GEN_AI_USAGE_TOTAL_TOKENS] ?? 0,\n cacheCreationInputTokens: attributes[GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS],\n cacheReadInputTokens: attributes[GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS],\n };\n}\n\n/**\n * Extract model and finish reason from a message's response_metadata\n */\nexport function extractModelMetadata(span: Span, message: LangChainMessage): void {\n const msg = message as Record<string, unknown>;\n\n if (msg.response_metadata && typeof msg.response_metadata === 'object') {\n const metadata = msg.response_metadata as Record<string, unknown>;\n\n if (metadata.model_name && typeof metadata.model_name === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_MODEL, metadata.model_name);\n }\n\n if (metadata.finish_reason && typeof metadata.finish_reason === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, JSON.stringify([metadata.finish_reason]));\n }\n }\n}\n\n/**\n * Extract tools from compiled graph structure\n *\n * Tools are stored in: compiledGraph.builder.nodes.tools.runnable.tools\n */\nexport function extractToolsFromCompiledGraph(compiledGraph: CompiledGraph): unknown[] | null {\n if (!compiledGraph.builder?.nodes?.tools?.runnable?.tools) {\n return null;\n }\n\n const tools = compiledGraph.builder?.nodes?.tools?.runnable?.tools;\n\n if (!tools || !Array.isArray(tools) || tools.length === 0) {\n return null;\n }\n\n // Extract name, description, and schema from each tool's lc_kwargs\n return tools.map((tool: LangGraphTool) => ({\n name: tool.lc_kwargs?.name,\n description: tool.lc_kwargs?.description,\n schema: tool.lc_kwargs?.schema,\n }));\n}\n\n/**\n * Set response attributes on the span\n */\nexport function setResponseAttributes(span: Span, inputMessages: LangChainMessage[] | null, result: unknown): void {\n // Extract messages from result\n const resultObj = result as { messages?: LangChainMessage[] } | undefined;\n const outputMessages = resultObj?.messages;\n\n if (!outputMessages || !Array.isArray(outputMessages)) {\n // Custom state annotations have no `messages` array, the whole state is recorded instead.\n if (result && typeof result === 'object') {\n const serializedState = stringify(result);\n // `gen_ai.output.messages` is what the product reads first; `gen_ai.response.text` is kept for\n // back-compat (Relay still migrates it).\n setOutputMessagesAttribute(span, { responseText: serializedState });\n span.setAttribute(GEN_AI_RESPONSE_TEXT, stringify([{ role: 'assistant', content: serializedState }]));\n }\n return;\n }\n\n // Get new messages (delta between input and output)\n const inputCount = inputMessages?.length ?? 0;\n const newMessages = outputMessages.length > inputCount ? outputMessages.slice(inputCount) : [];\n\n if (newMessages.length === 0) {\n return;\n }\n\n // Extract and set tool calls from new messages BEFORE normalization\n // (normalization strips tool_calls, so we need to extract them first)\n const toolCalls = extractToolCalls(newMessages);\n if (toolCalls) {\n span.setAttribute(GEN_AI_RESPONSE_TOOL_CALLS, JSON.stringify(toolCalls));\n }\n\n // Normalize the new messages\n const normalizedNewMessages = normalizeLangChainMessages(newMessages);\n span.setAttribute(GEN_AI_RESPONSE_TEXT, JSON.stringify(normalizedNewMessages));\n\n // Accumulate token usage across all messages\n let totalInputTokens = 0;\n let totalOutputTokens = 0;\n let totalTokens = 0;\n let cacheCreationInputTokens: number | undefined;\n let cacheReadInputTokens: number | undefined;\n\n // Extract metadata from messages\n for (const message of newMessages) {\n // Accumulate token usage\n const tokens = extractTokenUsageFromMessage(message);\n totalInputTokens += tokens.inputTokens;\n totalOutputTokens += tokens.outputTokens;\n totalTokens += tokens.totalTokens;\n if (tokens.cacheCreationInputTokens !== undefined) {\n cacheCreationInputTokens = (cacheCreationInputTokens ?? 0) + tokens.cacheCreationInputTokens;\n }\n if (tokens.cacheReadInputTokens !== undefined) {\n cacheReadInputTokens = (cacheReadInputTokens ?? 0) + tokens.cacheReadInputTokens;\n }\n\n // Extract model metadata (last message's metadata wins for model/finish_reason)\n extractModelMetadata(span, message);\n }\n\n // Set accumulated token usage on span\n if (totalInputTokens > 0) {\n span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, totalInputTokens);\n }\n if (totalOutputTokens > 0) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, totalOutputTokens);\n }\n if (totalTokens > 0) {\n span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, totalTokens);\n }\n if (cacheCreationInputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, cacheCreationInputTokens);\n }\n if (cacheReadInputTokens !== undefined) {\n span.setAttribute(GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, cacheReadInputTokens);\n }\n}\n"],"mappings":";;;;;;;;;;;AAuCA,SAAgB,qBAAqB,MAAuC;CAC1E,MAAM,MAAM,KAAK;CACjB,IAAI,OAAO,QAAQ,YAAY,CAAC,OAAO,EAAE,SAAS,QAAQ,CAAC,IAAI,OAAO,OAAO,IAAI,QAAQ,UACvF,OAAO;CAET,MAAM,MAAM,IAAI;CAChB,IAAI,OAAO,IAAI,cAAc,YAAY,OAAO,IAAI,UAAU,UAC5D,OAAO;CAET,OAAO;AACT;;;;AAKA,SAAgB,2BAA2B,MAAgC;CACzE,MAAM,MAAM,KAAK;CACjB,IAAI,OAAO,QAAQ,YAAY,CAAC,CAAC,OAAO,UAAU,OAAO,OAAO,IAAI,SAAS,UAC3E,OAAO,IAAI;CAEb,OAAO;AACT;;AAGA,SAAgB,2BAA2B,SAAyC;CAClF,MAAM,EAAE,cAAc,kBAAkB;CACxC,OAAO;EACL,cAAc,OAAO,iBAAiB,YAAY,eAAe,KAAA;EACjE,eAAe,OAAO,kBAAkB,YAAY,gB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AAM,WAAW,aAAa;EAEjC,MAAM,SAAS,6BAA6B,OAAO;EACnD,oBAAoB,OAAO;EAC3B,qBAAqB,OAAO;EAC5B,eAAe,OAAO;EACtB,IAAI,OAAO,6BAA6B,KAAA,GACtC,4BAA4B,4BAA4B,KAAK,OAAO;EAEtE,IAAI,OAAO,yBAAyB,KAAA,GAClC,wBAAwB,wBAAwB,KAAK,OAAO;EAI9D,qBAAqB,MAAM,OAAO;CACpC;CAGA,IAAI,mBAAmB,GACrB,KAAK,aAAa,2BAA2B,gBAAgB;CAE/D,IAAI,oBAAoB,GACtB,KAAK,aAAa,4BAA4B,iBAAiB;CAEjE,IAAI,cAAc,GAChB,KAAK,aAAa,2BAA2B,WAAW;CAE1D,IAAI,6BAA6B,KAAA,GAC/B,KAAK,aAAa,0CAA0C,wBAAwB;CAEtF,IAAI,yBAAyB,KAAA,GAC3B,KAAK,aAAa,sCAAsC,oBAAoB;AAEhF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"classifier-evaluation.js","names":[],"sources":["../../../../src/ai/mastra/classifier-evaluation.ts"],"sourcesContent":["import type { Span
|
|
1
|
+
{"version":3,"file":"classifier-evaluation.js","names":[],"sources":["../../../../src/ai/mastra/classifier-evaluation.ts"],"sourcesContent":["import type { Span } from '@sentry/core';\nimport type { MastraExportedSpan, MastraSpanOutputProcessor } from './types';\n\n/**\n * Links a `Classifier.evaluate()` call to the Sentry span the exporter opens for its\n * `classifier_evaluation` span. Mastra's span carries no input or output, so the integration adds\n * them from the call. Mastra ends its span before `evaluate()` returns the answers, so the exporter\n * leaves the Sentry span open and the integration ends it once the call settles.\n */\nexport interface ClassifierEvaluationCall {\n span?: Span;\n /** Mastra's span and the processors of its observability instance, to filter the call's data. */\n mastraSpan?: MastraExportedSpan;\n spanOutputProcessors?: MastraSpanOutputProcessor[];\n /** The recording options of the exporter that opened the span, so the call's data follows them. */\n recordInputs?: boolean;\n recordOutputs?: boolean;\n /** Ends the span at Mastra's end time, set when Mastra ended its span before the call settled. */\n end?: () => void;\n settled?: boolean;\n}\n\n// Mastra emits `span_started` synchronously inside `evaluate()`, before its first `await`, so at\n// most one call is ever in this window.\nlet startingCall: ClassifierEvaluationCall | undefined;\n\nexport function setStartingClassifierEvaluation(call: ClassifierEvaluationCall | undefined): void {\n startingCall = call;\n}\n\nexport function takeStartingClassifierEvaluation(): ClassifierEvaluationCall | undefined {\n const call = startingCall;\n startingCall = undefined;\n return call;\n}\n\n/**\n * Run the call's data through Mastra's span output processors (for example its default\n * `SensitiveDataFilter`), as Mastra does for the input and output of its own spans. Returns `undefined`\n * when a processor drops the span or throws, so unfiltered data is never recorded.\n */\nexport function processClassifierEvaluationData(\n call: ClassifierEvaluationCall,\n data: { input?: unknown; output?: unknown },\n): { input?: unknown; output?: unknown } | undefined {\n let span: MastraExportedSpan | undefined = { ...call.mastraSpan, ...data } as MastraExportedSpan;\n for (const processor of call.spanOutputProcessors ?? []) {\n try {\n span = processor.process(span);\n } catch {\n return undefined;\n }\n if (!span) {\n return undefined;\n }\n }\n return span;\n}\n"],"mappings":";AAwBA,IAAI;AAEJ,SAAgB,gCAAgC,MAAkD;CAChG,eAAe;AACjB;AAEA,SAAgB,mCAAyE;CACvF,MAAM,OAAO;CACb,eAAe,KAAA;CACf,OAAO;AACT;;;;;;AAOA,SAAgB,gCACd,MACA,MACmD;CACnD,IAAI,OAAuC;EAAE,GAAG,KAAK;EAAY,GAAG;CAAK;CACzE,KAAK,MAAM,aAAa,KAAK,wBAAwB,CAAC,GAAG;EACvD,IAAI;GACF,OAAO,UAAU,QAAQ,IAAI;EAC/B,QAAQ;GACN;EACF;EACA,IAAI,CAAC,MACH;CAEJ;CACA,OAAO;AACT"}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { DEBUG_BUILD } from "../../debug-build.js";
|
|
2
|
-
import {
|
|
2
|
+
import { runGenAiSpanEnd, runGenAiSpanStart } from "../core/span-hooks.js";
|
|
3
|
+
import { resolveGenAiCallRecording } from "../core/utils.js";
|
|
3
4
|
import { getOperation, getSpanAttributes, getSpanName, getUsageAttributes, isExportedSpanType, mergeUsageAttributes } from "./utils.js";
|
|
4
5
|
import { AGENT_SPAN_TYPES, MASTRA_EXPORTER_BRAND, MASTRA_EXPORTER_NAME, MASTRA_ORIGIN, MAX_TRACKED_MASTRA_SPANS, MODEL_SPAN_TYPES } from "./constants.js";
|
|
5
6
|
import { takeStartingClassifierEvaluation } from "./classifier-evaluation.js";
|
|
6
7
|
import { registerMastraSpan, unregisterMastraSpan } from "./span-registry.js";
|
|
7
|
-
import { GEN_AI_RESPONSE_MODEL, SENTRY_OP, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
|
|
8
|
+
import { GEN_AI_CONVERSATION_ID, GEN_AI_RESPONSE_MODEL, SENTRY_OP, SENTRY_ORIGIN } from "@sentry/conventions/attributes";
|
|
8
9
|
import { LRUMap, SPAN_STATUS_ERROR, debug, flush, getActiveSpan, getClient, startInactiveSpan, timestampInSeconds } from "@sentry/core";
|
|
9
10
|
// src/ai/mastra/index.ts
|
|
10
11
|
const FLUSH_TIMEOUT_MS = 2e3;
|
|
@@ -45,7 +46,7 @@ var SentryMastraExporter = class {
|
|
|
45
46
|
/** End open spans, then flush. Does not close the Sentry client. */
|
|
46
47
|
async shutdown() {
|
|
47
48
|
for (const id of this._spans.keys()) unregisterMastraSpan(id);
|
|
48
|
-
for (const
|
|
49
|
+
for (const tracked of this._spans.values()) this._endSpan(tracked, {});
|
|
49
50
|
this._spans.clear();
|
|
50
51
|
this._skipped.clear();
|
|
51
52
|
await this.flush();
|
|
@@ -58,18 +59,19 @@ var SentryMastraExporter = class {
|
|
|
58
59
|
else if (event.type === "span_ended") this._skipped.remove(span.id);
|
|
59
60
|
return;
|
|
60
61
|
}
|
|
61
|
-
const recordingOptions = resolveAIRecordingOptions(this._options);
|
|
62
62
|
switch (event.type) {
|
|
63
63
|
case "span_started":
|
|
64
|
-
this._onSpanStarted(span
|
|
64
|
+
this._onSpanStarted(span);
|
|
65
65
|
break;
|
|
66
66
|
case "span_updated":
|
|
67
|
-
this._onSpanUpdated(span
|
|
67
|
+
this._onSpanUpdated(span);
|
|
68
68
|
break;
|
|
69
|
-
case "span_ended": this._onSpanEnded(span
|
|
69
|
+
case "span_ended": this._onSpanEnded(span);
|
|
70
70
|
}
|
|
71
71
|
}
|
|
72
|
-
_onSpanStarted(span
|
|
72
|
+
_onSpanStarted(span) {
|
|
73
|
+
const call = { span };
|
|
74
|
+
const recordingOptions = resolveGenAiCallRecording(this._options, call);
|
|
73
75
|
const parentId = this._resolveParentId(span.parentSpanId);
|
|
74
76
|
const parentSpan = parentId ? this._spans.get(parentId)?.span : void 0;
|
|
75
77
|
const activeSpan = getActiveSpan();
|
|
@@ -79,10 +81,12 @@ var SentryMastraExporter = class {
|
|
|
79
81
|
parentSpan: parentSpan ?? activeSpan,
|
|
80
82
|
attributes: {
|
|
81
83
|
...getSpanAttributes(span, recordingOptions),
|
|
84
|
+
[GEN_AI_CONVERSATION_ID]: span.attributes?.conversationId ?? span.metadata?.threadId,
|
|
82
85
|
[SENTRY_OP]: getOperation(span.type)?.op,
|
|
83
86
|
[SENTRY_ORIGIN]: MASTRA_ORIGIN
|
|
84
87
|
}
|
|
85
88
|
});
|
|
89
|
+
runGenAiSpanStart(this._options, sentrySpan, call);
|
|
86
90
|
const evaluation = span.type === "classifier_evaluation" ? takeStartingClassifierEvaluation() : void 0;
|
|
87
91
|
if (evaluation) Object.assign(evaluation, {
|
|
88
92
|
span: sentrySpan,
|
|
@@ -93,37 +97,47 @@ var SentryMastraExporter = class {
|
|
|
93
97
|
});
|
|
94
98
|
this._trackSpan(span.id, {
|
|
95
99
|
span: sentrySpan,
|
|
100
|
+
call,
|
|
96
101
|
spanType: span.type,
|
|
97
102
|
usage: {},
|
|
103
|
+
recordingOptions,
|
|
98
104
|
evaluation
|
|
99
105
|
});
|
|
100
106
|
}
|
|
101
107
|
/** Track a started span, ending any Sentry span that would otherwise be dropped without `end()`. */
|
|
102
108
|
_trackSpan(id, tracked) {
|
|
103
|
-
this.
|
|
109
|
+
this._endTracked(id);
|
|
104
110
|
if (this._spans.size >= 1e3) {
|
|
105
111
|
const oldestId = this._spans.keys()[0];
|
|
106
|
-
if (oldestId !== void 0) this.
|
|
112
|
+
if (oldestId !== void 0) this._endTracked(oldestId);
|
|
107
113
|
}
|
|
108
114
|
this._spans.set(id, tracked);
|
|
109
115
|
registerMastraSpan(id, tracked.span);
|
|
110
116
|
}
|
|
117
|
+
_endTracked(id) {
|
|
118
|
+
const tracked = this._removeTracked(id);
|
|
119
|
+
if (tracked) this._endSpan(tracked, {});
|
|
120
|
+
}
|
|
121
|
+
_endSpan(tracked, result, endTime) {
|
|
122
|
+
runGenAiSpanEnd(this._options, tracked.span, tracked.call, result);
|
|
123
|
+
tracked.span.end(endTime);
|
|
124
|
+
}
|
|
111
125
|
/** Remove a tracked span and keep the id→span registry in lockstep. */
|
|
112
126
|
_removeTracked(id) {
|
|
113
127
|
unregisterMastraSpan(id);
|
|
114
128
|
return this._spans.remove(id);
|
|
115
129
|
}
|
|
116
|
-
_onSpanUpdated(span
|
|
130
|
+
_onSpanUpdated(span) {
|
|
117
131
|
const tracked = this._spans.get(span.id);
|
|
118
|
-
if (tracked) tracked.span.setAttributes(getSpanAttributes(span, recordingOptions));
|
|
132
|
+
if (tracked) tracked.span.setAttributes(getSpanAttributes(span, tracked.recordingOptions));
|
|
119
133
|
}
|
|
120
|
-
_onSpanEnded(span
|
|
134
|
+
_onSpanEnded(span) {
|
|
121
135
|
const tracked = this._spans.get(span.id);
|
|
122
136
|
if (!tracked) {
|
|
123
137
|
DEBUG_BUILD && debug.warn(`[Mastra] no Sentry span open for ended span ${span.id} (${span.name})`);
|
|
124
138
|
return;
|
|
125
139
|
}
|
|
126
|
-
const { span: sentrySpan } = tracked;
|
|
140
|
+
const { span: sentrySpan, recordingOptions } = tracked;
|
|
127
141
|
sentrySpan.setAttributes(getSpanAttributes(span, recordingOptions));
|
|
128
142
|
sentrySpan.updateName(getSpanName(span));
|
|
129
143
|
if (MODEL_SPAN_TYPES.has(span.type)) this._rollUpToParentAgent(span);
|
|
@@ -131,9 +145,12 @@ var SentryMastraExporter = class {
|
|
|
131
145
|
code: SPAN_STATUS_ERROR,
|
|
132
146
|
message: span.errorInfo.message
|
|
133
147
|
});
|
|
148
|
+
const result = span.errorInfo ? { error: span.errorInfo } : { response: span };
|
|
134
149
|
const { evaluation } = tracked;
|
|
135
|
-
if (evaluation && !evaluation.settled)
|
|
136
|
-
|
|
150
|
+
if (evaluation && !evaluation.settled) {
|
|
151
|
+
const endTime = span.endTime ?? timestampInSeconds();
|
|
152
|
+
evaluation.end = () => this._endSpan(tracked, result, endTime);
|
|
153
|
+
} else this._endSpan(tracked, result, span.endTime);
|
|
137
154
|
this._removeTracked(span.id);
|
|
138
155
|
}
|
|
139
156
|
/** Copy model/usage onto the parent agent so the AI Agents view shows totals. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["sentryFlush"],"sources":["../../../../src/ai/mastra/index.ts"],"sourcesContent":["import type { Span } from '@sentry/core';\nimport {\n debug,\n flush as sentryFlush,\n getActiveSpan,\n getClient,\n LRUMap,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n timestampInSeconds,\n} from '@sentry/core';\nimport { GEN_AI_RESPONSE_MODEL, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type { GenAiOptions } from '../core/utils';\nimport { resolveAIRecordingOptions } from '../core/utils';\nimport {\n getOperation,\n getSpanAttributes,\n getSpanName,\n getUsageAttributes,\n isExportedSpanType,\n mergeUsageAttributes,\n type AttributeRecordingOptions,\n type SpanAttributes,\n} from './utils';\nimport {\n AGENT_SPAN_TYPES,\n MASTRA_EXPORTER_BRAND,\n MASTRA_EXPORTER_NAME,\n MASTRA_ORIGIN,\n MAX_TRACKED_MASTRA_SPANS,\n MODEL_SPAN_TYPES,\n} from './constants';\nimport type { ClassifierEvaluationCall } from './classifier-evaluation';\nimport { takeStartingClassifierEvaluation } from './classifier-evaluation';\nimport { registerMastraSpan, unregisterMastraSpan } from './span-registry';\nimport type {\n MastraExportedSpan,\n MastraExporterInitOptions,\n MastraObservabilityExporter,\n MastraSpanOutputProcessor,\n MastraSpanType,\n MastraTracingEvent,\n} from './types';\n\nexport type MastraExporterOptions = GenAiOptions;\n\ninterface TrackedSpan {\n span: Span;\n spanType: MastraSpanType;\n usage: SpanAttributes;\n evaluation?: ClassifierEvaluationCall;\n}\n\nconst FLUSH_TIMEOUT_MS = 2000;\n\n/** Bound on the skipped-span parent walk; a cyclic chain from Mastra would otherwise hang the process. */\nconst MAX_PARENT_WALK_DEPTH = 100;\n\n/**\n * Mastra `ObservabilityExporter` that turns tracing events into Sentry spans.\n *\n * Never calls `Sentry.init()` / `Sentry.close()` — the community `@mastra/sentry` package does both\n * and replaces the app's client. No `@mastra/*` or `node:` imports.\n */\nexport class SentryMastraExporter implements MastraObservabilityExporter {\n public name = MASTRA_EXPORTER_NAME;\n\n public readonly [MASTRA_EXPORTER_BRAND] = true;\n\n private readonly _spans = new LRUMap<string, TrackedSpan>(MAX_TRACKED_MASTRA_SPANS);\n /**\n * Dropped span id -> parent id, for re-parenting descendants. A dropped span with no parent maps to\n * its own id: `LRUMap.remove` only deletes truthy values, so an empty-string sentinel would never be\n * evicted and would eventually fill the map, while a self-reference can never be a real parent id.\n */\n private readonly _skipped = new LRUMap<string, string>(MAX_TRACKED_MASTRA_SPANS);\n private readonly _options: MastraExporterOptions;\n private _spanOutputProcessors: MastraSpanOutputProcessor[] = [];\n\n public constructor(options: MastraExporterOptions = {}) {\n this._options = options;\n }\n\n /** Called by Mastra with the config of the observability instance this exporter belongs to. */\n public init(options: MastraExporterInitOptions): void {\n this._spanOutputProcessors = options.config?.spanOutputProcessors ?? [];\n }\n\n /** Mastra's interface is async; the work is synchronous. */\n public async exportTracingEvent(event: MastraTracingEvent): Promise<void> {\n if (!getClient()) {\n return;\n }\n\n try {\n this._handleEvent(event);\n } catch (error) {\n DEBUG_BUILD && debug.error('[Mastra] failed to export tracing event', error);\n }\n }\n\n /** Flush without closing the client — the app still owns it. */\n public async flush(): Promise<void> {\n await sentryFlush(FLUSH_TIMEOUT_MS);\n }\n\n /** End open spans, then flush. Does not close the Sentry client. */\n public async shutdown(): Promise<void> {\n for (const id of this._spans.keys()) {\n unregisterMastraSpan(id);\n }\n for (const { span } of this._spans.values()) {\n span.end();\n }\n this._spans.clear();\n this._skipped.clear();\n await this.flush();\n }\n\n private _handleEvent(event: MastraTracingEvent): void {\n const span = event.exportedSpan;\n\n if (span.isEvent) {\n return;\n }\n\n // Unmapped types are recorded so children re-parent onto a surviving ancestor.\n if (!isExportedSpanType(span.type)) {\n if (event.type === 'span_started') {\n this._skipped.set(span.id, span.parentSpanId ?? span.id);\n } else if (event.type === 'span_ended') {\n this._skipped.remove(span.id);\n }\n return;\n }\n\n // Per event: the exporter can be constructed before `Sentry.init()`, when `dataCollection.genAI` does not exist yet.\n const recordingOptions = resolveAIRecordingOptions(this._options);\n switch (event.type) {\n case 'span_started':\n this._onSpanStarted(span, recordingOptions);\n break;\n case 'span_updated':\n this._onSpanUpdated(span, recordingOptions);\n break;\n case 'span_ended':\n this._onSpanEnded(span, recordingOptions);\n break;\n }\n }\n\n private _onSpanStarted(span: MastraExportedSpan, recordingOptions: AttributeRecordingOptions): void {\n const parentId = this._resolveParentId(span.parentSpanId);\n const parentSpan = parentId ? this._spans.get(parentId)?.span : undefined;\n const activeSpan = getActiveSpan();\n\n const sentrySpan = startInactiveSpan({\n name: getSpanName(span),\n startTime: span.startTime,\n // Prefer the Mastra parent so the tree stays together; else the active request span.\n parentSpan: parentSpan ?? activeSpan,\n attributes: {\n ...getSpanAttributes(span, recordingOptions),\n [SENTRY_OP]: getOperation(span.type)?.op,\n [SENTRY_ORIGIN]: MASTRA_ORIGIN,\n },\n });\n\n const evaluation = span.type === 'classifier_evaluation' ? takeStartingClassifierEvaluation() : undefined;\n if (evaluation) {\n Object.assign(evaluation, {\n span: sentrySpan,\n mastraSpan: span,\n spanOutputProcessors: this._spanOutputProcessors,\n recordInputs: recordingOptions.recordInputs,\n recordOutputs: recordingOptions.recordOutputs,\n });\n }\n\n this._trackSpan(span.id, { span: sentrySpan, spanType: span.type, usage: {}, evaluation });\n }\n\n /** Track a started span, ending any Sentry span that would otherwise be dropped without `end()`. */\n private _trackSpan(id: string, tracked: TrackedSpan): void {\n // A duplicate `span_started` would otherwise overwrite the entry and leak its Sentry span.\n this._removeTracked(id)?.span.end();\n\n // `LRUMap.set` evicts the oldest entry once the map is full, dropping that span without ending it.\n if (this._spans.size >= MAX_TRACKED_MASTRA_SPANS) {\n const oldestId = this._spans.keys()[0];\n if (oldestId !== undefined) {\n this._removeTracked(oldestId)?.span.end();\n }\n }\n\n this._spans.set(id, tracked);\n // Let the `executeWithContext` channel subscriber find this Sentry span by Mastra span id.\n registerMastraSpan(id, tracked.span);\n }\n\n /** Remove a tracked span and keep the id→span registry in lockstep. */\n private _removeTracked(id: string): TrackedSpan | undefined {\n unregisterMastraSpan(id);\n return this._spans.remove(id);\n }\n\n private _onSpanUpdated(span: MastraExportedSpan, recordingOptions: AttributeRecordingOptions): void {\n const tracked = this._spans.get(span.id);\n if (tracked) {\n tracked.span.setAttributes(getSpanAttributes(span, recordingOptions));\n }\n }\n\n private _onSpanEnded(span: MastraExportedSpan, recordingOptions: AttributeRecordingOptions): void {\n const tracked = this._spans.get(span.id);\n if (!tracked) {\n DEBUG_BUILD && debug.warn(`[Mastra] no Sentry span open for ended span ${span.id} (${span.name})`);\n return;\n }\n\n const { span: sentrySpan } = tracked;\n sentrySpan.setAttributes(getSpanAttributes(span, recordingOptions));\n sentrySpan.updateName(getSpanName(span));\n\n if (MODEL_SPAN_TYPES.has(span.type)) {\n this._rollUpToParentAgent(span);\n }\n\n if (span.errorInfo) {\n // Status only — capturing here would duplicate the app's own report with a worse stack.\n sentrySpan.setStatus({ code: SPAN_STATUS_ERROR, message: span.errorInfo.message });\n }\n\n const { evaluation } = tracked;\n if (evaluation && !evaluation.settled) {\n // The integration adds the call's input and answers once `evaluate()` settles, then ends the span.\n evaluation.endTime = span.endTime ?? timestampInSeconds();\n } else {\n sentrySpan.end(span.endTime);\n }\n this._removeTracked(span.id);\n }\n\n /** Copy model/usage onto the parent agent so the AI Agents view shows totals. */\n private _rollUpToParentAgent(span: MastraExportedSpan): void {\n const parentId = this._resolveParentId(span.parentSpanId);\n const parent = parentId ? this._spans.get(parentId) : undefined;\n if (!parent || !AGENT_SPAN_TYPES.has(parent.spanType)) {\n return;\n }\n\n const attrs = span.attributes ?? {};\n const rolled = mergeUsageAttributes(parent.usage, getUsageAttributes(attrs.usage));\n parent.usage = rolled;\n const model = attrs.responseModel ?? attrs.model;\n if (model !== undefined) {\n rolled[GEN_AI_RESPONSE_MODEL] = model;\n }\n parent.span.setAttributes(rolled);\n }\n\n /** Nearest exported ancestor of a dropped span. */\n private _resolveParentId(parentSpanId: string | undefined): string | undefined {\n let current = parentSpanId;\n for (let depth = 0; current; depth++) {\n const parentOfSkipped = this._skipped.get(current);\n if (parentOfSkipped === undefined) {\n return current;\n }\n if (depth >= MAX_PARENT_WALK_DEPTH) {\n DEBUG_BUILD && debug.warn('[Mastra] gave up walking a parent chain that is too deep or cyclic');\n return undefined;\n }\n // Self-reference marks a dropped span with no parent; stop and fall back to the active span.\n current = parentOfSkipped === current ? undefined : parentOfSkipped;\n }\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;AAsDA,MAAM,mBAAmB;;AAGzB,MAAM,wBAAwB;;;;;;;AAQ9B,IAAa,uBAAb,MAAyE;CAehE,YAAY,UAAiC,CAAC,GAAG;EAdxD,KAAO,OAAO;EAEd,KAAiB,yBAAyB;EAE1C,KAAiB,SAAS,IAAI,OAA4B,wBAAwB;EAMlF,KAAiB,WAAW,IAAI,OAAuB,wBAAwB;EAE/E,KAAQ,wBAAqD,CAAC;E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{ Span, SpanTimeInput } from '@sentry/core';\nimport {\n debug,\n flush as sentryFlush,\n getActiveSpan,\n getClient,\n LRUMap,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n timestampInSeconds,\n} from '@sentry/core';\nimport {\n GEN_AI_CONVERSATION_ID,\n GEN_AI_RESPONSE_MODEL,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type { GenAiSpanHooks, GenAiSpanResult } from '../core/span-hooks';\nimport { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { GenAiCallOptions } from '../core/utils';\nimport { resolveGenAiCallRecording } from '../core/utils';\nimport {\n getOperation,\n getSpanAttributes,\n getSpanName,\n getUsageAttributes,\n isExportedSpanType,\n mergeUsageAttributes,\n type AttributeRecordingOptions,\n type SpanAttributes,\n} from './utils';\nimport {\n AGENT_SPAN_TYPES,\n MASTRA_EXPORTER_BRAND,\n MASTRA_EXPORTER_NAME,\n MASTRA_ORIGIN,\n MAX_TRACKED_MASTRA_SPANS,\n MODEL_SPAN_TYPES,\n} from './constants';\nimport type { ClassifierEvaluationCall } from './classifier-evaluation';\nimport { takeStartingClassifierEvaluation } from './classifier-evaluation';\nimport { registerMastraSpan, unregisterMastraSpan } from './span-registry';\nimport type {\n MastraExportedSpan,\n MastraExporterInitOptions,\n MastraObservabilityExporter,\n MastraSpanOutputProcessor,\n MastraSpanType,\n MastraTracingEvent,\n} from './types';\n\n/** The span that `recordInputs`/`recordOutputs` decide on, and that the span hooks get. */\nexport interface MastraCallInfo {\n /** The Mastra span as exported, when it starts. */\n span: MastraExportedSpan;\n}\n\n/**\n * `recordInputs`/`recordOutputs` and `onSpanStart` run when the exporter receives the start of a Mastra\n * span, and `onSpanEnd` when it receives its end, not in the async context of the code that started it.\n * `onSpanEnd` gets the Mastra span as exported when it ends, with its output, unless it failed or the\n * exporter ended it early, on shutdown or when too many spans are open at once.\n */\nexport type MastraExporterOptions = GenAiCallOptions<MastraCallInfo> &\n GenAiSpanHooks<MastraCallInfo, MastraExportedSpan>;\n\ninterface TrackedSpan {\n span: Span;\n call: MastraCallInfo;\n spanType: MastraSpanType;\n usage: SpanAttributes;\n recordingOptions: AttributeRecordingOptions;\n evaluation?: ClassifierEvaluationCall;\n}\n\nconst FLUSH_TIMEOUT_MS = 2000;\n\n/** Bound on the skipped-span parent walk; a cyclic chain from Mastra would otherwise hang the process. */\nconst MAX_PARENT_WALK_DEPTH = 100;\n\n/**\n * Mastra `ObservabilityExporter` that turns tracing events into Sentry spans.\n *\n * Never calls `Sentry.init()` / `Sentry.close()` — the community `@mastra/sentry` package does both\n * and replaces the app's client. No `@mastra/*` or `node:` imports.\n */\nexport class SentryMastraExporter implements MastraObservabilityExporter {\n public name = MASTRA_EXPORTER_NAME;\n\n public readonly [MASTRA_EXPORTER_BRAND] = true;\n\n private readonly _spans = new LRUMap<string, TrackedSpan>(MAX_TRACKED_MASTRA_SPANS);\n /**\n * Dropped span id -> parent id, for re-parenting descendants. A dropped span with no parent maps to\n * its own id: `LRUMap.remove` only deletes truthy values, so an empty-string sentinel would never be\n * evicted and would eventually fill the map, while a self-reference can never be a real parent id.\n */\n private readonly _skipped = new LRUMap<string, string>(MAX_TRACKED_MASTRA_SPANS);\n private readonly _options: MastraExporterOptions;\n private _spanOutputProcessors: MastraSpanOutputProcessor[] = [];\n\n public constructor(options: MastraExporterOptions = {}) {\n this._options = options;\n }\n\n /** Called by Mastra with the config of the observability instance this exporter belongs to. */\n public init(options: MastraExporterInitOptions): void {\n this._spanOutputProcessors = options.config?.spanOutputProcessors ?? [];\n }\n\n /** Mastra's interface is async; the work is synchronous. */\n public async exportTracingEvent(event: MastraTracingEvent): Promise<void> {\n if (!getClient()) {\n return;\n }\n\n try {\n this._handleEvent(event);\n } catch (error) {\n DEBUG_BUILD && debug.error('[Mastra] failed to export tracing event', error);\n }\n }\n\n /** Flush without closing the client — the app still owns it. */\n public async flush(): Promise<void> {\n await sentryFlush(FLUSH_TIMEOUT_MS);\n }\n\n /** End open spans, then flush. Does not close the Sentry client. */\n public async shutdown(): Promise<void> {\n for (const id of this._spans.keys()) {\n unregisterMastraSpan(id);\n }\n for (const tracked of this._spans.values()) {\n this._endSpan(tracked, {});\n }\n this._spans.clear();\n this._skipped.clear();\n await this.flush();\n }\n\n private _handleEvent(event: MastraTracingEvent): void {\n const span = event.exportedSpan;\n\n if (span.isEvent) {\n return;\n }\n\n // Unmapped types are recorded so children re-parent onto a surviving ancestor.\n if (!isExportedSpanType(span.type)) {\n if (event.type === 'span_started') {\n this._skipped.set(span.id, span.parentSpanId ?? span.id);\n } else if (event.type === 'span_ended') {\n this._skipped.remove(span.id);\n }\n return;\n }\n\n switch (event.type) {\n case 'span_started':\n this._onSpanStarted(span);\n break;\n case 'span_updated':\n this._onSpanUpdated(span);\n break;\n case 'span_ended':\n this._onSpanEnded(span);\n break;\n }\n }\n\n private _onSpanStarted(span: MastraExportedSpan): void {\n // Per span, not in the constructor: the exporter can be constructed before `Sentry.init()`, when\n // `dataCollection.genAI` does not exist yet.\n const call: MastraCallInfo = { span };\n const recordingOptions = resolveGenAiCallRecording(this._options, call);\n const parentId = this._resolveParentId(span.parentSpanId);\n const parentSpan = parentId ? this._spans.get(parentId)?.span : undefined;\n const activeSpan = getActiveSpan();\n\n const sentrySpan = startInactiveSpan({\n name: getSpanName(span),\n startTime: span.startTime,\n // Prefer the Mastra parent so the tree stays together; else the active request span.\n parentSpan: parentSpan ?? activeSpan,\n attributes: {\n ...getSpanAttributes(span, recordingOptions),\n // Only on start, so the id from `Sentry.setConversationId()`, applied on `spanStart`, is kept.\n [GEN_AI_CONVERSATION_ID]: span.attributes?.conversationId ?? span.metadata?.threadId,\n [SENTRY_OP]: getOperation(span.type)?.op,\n [SENTRY_ORIGIN]: MASTRA_ORIGIN,\n },\n });\n runGenAiSpanStart(this._options, sentrySpan, call);\n\n const evaluation = span.type === 'classifier_evaluation' ? takeStartingClassifierEvaluation() : undefined;\n if (evaluation) {\n Object.assign(evaluation, {\n span: sentrySpan,\n mastraSpan: span,\n spanOutputProcessors: this._spanOutputProcessors,\n recordInputs: recordingOptions.recordInputs,\n recordOutputs: recordingOptions.recordOutputs,\n });\n }\n\n this._trackSpan(span.id, { span: sentrySpan, call, spanType: span.type, usage: {}, recordingOptions, evaluation });\n }\n\n /** Track a started span, ending any Sentry span that would otherwise be dropped without `end()`. */\n private _trackSpan(id: string, tracked: TrackedSpan): void {\n // A duplicate `span_started` would otherwise overwrite the entry and leak its Sentry span.\n this._endTracked(id);\n\n // `LRUMap.set` evicts the oldest entry once the map is full, dropping that span without ending it.\n if (this._spans.size >= MAX_TRACKED_MASTRA_SPANS) {\n const oldestId = this._spans.keys()[0];\n if (oldestId !== undefined) {\n this._endTracked(oldestId);\n }\n }\n\n this._spans.set(id, tracked);\n // Let the `executeWithContext` channel subscriber find this Sentry span by Mastra span id.\n registerMastraSpan(id, tracked.span);\n }\n\n private _endTracked(id: string): void {\n const tracked = this._removeTracked(id);\n if (tracked) {\n this._endSpan(tracked, {});\n }\n }\n\n private _endSpan(tracked: TrackedSpan, result: GenAiSpanResult<MastraExportedSpan>, endTime?: SpanTimeInput): void {\n runGenAiSpanEnd(this._options, tracked.span, tracked.call, result);\n tracked.span.end(endTime);\n }\n\n /** Remove a tracked span and keep the id→span registry in lockstep. */\n private _removeTracked(id: string): TrackedSpan | undefined {\n unregisterMastraSpan(id);\n return this._spans.remove(id);\n }\n\n private _onSpanUpdated(span: MastraExportedSpan): void {\n const tracked = this._spans.get(span.id);\n if (tracked) {\n tracked.span.setAttributes(getSpanAttributes(span, tracked.recordingOptions));\n }\n }\n\n private _onSpanEnded(span: MastraExportedSpan): void {\n const tracked = this._spans.get(span.id);\n if (!tracked) {\n DEBUG_BUILD && debug.warn(`[Mastra] no Sentry span open for ended span ${span.id} (${span.name})`);\n return;\n }\n\n const { span: sentrySpan, recordingOptions } = tracked;\n sentrySpan.setAttributes(getSpanAttributes(span, recordingOptions));\n sentrySpan.updateName(getSpanName(span));\n\n if (MODEL_SPAN_TYPES.has(span.type)) {\n this._rollUpToParentAgent(span);\n }\n\n if (span.errorInfo) {\n // Status only — capturing here would duplicate the app's own report with a worse stack.\n sentrySpan.setStatus({ code: SPAN_STATUS_ERROR, message: span.errorInfo.message });\n }\n\n const result = span.errorInfo ? { error: span.errorInfo } : { response: span };\n const { evaluation } = tracked;\n if (evaluation && !evaluation.settled) {\n // The integration adds the call's input and answers once `evaluate()` settles, then ends the span.\n const endTime = span.endTime ?? timestampInSeconds();\n evaluation.end = () => this._endSpan(tracked, result, endTime);\n } else {\n this._endSpan(tracked, result, span.endTime);\n }\n this._removeTracked(span.id);\n }\n\n /** Copy model/usage onto the parent agent so the AI Agents view shows totals. */\n private _rollUpToParentAgent(span: MastraExportedSpan): void {\n const parentId = this._resolveParentId(span.parentSpanId);\n const parent = parentId ? this._spans.get(parentId) : undefined;\n if (!parent || !AGENT_SPAN_TYPES.has(parent.spanType)) {\n return;\n }\n\n const attrs = span.attributes ?? {};\n const rolled = mergeUsageAttributes(parent.usage, getUsageAttributes(attrs.usage));\n parent.usage = rolled;\n const model = attrs.responseModel ?? attrs.model;\n if (model !== undefined) {\n rolled[GEN_AI_RESPONSE_MODEL] = model;\n }\n parent.span.setAttributes(rolled);\n }\n\n /** Nearest exported ancestor of a dropped span. */\n private _resolveParentId(parentSpanId: string | undefined): string | undefined {\n let current = parentSpanId;\n for (let depth = 0; current; depth++) {\n const parentOfSkipped = this._skipped.get(current);\n if (parentOfSkipped === undefined) {\n return current;\n }\n if (depth >= MAX_PARENT_WALK_DEPTH) {\n DEBUG_BUILD && debug.warn('[Mastra] gave up walking a parent chain that is too deep or cyclic');\n return undefined;\n }\n // Self-reference marks a dropped span with no parent; stop and fall back to the active span.\n current = parentOfSkipped === current ? undefined : parentOfSkipped;\n }\n return undefined;\n }\n}\n"],"mappings":";;;;;;;;;;AA4EA,MAAM,mBAAmB;;AAGzB,MAAM,wBAAwB;;;;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,IAAI,CAAC,UAAU,CAAC,iBAAiB,IAAI,OAAO,QAAQ,GAClD;EAGF,MAAM,QAAQ,KAAK,cAAc,CAAC;EAClC,MAAM,SAAS,qBAAqB,OAAO,OAAO,mBAAmB,MAAM,KAAK,CAAC;EACjF,OAAO,QAAQ;EACf,MAAM,QAAQ,MAAM,iBAAiB,MAAM;EAC3C,IAAI,UAAU,KAAA,GACZ,OAAO,yBAAyB;EAElC,OAAO,KAAK,cAAc,MAAM;CAClC;;CAGQ,iBAAiB,cAAsD;EAC7E,IAAI,UAAU;EACd,KAAK,IAAI,QAAQ,GAAG,SAAS,SAAS;GACpC,MAAM,kBAAkB,KAAK,SAAS,IAAI,OAAO;GACjD,IAAI,oBAAoB,KAAA,GACtB,OAAO;GAET,IAAI,SAAS,uBAAuB;IAClC,eAAe,MAAM,KAAK,oEAAoE;IAC9F;GACF;GAEA,UAAU,oBAAoB,UAAU,KAAA,IAAY;EACtD;CAEF;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { AGENT_SPAN_TYPES, MODEL_SPAN_TYPES, SPAN_TYPE_OPS, TOOL_SPAN_TYPES } from "./constants.js";
|
|
2
|
-
import { ERROR_TYPE, GEN_AI_AGENT_NAME,
|
|
2
|
+
import { ERROR_TYPE, GEN_AI_AGENT_NAME, GEN_AI_INPUT_MESSAGES, GEN_AI_OPERATION_NAME, GEN_AI_OUTPUT_MESSAGES, GEN_AI_PIPELINE_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_SEED, GEN_AI_REQUEST_STOP_SEQUENCES, GEN_AI_REQUEST_TEMPERATURE, GEN_AI_REQUEST_TOP_K, GEN_AI_REQUEST_TOP_P, GEN_AI_RESPONSE_FINISH_REASONS, GEN_AI_RESPONSE_ID, GEN_AI_RESPONSE_MODEL, GEN_AI_RESPONSE_STREAMING, GEN_AI_RESPONSE_TEXT, GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK, GEN_AI_SYSTEM_INSTRUCTIONS, GEN_AI_TOOL_CALL_ARGUMENTS, GEN_AI_TOOL_CALL_RESULT, GEN_AI_TOOL_DEFINITIONS, GEN_AI_TOOL_DESCRIPTION, GEN_AI_TOOL_NAME, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, GEN_AI_USAGE_INPUT_TOKENS, GEN_AI_USAGE_OUTPUT_TOKENS, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, GEN_AI_USAGE_TOTAL_TOKENS } from "@sentry/conventions/attributes";
|
|
3
3
|
import { stringify } from "@sentry/core";
|
|
4
4
|
// src/ai/mastra/utils.ts
|
|
5
5
|
function isExportedSpanType(spanType) {
|
|
@@ -69,10 +69,7 @@ function mergeUsageAttributes(existing, incoming) {
|
|
|
69
69
|
/** Convention attributes only. Called on start and end — Mastra fills fields progressively. */
|
|
70
70
|
function getSpanAttributes(span, options) {
|
|
71
71
|
const operationName = getOperation(span.type)?.operationName;
|
|
72
|
-
const attributes = {
|
|
73
|
-
[GEN_AI_OPERATION_NAME]: operationName,
|
|
74
|
-
[GEN_AI_CONVERSATION_ID]: span.attributes?.conversationId ?? span.metadata?.threadId
|
|
75
|
-
};
|
|
72
|
+
const attributes = { [GEN_AI_OPERATION_NAME]: operationName };
|
|
76
73
|
if (AGENT_SPAN_TYPES.has(span.type)) addAgentAttributes(attributes, span, options);
|
|
77
74
|
if (MODEL_SPAN_TYPES.has(span.type) || span.type === "rag_embedding") addModelAttributes(attributes, span, options);
|
|
78
75
|
if (TOOL_SPAN_TYPES.has(span.type)) addToolAttributes(attributes, span, options);
|
|
@@ -103,6 +100,7 @@ function addModelAttributes(attributes, span, options) {
|
|
|
103
100
|
attributes[GEN_AI_RESPONSE_MODEL] = attrs.responseModel;
|
|
104
101
|
attributes[GEN_AI_RESPONSE_ID] = attrs.responseId;
|
|
105
102
|
attributes[GEN_AI_RESPONSE_STREAMING] = attrs.streaming;
|
|
103
|
+
attributes[GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK] = attrs.completionStartTime ? (attrs.completionStartTime.getTime() - span.startTime.getTime()) / 1e3 : void 0;
|
|
106
104
|
attributes[GEN_AI_RESPONSE_FINISH_REASONS] = attrs.finishReason ? JSON.stringify([attrs.finishReason]) : void 0;
|
|
107
105
|
attributes[GEN_AI_AGENT_NAME] = span.entityName;
|
|
108
106
|
attributes[GEN_AI_REQUEST_TEMPERATURE] = parameters.temperature;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":[],"sources":["../../../../src/ai/mastra/utils.ts"],"sourcesContent":["import type { SpanAttributeValue } from '@sentry/core';\nimport { stringify } from '@sentry/core';\nimport {\n ERROR_TYPE,\n GEN_AI_AGENT_NAME,\n GEN_AI_CONVERSATION_ID,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_PIPELINE_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_SEED,\n GEN_AI_REQUEST_STOP_SEQUENCES,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_K,\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_STREAMING,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DEFINITIONS,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n} from '@sentry/conventions/attributes';\nimport { AGENT_SPAN_TYPES, MODEL_SPAN_TYPES, SPAN_TYPE_OPS, TOOL_SPAN_TYPES } from './constants';\nimport type { MastraExportedSpan, MastraSpanType, MastraUsageStats } from './types';\n\nexport interface AttributeRecordingOptions {\n recordInputs: boolean;\n recordOutputs: boolean;\n}\n\nexport type SpanAttributes = Record<string, SpanAttributeValue | undefined>;\n\nexport function isExportedSpanType(spanType: MastraSpanType): boolean {\n // `in` would also match inherited keys like `constructor` or `toString`.\n return Object.prototype.hasOwnProperty.call(SPAN_TYPE_OPS, spanType);\n}\n\nexport function getOperation(spanType: MastraSpanType): { op: string; operationName: string } | undefined {\n return SPAN_TYPE_OPS[spanType];\n}\n\n/**\n * `{operation} {identifier}` per the gen_ai name templates. Mastra's own span name is never used.\n * https://conventions.sentry.dev/names/\n */\nexport function getSpanName(span: MastraExportedSpan): string {\n const operationName = getOperation(span.type)?.operationName ?? span.type;\n const identifier = getSpanIdentifier(span);\n\n return identifier ? `${operationName} ${identifier}` : operationName;\n}\n\nfunction getSpanIdentifier(span: MastraExportedSpan): string | undefined {\n if (span.type === 'classifier_evaluation') {\n return span.attributes?.modelId;\n }\n if (MODEL_SPAN_TYPES.has(span.type) || span.type === 'rag_embedding') {\n return span.attributes?.model;\n }\n return span.entityName ?? span.entityId;\n}\n\nfunction serialize(value: unknown): string | undefined {\n if (value === undefined || value === null) {\n return undefined;\n }\n return typeof value === 'string' ? value : stringify(value);\n}\n\nfunction positive(value: number | undefined): number | undefined {\n return value !== undefined && value > 0 ? value : undefined;\n}\n\nexport function getUsageAttributes(usage: MastraUsageStats | undefined): SpanAttributes {\n if (!usage) {\n return {};\n }\n\n const inputTokens = usage.inputTokens;\n const outputTokens = usage.outputTokens;\n // Mastra only reports `totalTokens` for some providers, so derive it when both halves are known.\n const totalTokens =\n usage.totalTokens ??\n (inputTokens !== undefined || outputTokens !== undefined ? (inputTokens ?? 0) + (outputTokens ?? 0) : undefined);\n\n return {\n [GEN_AI_USAGE_INPUT_TOKENS]: inputTokens,\n [GEN_AI_USAGE_OUTPUT_TOKENS]: outputTokens,\n [GEN_AI_USAGE_TOTAL_TOKENS]: totalTokens,\n // Mastra reports these as 0 for providers that don't cache or reason.\n [GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: positive(usage.inputDetails?.cacheRead),\n [GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: positive(usage.inputDetails?.cacheWrite),\n [GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]: positive(usage.outputDetails?.reasoning),\n };\n}\n\nconst USAGE_ATTRIBUTE_KEYS = [\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n] as const;\n\nfunction addTokenCounts(\n left: SpanAttributeValue | undefined,\n right: SpanAttributeValue | undefined,\n): number | undefined {\n const a = typeof left === 'number' ? left : undefined;\n const b = typeof right === 'number' ? right : undefined;\n if (a === undefined && b === undefined) {\n return undefined;\n }\n return (a ?? 0) + (b ?? 0);\n}\n\n/** Sum usage across generations. `setAttributes(undefined)` would drop the previous total. */\nexport function mergeUsageAttributes(existing: SpanAttributes, incoming: SpanAttributes): SpanAttributes {\n const merged: SpanAttributes = {};\n for (const key of USAGE_ATTRIBUTE_KEYS) {\n const value = addTokenCounts(existing[key], incoming[key]);\n if (value !== undefined) {\n merged[key] = value;\n }\n }\n return merged;\n}\n\n/** Convention attributes only. Called on start and end — Mastra fills fields progressively. */\nexport function getSpanAttributes(span: MastraExportedSpan, options: AttributeRecordingOptions): SpanAttributes {\n const operationName = getOperation(span.type)?.operationName;\n\n const attributes: SpanAttributes = {\n [GEN_AI_OPERATION_NAME]: operationName,\n [GEN_AI_CONVERSATION_ID]: span.attributes?.conversationId ?? span.metadata?.threadId,\n };\n\n if (AGENT_SPAN_TYPES.has(span.type)) {\n addAgentAttributes(attributes, span, options);\n }\n\n if (MODEL_SPAN_TYPES.has(span.type) || span.type === 'rag_embedding') {\n addModelAttributes(attributes, span, options);\n }\n\n if (TOOL_SPAN_TYPES.has(span.type)) {\n addToolAttributes(attributes, span, options);\n }\n\n if (span.type === 'classifier_evaluation') {\n addEvaluationAttributes(attributes, span);\n }\n\n if (span.errorInfo) {\n attributes[ERROR_TYPE] = span.errorInfo.name ?? span.errorInfo.id;\n }\n\n return attributes;\n}\n\nfunction addAgentAttributes(\n attributes: SpanAttributes,\n span: MastraExportedSpan,\n options: AttributeRecordingOptions,\n): void {\n const attrs = span.attributes ?? {};\n const name = span.entityName ?? span.entityId;\n\n attributes[GEN_AI_AGENT_NAME] = name;\n attributes[GEN_AI_PIPELINE_NAME] = name;\n attributes[GEN_AI_TOOL_DEFINITIONS] = serialize(attrs.availableTools);\n\n if (options.recordInputs) {\n // `prompt` is Mastra's legacy alias for the system prompt.\n attributes[GEN_AI_SYSTEM_INSTRUCTIONS] = attrs.instructions ?? attrs.prompt;\n attributes[GEN_AI_INPUT_MESSAGES] = serialize(span.input);\n }\n if (options.recordOutputs) {\n attributes[GEN_AI_OUTPUT_MESSAGES] = serialize(span.output);\n // oxlint-disable-next-line typescript/no-deprecated -- still emitted by the other AI integrations\n attributes[GEN_AI_RESPONSE_TEXT] = responseText(span.output);\n }\n}\n\nfunction addModelAttributes(\n attributes: SpanAttributes,\n span: MastraExportedSpan,\n options: AttributeRecordingOptions,\n): void {\n const attrs = span.attributes ?? {};\n const parameters = attrs.parameters ?? {};\n\n attributes[GEN_AI_REQUEST_MODEL] = attrs.model;\n attributes[GEN_AI_PROVIDER_NAME] = attrs.provider;\n attributes[GEN_AI_RESPONSE_MODEL] = attrs.responseModel;\n attributes[GEN_AI_RESPONSE_ID] = attrs.responseId;\n attributes[GEN_AI_RESPONSE_STREAMING] = attrs.streaming;\n attributes[GEN_AI_RESPONSE_FINISH_REASONS] = attrs.finishReason ? JSON.stringify([attrs.finishReason]) : undefined;\n attributes[GEN_AI_AGENT_NAME] = span.entityName;\n\n attributes[GEN_AI_REQUEST_TEMPERATURE] = parameters.temperature;\n attributes[GEN_AI_REQUEST_MAX_TOKENS] = parameters.maxOutputTokens;\n attributes[GEN_AI_REQUEST_TOP_P] = parameters.topP;\n attributes[GEN_AI_REQUEST_TOP_K] = parameters.topK;\n attributes[GEN_AI_REQUEST_PRESENCE_PENALTY] = parameters.presencePenalty;\n attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY] = parameters.frequencyPenalty;\n attributes[GEN_AI_REQUEST_SEED] = parameters.seed;\n attributes[GEN_AI_REQUEST_STOP_SEQUENCES] = parameters.stopSequences;\n\n Object.assign(attributes, getUsageAttributes(attrs.usage));\n\n if (options.recordInputs) {\n attributes[GEN_AI_INPUT_MESSAGES] = serialize(span.input);\n }\n if (options.recordOutputs) {\n attributes[GEN_AI_OUTPUT_MESSAGES] = serialize(span.output);\n // oxlint-disable-next-line typescript/no-deprecated -- still emitted by the other AI integrations\n attributes[GEN_AI_RESPONSE_TEXT] = responseText(span.output);\n }\n}\n\nfunction addToolAttributes(\n attributes: SpanAttributes,\n span: MastraExportedSpan,\n options: AttributeRecordingOptions,\n): void {\n const attrs = span.attributes ?? {};\n\n attributes[GEN_AI_TOOL_NAME] = span.entityName ?? span.entityId;\n attributes[GEN_AI_TOOL_DESCRIPTION] = attrs.toolDescription;\n\n if (options.recordInputs) {\n attributes[GEN_AI_TOOL_CALL_ARGUMENTS] = serialize(span.input);\n }\n if (options.recordOutputs) {\n attributes[GEN_AI_TOOL_CALL_RESULT] = serialize(span.output);\n }\n}\n\n/** Mastra's `Classifier` sets no input or output on this span, so only the model and usage are known. */\nfunction addEvaluationAttributes(attributes: SpanAttributes, span: MastraExportedSpan): void {\n const attrs = span.attributes ?? {};\n\n attributes[GEN_AI_REQUEST_MODEL] = attrs.modelId;\n attributes[GEN_AI_PROVIDER_NAME] = attrs.provider;\n Object.assign(attributes, getUsageAttributes(attrs.usage));\n}\n\nfunction responseText(output: unknown): string | undefined {\n if (typeof output === 'string') {\n return output;\n }\n if (output && typeof output === 'object' && 'text' in output && typeof output.text === 'string') {\n return output.text;\n }\n return undefined;\n}\n"],"mappings":";;;;AAgDA,SAAgB,mBAAmB,UAAmC;CAEpE,OAAO,OAAO,UAAU,eAAe,KAAK,eAAe,QAAQ;AACrE;AAEA,SAAgB,aAAa,UAA6E;CACxG,OAAO,cAAc;AACvB;;;;;AAMA,SAAgB,YAAY,MAAkC;CAC5D,MAAM,gBAAgB,aAAa,KAAK,IAAI,CAAC,EAAE,iBAAiB,KAAK;CACrE,MAAM,aAAa,kBAAkB,IAAI;CAEzC,OAAO,aAAa,GAAG,cAAc,GAAG,eAAe;AACzD;AAEA,SAAS,kBAAkB,MAA8C;CACvE,IAAI,KAAK,SAAS,yBAChB,OAAO,KAAK,YAAY;CAE1B,IAAI,iBAAiB,IAAI,KAAK,IAAI,KAAK,KAAK,SAAS,iBACnD,OAAO,KAAK,YAAY;CAE1B,OAAO,KAAK,cAAc,KAAK;AACjC;AAEA,SAAS,UAAU,OAAoC;CACrD,IAAI,UAAU,KAAA,KAAa,UAAU,MACnC;CAEF,OAAO,OAAO,UAAU,WAAW,QAAQ,UAAU,KAAK;AAC5D;AAEA,SAAS,SAAS,OAA+C;CAC/D,OAAO,UAAU,KAAA,KAAa,QAAQ,IAAI,QAAQ,KAAA;AACpD;AAEA,SAAgB,mBAAmB,OAAqD;CACtF,IAAI,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AU,KAAK,KAAK;CAE1D,IAAI,QAAQ,eAAe;EACzB,WAAW,0BAA0B,UAAU,KAAK,MAAM;EAE1D,WAAW,wBAAwB,aAAa,KAAK,MAAM;CAC7D;AACF;AAEA,SAAS,kBACP,YACA,MACA,SACM;CACN,MAAM,QAAQ,KAAK,cAAc,CAAC;CAElC,WAAW,oBAAoB,KAAK,cAAc,KAAK;CACvD,WAAW,2BAA2B,MAAM;CAE5C,IAAI,QAAQ,cACV,WAAW,8BAA8B,UAAU,KAAK,KAAK;CAE/D,IAAI,QAAQ,eACV,WAAW,2BAA2B,UAAU,KAAK,MAAM;AAE/D;;AAGA,SAAS,wBAAwB,YAA4B,MAAgC;CAC3F,MAAM,QAAQ,KAAK,cAAc,CAAC;CAElC,WAAW,wBAAwB,MAAM;CACzC,WAAW,wBAAwB,MAAM;CACzC,OAAO,OAAO,YAAY,mBAAmB,MAAM,KAAK,CAAC;AAC3D;AAEA,SAAS,aAAa,QAAqC;CACzD,IAAI,OAAO,WAAW,UACpB,OAAO;CAET,IAAI,UAAU,OAAO,WAAW,YAAY,UAAU,UAAU,OAAO,OAAO,SAAS,UACrF,OAAO,OAAO;AAGlB"}
|
|
1
|
+
{"version":3,"file":"utils.js","names":[],"sources":["../../../../src/ai/mastra/utils.ts"],"sourcesContent":["import type { SpanAttributeValue } from '@sentry/core';\nimport { stringify } from '@sentry/core';\nimport {\n ERROR_TYPE,\n GEN_AI_AGENT_NAME,\n GEN_AI_INPUT_MESSAGES,\n GEN_AI_OPERATION_NAME,\n GEN_AI_OUTPUT_MESSAGES,\n GEN_AI_PIPELINE_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_SEED,\n GEN_AI_REQUEST_STOP_SEQUENCES,\n GEN_AI_REQUEST_TEMPERATURE,\n GEN_AI_REQUEST_TOP_K,\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_STREAMING,\n GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK,\n GEN_AI_RESPONSE_TEXT,\n GEN_AI_SYSTEM_INSTRUCTIONS,\n GEN_AI_TOOL_CALL_ARGUMENTS,\n GEN_AI_TOOL_CALL_RESULT,\n GEN_AI_TOOL_DEFINITIONS,\n GEN_AI_TOOL_DESCRIPTION,\n GEN_AI_TOOL_NAME,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n} from '@sentry/conventions/attributes';\nimport { AGENT_SPAN_TYPES, MODEL_SPAN_TYPES, SPAN_TYPE_OPS, TOOL_SPAN_TYPES } from './constants';\nimport type { MastraExportedSpan, MastraSpanType, MastraUsageStats } from './types';\n\nexport interface AttributeRecordingOptions {\n recordInputs: boolean;\n recordOutputs: boolean;\n}\n\nexport type SpanAttributes = Record<string, SpanAttributeValue | undefined>;\n\nexport function isExportedSpanType(spanType: MastraSpanType): boolean {\n // `in` would also match inherited keys like `constructor` or `toString`.\n return Object.prototype.hasOwnProperty.call(SPAN_TYPE_OPS, spanType);\n}\n\nexport function getOperation(spanType: MastraSpanType): { op: string; operationName: string } | undefined {\n return SPAN_TYPE_OPS[spanType];\n}\n\n/**\n * `{operation} {identifier}` per the gen_ai name templates. Mastra's own span name is never used.\n * https://conventions.sentry.dev/names/\n */\nexport function getSpanName(span: MastraExportedSpan): string {\n const operationName = getOperation(span.type)?.operationName ?? span.type;\n const identifier = getSpanIdentifier(span);\n\n return identifier ? `${operationName} ${identifier}` : operationName;\n}\n\nfunction getSpanIdentifier(span: MastraExportedSpan): string | undefined {\n if (span.type === 'classifier_evaluation') {\n return span.attributes?.modelId;\n }\n if (MODEL_SPAN_TYPES.has(span.type) || span.type === 'rag_embedding') {\n return span.attributes?.model;\n }\n return span.entityName ?? span.entityId;\n}\n\nfunction serialize(value: unknown): string | undefined {\n if (value === undefined || value === null) {\n return undefined;\n }\n return typeof value === 'string' ? value : stringify(value);\n}\n\nfunction positive(value: number | undefined): number | undefined {\n return value !== undefined && value > 0 ? value : undefined;\n}\n\nexport function getUsageAttributes(usage: MastraUsageStats | undefined): SpanAttributes {\n if (!usage) {\n return {};\n }\n\n const inputTokens = usage.inputTokens;\n const outputTokens = usage.outputTokens;\n // Mastra only reports `totalTokens` for some providers, so derive it when both halves are known.\n const totalTokens =\n usage.totalTokens ??\n (inputTokens !== undefined || outputTokens !== undefined ? (inputTokens ?? 0) + (outputTokens ?? 0) : undefined);\n\n return {\n [GEN_AI_USAGE_INPUT_TOKENS]: inputTokens,\n [GEN_AI_USAGE_OUTPUT_TOKENS]: outputTokens,\n [GEN_AI_USAGE_TOTAL_TOKENS]: totalTokens,\n // Mastra reports these as 0 for providers that don't cache or reason.\n [GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: positive(usage.inputDetails?.cacheRead),\n [GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: positive(usage.inputDetails?.cacheWrite),\n [GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]: positive(usage.outputDetails?.reasoning),\n };\n}\n\nconst USAGE_ATTRIBUTE_KEYS = [\n GEN_AI_USAGE_INPUT_TOKENS,\n GEN_AI_USAGE_OUTPUT_TOKENS,\n GEN_AI_USAGE_TOTAL_TOKENS,\n GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n] as const;\n\nfunction addTokenCounts(\n left: SpanAttributeValue | undefined,\n right: SpanAttributeValue | undefined,\n): number | undefined {\n const a = typeof left === 'number' ? left : undefined;\n const b = typeof right === 'number' ? right : undefined;\n if (a === undefined && b === undefined) {\n return undefined;\n }\n return (a ?? 0) + (b ?? 0);\n}\n\n/** Sum usage across generations. `setAttributes(undefined)` would drop the previous total. */\nexport function mergeUsageAttributes(existing: SpanAttributes, incoming: SpanAttributes): SpanAttributes {\n const merged: SpanAttributes = {};\n for (const key of USAGE_ATTRIBUTE_KEYS) {\n const value = addTokenCounts(existing[key], incoming[key]);\n if (value !== undefined) {\n merged[key] = value;\n }\n }\n return merged;\n}\n\n/** Convention attributes only. Called on start and end — Mastra fills fields progressively. */\nexport function getSpanAttributes(span: MastraExportedSpan, options: AttributeRecordingOptions): SpanAttributes {\n const operationName = getOperation(span.type)?.operationName;\n\n const attributes: SpanAttributes = {\n [GEN_AI_OPERATION_NAME]: operationName,\n };\n\n if (AGENT_SPAN_TYPES.has(span.type)) {\n addAgentAttributes(attributes, span, options);\n }\n\n if (MODEL_SPAN_TYPES.has(span.type) || span.type === 'rag_embedding') {\n addModelAttributes(attributes, span, options);\n }\n\n if (TOOL_SPAN_TYPES.has(span.type)) {\n addToolAttributes(attributes, span, options);\n }\n\n if (span.type === 'classifier_evaluation') {\n addEvaluationAttributes(attributes, span);\n }\n\n if (span.errorInfo) {\n attributes[ERROR_TYPE] = span.errorInfo.name ?? span.errorInfo.id;\n }\n\n return attributes;\n}\n\nfunction addAgentAttributes(\n attributes: SpanAttributes,\n span: MastraExportedSpan,\n options: AttributeRecordingOptions,\n): void {\n const attrs = span.attributes ?? {};\n const name = span.entityName ?? span.entityId;\n\n attributes[GEN_AI_AGENT_NAME] = name;\n attributes[GEN_AI_PIPELINE_NAME] = name;\n attributes[GEN_AI_TOOL_DEFINITIONS] = serialize(attrs.availableTools);\n\n if (options.recordInputs) {\n // `prompt` is Mastra's legacy alias for the system prompt.\n attributes[GEN_AI_SYSTEM_INSTRUCTIONS] = attrs.instructions ?? attrs.prompt;\n attributes[GEN_AI_INPUT_MESSAGES] = serialize(span.input);\n }\n if (options.recordOutputs) {\n attributes[GEN_AI_OUTPUT_MESSAGES] = serialize(span.output);\n // oxlint-disable-next-line typescript/no-deprecated -- still emitted by the other AI integrations\n attributes[GEN_AI_RESPONSE_TEXT] = responseText(span.output);\n }\n}\n\nfunction addModelAttributes(\n attributes: SpanAttributes,\n span: MastraExportedSpan,\n options: AttributeRecordingOptions,\n): void {\n const attrs = span.attributes ?? {};\n const parameters = attrs.parameters ?? {};\n\n attributes[GEN_AI_REQUEST_MODEL] = attrs.model;\n attributes[GEN_AI_PROVIDER_NAME] = attrs.provider;\n attributes[GEN_AI_RESPONSE_MODEL] = attrs.responseModel;\n attributes[GEN_AI_RESPONSE_ID] = attrs.responseId;\n attributes[GEN_AI_RESPONSE_STREAMING] = attrs.streaming;\n attributes[GEN_AI_RESPONSE_TIME_TO_FIRST_CHUNK] = attrs.completionStartTime\n ? (attrs.completionStartTime.getTime() - span.startTime.getTime()) / 1000\n : undefined;\n attributes[GEN_AI_RESPONSE_FINISH_REASONS] = attrs.finishReason ? JSON.stringify([attrs.finishReason]) : undefined;\n attributes[GEN_AI_AGENT_NAME] = span.entityName;\n\n attributes[GEN_AI_REQUEST_TEMPERATURE] = parameters.temperature;\n attributes[GEN_AI_REQUEST_MAX_TOKENS] = parameters.maxOutputTokens;\n attributes[GEN_AI_REQUEST_TOP_P] = parameters.topP;\n attributes[GEN_AI_REQUEST_TOP_K] = parameters.topK;\n attributes[GEN_AI_REQUEST_PRESENCE_PENALTY] = parameters.presencePenalty;\n attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY] = parameters.frequencyPenalty;\n attributes[GEN_AI_REQUEST_SEED] = parameters.seed;\n attributes[GEN_AI_REQUEST_STOP_SEQUENCES] = parameters.stopSequences;\n\n Object.assign(attributes, getUsageAttributes(attrs.usage));\n\n if (options.recordInputs) {\n attributes[GEN_AI_INPUT_MESSAGES] = serialize(span.input);\n }\n if (options.recordOutputs) {\n attributes[GEN_AI_OUTPUT_MESSAGES] = serialize(span.output);\n // oxlint-disable-next-line typescript/no-deprecated -- still emitted by the other AI integrations\n attributes[GEN_AI_RESPONSE_TEXT] = responseText(span.output);\n }\n}\n\nfunction addToolAttributes(\n attributes: SpanAttributes,\n span: MastraExportedSpan,\n options: AttributeRecordingOptions,\n): void {\n const attrs = span.attributes ?? {};\n\n attributes[GEN_AI_TOOL_NAME] = span.entityName ?? span.entityId;\n attributes[GEN_AI_TOOL_DESCRIPTION] = attrs.toolDescription;\n\n if (options.recordInputs) {\n attributes[GEN_AI_TOOL_CALL_ARGUMENTS] = serialize(span.input);\n }\n if (options.recordOutputs) {\n attributes[GEN_AI_TOOL_CALL_RESULT] = serialize(span.output);\n }\n}\n\n/** Mastra's `Classifier` sets no input or output on this span, so only the model and usage are known. */\nfunction addEvaluationAttributes(attributes: SpanAttributes, span: MastraExportedSpan): void {\n const attrs = span.attributes ?? {};\n\n attributes[GEN_AI_REQUEST_MODEL] = attrs.modelId;\n attributes[GEN_AI_PROVIDER_NAME] = attrs.provider;\n Object.assign(attributes, getUsageAttributes(attrs.usage));\n}\n\nfunction responseText(output: unknown): string | undefined {\n if (typeof output === 'string') {\n return output;\n }\n if (output && typeof output === 'object' && 'text' in output && typeof output.text === 'string') {\n return output.text;\n }\n return undefined;\n}\n"],"mappings":";;;;AAgDA,SAAgB,mBAAmB,UAAmC;CAEpE,OAAO,OAAO,UAAU,eAAe,KAAK,eAAe,QAAQ;AACrE;AAEA,SAAgB,aAAa,UAA6E;CACxG,OAAO,cAAc;AACvB;;;;;AAMA,SAAgB,YAAY,MAAkC;CAC5D,MAAM,gBAAgB,aAAa,KAAK,IAAI,CAAC,EAAE,iBAAiB,KAAK;CACrE,MAAM,aAAa,kBAAkB,IAAI;CAEzC,OAAO,aAAa,GAAG,cAAc,GAAG,eAAe;AACzD;AAEA,SAAS,kBAAkB,MAA8C;CACvE,IAAI,KAAK,SAAS,yBAChB,OAAO,KA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d, runGenAiSpanStart } from "../core/span-hooks.js";
|
|
2
|
+
import { buildMethodPath, extractSystemInstructions, getErrorStatus, getGenAiSpanOp, resolveGenAiCallRecording, wrapPromiseWithMethods } from "../core/utils.js";
|
|
2
3
|
import { GEN_AI_REQUEST_STREAM_ATTRIBUTE } from "../core/gen-ai-attributes.js";
|
|
3
4
|
import { MISTRAL_METHOD_REGISTRY, MISTRAL_ORIGIN, MISTRAL_PROVIDER_NAME } from "./constants.js";
|
|
4
5
|
import { instrumentEventStream } from "./streaming.js";
|
|
@@ -60,9 +61,14 @@ function instrumentMethod(originalMethod, instrumentedMethod, context, options)
|
|
|
60
61
|
return function instrumentedCall(...args) {
|
|
61
62
|
const operationName = instrumentedMethod.operation || "unknown";
|
|
62
63
|
const isStreamRequested = !!instrumentedMethod.streaming;
|
|
63
|
-
const requestAttributes = extractRequestAttributes(args, operationName, !!options.recordInputs, isStreamRequested);
|
|
64
64
|
const params = args[0];
|
|
65
65
|
const abortSignal = getMistralRequestSignal(args[1]);
|
|
66
|
+
const call = {
|
|
67
|
+
operation: operationName,
|
|
68
|
+
request: params
|
|
69
|
+
};
|
|
70
|
+
const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);
|
|
71
|
+
const requestAttributes = extractRequestAttributes(args, operationName, recordInputs, isStreamRequested);
|
|
66
72
|
const spanConfig = {
|
|
67
73
|
name: getSpanName(operationName, requestAttributes),
|
|
68
74
|
op: getGenAiSpanOp(operationName),
|
|
@@ -72,12 +78,17 @@ function instrumentMethod(originalMethod, instrumentedMethod, context, options)
|
|
|
72
78
|
let originalResult;
|
|
73
79
|
const instrumentedPromise = startSpanManual(spanConfig, (span) => {
|
|
74
80
|
originalResult = originalMethod.apply(context, args);
|
|
75
|
-
if (
|
|
81
|
+
if (recordInputs && params) addRequestAttributes(span, params, operationName);
|
|
82
|
+
runGenAiSpanStart(options, span, call);
|
|
76
83
|
return originalResult.then((result) => {
|
|
77
|
-
if (!instrumentEventStream(result, span,
|
|
84
|
+
if (!instrumentEventStream(result, span, recordOutputs, abortSignal, (streamResult) => runGenAiSpanEnd(options, span, call, streamResult))) {
|
|
85
|
+
runGenAiSpanEnd(options, span, call, { response: result });
|
|
86
|
+
span.end();
|
|
87
|
+
}
|
|
78
88
|
return result;
|
|
79
89
|
}, (error) => {
|
|
80
90
|
span.setStatus(getErrorStatus(abortSignal));
|
|
91
|
+
runGenAiSpanEnd(options, span, call, { error });
|
|
81
92
|
span.end();
|
|
82
93
|
throw error;
|
|
83
94
|
});
|
|
@@ -87,12 +98,15 @@ function instrumentMethod(originalMethod, instrumentedMethod, context, options)
|
|
|
87
98
|
let originalResult;
|
|
88
99
|
const instrumentedPromise = startSpan(spanConfig, (span) => {
|
|
89
100
|
originalResult = originalMethod.apply(context, args);
|
|
90
|
-
if (
|
|
101
|
+
if (recordInputs && params) addRequestAttributes(span, params, operationName);
|
|
102
|
+
runGenAiSpanStart(options, span, call);
|
|
91
103
|
return originalResult.then((result) => {
|
|
92
|
-
addResponseAttributes(span, result,
|
|
104
|
+
addResponseAttributes(span, result, recordOutputs);
|
|
105
|
+
runGenAiSpanEnd(options, span, call, { response: result });
|
|
93
106
|
return result;
|
|
94
107
|
}, (error) => {
|
|
95
108
|
span.setStatus(getErrorStatus(abortSignal));
|
|
109
|
+
runGenAiSpanEnd(options, span, call, { error });
|
|
96
110
|
throw error;
|
|
97
111
|
});
|
|
98
112
|
});
|
|
@@ -118,7 +132,7 @@ function createDeepProxy(target, currentPath = "", options) {
|
|
|
118
132
|
* Can be used across Node.js, Cloudflare Workers, and Vercel Edge.
|
|
119
133
|
*/
|
|
120
134
|
function instrumentMistralAiClient(client, options) {
|
|
121
|
-
return createDeepProxy(client, "",
|
|
135
|
+
return createDeepProxy(client, "", options ?? {});
|
|
122
136
|
}
|
|
123
137
|
export { addRequestAttributes, extractRequestAttributes, instrumentMistralAiClient };
|
|
124
138
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../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,IAA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AM;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
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../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 { runGenAiSpanEnd, runGenAiSpanStart } from '../core/span-hooks';\nimport type { InstrumentedMethodEntry } from '../core/utils';\nimport {\n buildMethodPath,\n extractSystemInstructions,\n getErrorStatus,\n getGenAiSpanOp,\n resolveGenAiCallRecording,\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 { MistralCallInfo, 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 params = args[0] as Record<string, unknown> | undefined;\n const abortSignal = getMistralRequestSignal(args[1]);\n const call: MistralCallInfo = { operation: operationName, request: params };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n const requestAttributes = extractRequestAttributes(args, operationName, recordInputs, isStreamRequested);\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 (recordInputs && params) {\n addRequestAttributes(span, params, operationName);\n }\n runGenAiSpanStart(options, span, call);\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 const isStream = instrumentEventStream(result, span, recordOutputs, abortSignal, streamResult =>\n runGenAiSpanEnd(options, span, call, streamResult),\n );\n if (!isStream) {\n runGenAiSpanEnd(options, span, call, { response: result });\n span.end();\n }\n return result;\n },\n error => {\n span.setStatus(getErrorStatus(abortSignal));\n runGenAiSpanEnd(options, span, call, { 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 (recordInputs && params) {\n addRequestAttributes(span, params, operationName);\n }\n runGenAiSpanStart(options, span, call);\n\n return originalResult.then(\n result => {\n addResponseAttributes(span, result, recordOutputs);\n runGenAiSpanEnd(options, span, call, { response: result });\n return result;\n },\n error => {\n span.setStatus(getErrorStatus(abortSignal));\n runGenAiSpanEnd(options, span, call, { error });\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, '', options ?? {});\n}\n"],"mappings":";;;;;;;;;;;;AA+BA,SAAS,uBAAuB,QAAqD;CACnF,IAAI,CAAC,MAAM,Q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,CAAC;IACzD,OAAO;GACT,IACA,UAAS;IACP,KAAK,UAAU,eAAe,WAAW,CAAC;IAC1C,gBAAgB,SAAS,MAAM,MAAM,EAAE,MAAM,CAAC;IAC9C,MAAM;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,WAAW,CAAC,CAAC;AAClD"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { endStreamSpan, getErrorStatus, setOutputMessagesAttribute } from "../core/utils.js";
|
|
2
|
+
import { recordTimeToFirstChunk } from "../core/time-to-first-chunk.js";
|
|
2
3
|
import { contentToString } from "./utils.js";
|
|
3
4
|
// src/ai/mistral/streaming.ts
|
|
4
5
|
/** Whether a value can be drained with `for await`. */
|
|
@@ -140,13 +141,14 @@ function instrumentedSource(readable) {
|
|
|
140
141
|
*
|
|
141
142
|
* Returns `false` for a value that is not a stream, leaving it untouched.
|
|
142
143
|
*/
|
|
143
|
-
function instrumentEventStream(stream, span, recordOutputs, abortSignal) {
|
|
144
|
+
function instrumentEventStream(stream, span, recordOutputs, abortSignal, beforeSpanEnd) {
|
|
144
145
|
if (!isAsyncIterable(stream)) return false;
|
|
145
146
|
const state = createStreamingState();
|
|
146
147
|
let consumer;
|
|
147
148
|
let settled = false;
|
|
148
149
|
let cancelled = false;
|
|
149
150
|
const claim = (candidate) => {
|
|
151
|
+
recordTimeToFirstChunk(span);
|
|
150
152
|
consumer ?? (consumer = candidate);
|
|
151
153
|
return consumer === candidate;
|
|
152
154
|
};
|
|
@@ -166,7 +168,7 @@ function instrumentEventStream(stream, span, recordOutputs, abortSignal) {
|
|
|
166
168
|
endStreamSpan(span, {
|
|
167
169
|
...state,
|
|
168
170
|
toolCalls
|
|
169
|
-
}, recordOutputs);
|
|
171
|
+
}, recordOutputs, () => beforeSpanEnd?.(error !== void 0 && !cancelled ? { error } : {}));
|
|
170
172
|
};
|
|
171
173
|
const instrumented = instrumentIterator(stream[Symbol.asyncIterator].bind(stream), state, recordOutputs, claim, settle);
|
|
172
174
|
stream[Symbol.asyncIterator] = () => instrumented;
|