|
| 1 | +import * as diagnosticsChannel from 'node:diagnostics_channel'; |
| 2 | +import type { CompiledGraph, IntegrationFn, LangGraphOptions } from '@sentry/core'; |
| 3 | +import { |
| 4 | + _INTERNAL_getLangGraphCreateAgentSpanOptions, |
| 5 | + createLangChainCallbackHandler, |
| 6 | + debug, |
| 7 | + defineIntegration, |
| 8 | + extractAgentNameFromParams, |
| 9 | + extractLLMFromParams, |
| 10 | + instrumentCompiledGraphInvoke, |
| 11 | + LANGGRAPH_INTEGRATION_NAME, |
| 12 | + resolveAIRecordingOptions, |
| 13 | + startInactiveSpan, |
| 14 | + waitForTracingChannelBinding, |
| 15 | + wrapToolsWithSpans, |
| 16 | +} from '@sentry/core'; |
| 17 | +import { DEBUG_BUILD } from '../../debug-build'; |
| 18 | +import { CHANNELS } from '../../orchestrion/channels'; |
| 19 | +import { bindTracingChannelToSpan } from '../../tracing-channel'; |
| 20 | + |
| 21 | +// Same name as the OTel integration by design: when enabled, the OTel 'LangGraph' integration is |
| 22 | +// dropped from the default set (see the Node opt-in loader). |
| 23 | +const INTEGRATION_NAME = LANGGRAPH_INTEGRATION_NAME; |
| 24 | + |
| 25 | +interface CompileChannelContext { |
| 26 | + arguments: unknown[]; |
| 27 | + result?: unknown; |
| 28 | +} |
| 29 | + |
| 30 | +interface CreateReactAgentChannelContext { |
| 31 | + arguments: unknown[]; |
| 32 | + result?: unknown; |
| 33 | +} |
| 34 | + |
| 35 | +let subscribed = false; |
| 36 | + |
| 37 | +// `createReactAgent` compiles a `StateGraph` internally; suppress the `create_agent` span for that |
| 38 | +// nested compile so a react agent gets a single `invoke_agent` span, matching the OTel path. |
| 39 | +let insideCreateReactAgent = false; |
| 40 | + |
| 41 | +const _langGraphChannelIntegration = ((options: LangGraphOptions = {}) => { |
| 42 | + return { |
| 43 | + name: INTEGRATION_NAME, |
| 44 | + setupOnce() { |
| 45 | + // `tracingChannel` is unavailable before Node 18.19, and a second `init()` would double-subscribe. |
| 46 | + if (!diagnosticsChannel.tracingChannel || subscribed) { |
| 47 | + return; |
| 48 | + } |
| 49 | + subscribed = true; |
| 50 | + |
| 51 | + const resolvedOptions = resolveAIRecordingOptions(options); |
| 52 | + const sentryHandler = createLangChainCallbackHandler(resolvedOptions); |
| 53 | + |
| 54 | + // `bindTracingChannelToSpan` needs the async-context binding that `initOpenTelemetry()` registers |
| 55 | + // after `setupOnce` runs, so wait for it before subscribing. |
| 56 | + waitForTracingChannelBinding(() => { |
| 57 | + // StateGraph.compile → `create_agent` span, then wrap the returned graph's `invoke`. |
| 58 | + DEBUG_BUILD && |
| 59 | + debug.log(`[orchestrion:langgraph] subscribing to channel "${CHANNELS.LANGGRAPH_STATE_GRAPH_COMPILE}"`); |
| 60 | + bindTracingChannelToSpan( |
| 61 | + diagnosticsChannel.tracingChannel<CompileChannelContext>(CHANNELS.LANGGRAPH_STATE_GRAPH_COMPILE), |
| 62 | + data => { |
| 63 | + if (insideCreateReactAgent) { |
| 64 | + return undefined; |
| 65 | + } |
| 66 | + const compileOptions = getFirstArgObject(data.arguments); |
| 67 | + const name = typeof compileOptions?.name === 'string' ? compileOptions.name : undefined; |
| 68 | + |
| 69 | + return startInactiveSpan(_INTERNAL_getLangGraphCreateAgentSpanOptions(name)); |
| 70 | + }, |
| 71 | + { |
| 72 | + beforeSpanEnd: (_span, data) => { |
| 73 | + wrapCompiledGraphInvoke( |
| 74 | + data.result, |
| 75 | + getFirstArgObject(data.arguments) ?? {}, |
| 76 | + resolvedOptions, |
| 77 | + null, |
| 78 | + sentryHandler, |
| 79 | + ); |
| 80 | + }, |
| 81 | + }, |
| 82 | + ); |
| 83 | + |
| 84 | + // createReactAgent has no `create_agent` span of its own; it only wraps tools and the returned |
| 85 | + // graph's `invoke`. Tools are wrapped at `start` (before the agent runs), invoke at `end`. |
| 86 | + DEBUG_BUILD && |
| 87 | + debug.log(`[orchestrion:langgraph] subscribing to channel "${CHANNELS.LANGGRAPH_CREATE_REACT_AGENT}"`); |
| 88 | + const reactAgentChannel = diagnosticsChannel.tracingChannel<CreateReactAgentChannelContext>( |
| 89 | + CHANNELS.LANGGRAPH_CREATE_REACT_AGENT, |
| 90 | + ); |
| 91 | + reactAgentChannel.start.subscribe(message => { |
| 92 | + insideCreateReactAgent = true; |
| 93 | + const { arguments: args } = message as CreateReactAgentChannelContext; |
| 94 | + const params = getFirstArgObject(args); |
| 95 | + if (params && Array.isArray(params.tools) && params.tools.length > 0) { |
| 96 | + wrapToolsWithSpans(params.tools, resolvedOptions, extractAgentNameFromParams(args) ?? undefined); |
| 97 | + } |
| 98 | + }); |
| 99 | + reactAgentChannel.end.subscribe(message => { |
| 100 | + insideCreateReactAgent = false; |
| 101 | + const { arguments: args, result } = message as CreateReactAgentChannelContext; |
| 102 | + const agentName = extractAgentNameFromParams(args) ?? undefined; |
| 103 | + const compileOptions = agentName ? { name: agentName } : {}; |
| 104 | + wrapCompiledGraphInvoke(result, compileOptions, resolvedOptions, extractLLMFromParams(args), sentryHandler); |
| 105 | + }); |
| 106 | + // Make sure a thrown `createReactAgent` doesn't leave the suppression flag stuck on. |
| 107 | + reactAgentChannel.error.subscribe(() => { |
| 108 | + insideCreateReactAgent = false; |
| 109 | + }); |
| 110 | + }); |
| 111 | + }, |
| 112 | + }; |
| 113 | +}) satisfies IntegrationFn; |
| 114 | + |
| 115 | +function getFirstArgObject(args: unknown[] | undefined): Record<string, unknown> | undefined { |
| 116 | + const first = (args ?? [])[0]; |
| 117 | + |
| 118 | + return typeof first === 'object' && first !== null ? (first as Record<string, unknown>) : undefined; |
| 119 | +} |
| 120 | + |
| 121 | +/** |
| 122 | + * Wrap the compiled graph's `invoke` with the shared `invoke_agent` instrumentation, exactly as the |
| 123 | + * OTel path does on the returned graph. |
| 124 | + */ |
| 125 | +function wrapCompiledGraphInvoke( |
| 126 | + graph: unknown, |
| 127 | + compileOptions: Record<string, unknown>, |
| 128 | + options: LangGraphOptions, |
| 129 | + llm: ReturnType<typeof extractLLMFromParams>, |
| 130 | + sentryHandler: unknown, |
| 131 | +): void { |
| 132 | + if (!graph || typeof graph !== 'object') { |
| 133 | + return; |
| 134 | + } |
| 135 | + |
| 136 | + const compiledGraph = graph as CompiledGraph; |
| 137 | + const originalInvoke = compiledGraph.invoke; |
| 138 | + if (typeof originalInvoke === 'function') { |
| 139 | + compiledGraph.invoke = instrumentCompiledGraphInvoke( |
| 140 | + originalInvoke.bind(compiledGraph), |
| 141 | + compiledGraph, |
| 142 | + compileOptions, |
| 143 | + options, |
| 144 | + llm, |
| 145 | + sentryHandler, |
| 146 | + ); |
| 147 | + } |
| 148 | +} |
| 149 | + |
| 150 | +/** |
| 151 | + * EXPERIMENTAL — orchestrion-driven LangGraph integration. Subscribes to the diagnostics_channels |
| 152 | + * injected into `@langchain/langgraph`'s `StateGraph.compile` and `createReactAgent`, so it requires |
| 153 | + * the orchestrion runtime hook or bundler plugin. |
| 154 | + */ |
| 155 | +export const langGraphChannelIntegration = defineIntegration(_langGraphChannelIntegration); |
0 commit comments