|
| 1 | +import { trace } from '@opentelemetry/api'; |
| 2 | +import { |
| 3 | + BasicTracerProvider, |
| 4 | + InMemorySpanExporter, |
| 5 | + SimpleSpanProcessor, |
| 6 | +} from '@opentelemetry/sdk-trace-base'; |
| 7 | +import { generateText, isStepCount, tool } from 'ai'; |
| 8 | +import { MockLanguageModelV4 } from 'ai/test'; |
| 9 | +import { z } from 'zod'; |
| 10 | + |
| 11 | +import { |
| 12 | + createAITelemetry, |
| 13 | + enrichLLMSpan, |
| 14 | + type LLMAttribution, |
| 15 | + llmTelemetry, |
| 16 | + registerAITelemetry, |
| 17 | +} from '@/utils/aiTelemetry'; |
| 18 | + |
| 19 | +const usage: Awaited<ReturnType<MockLanguageModelV4['doGenerate']>>['usage'] = { |
| 20 | + inputTokens: { |
| 21 | + total: 10, |
| 22 | + noCache: 10, |
| 23 | + cacheRead: undefined, |
| 24 | + cacheWrite: undefined, |
| 25 | + }, |
| 26 | + outputTokens: { total: 5, text: 5, reasoning: undefined }, |
| 27 | +}; |
| 28 | + |
| 29 | +// Step 1 calls a tool, step 2 answers, so the call produces operation, step, |
| 30 | +// chat and execute_tool spans. |
| 31 | +const createModel = () => { |
| 32 | + let call = 0; |
| 33 | + return new MockLanguageModelV4({ |
| 34 | + provider: 'anthropic', |
| 35 | + modelId: 'mock-model', |
| 36 | + doGenerate: async () => { |
| 37 | + call += 1; |
| 38 | + return call === 1 |
| 39 | + ? { |
| 40 | + content: [ |
| 41 | + { |
| 42 | + type: 'tool-call', |
| 43 | + toolCallId: 'tc-1', |
| 44 | + toolName: 'lookup', |
| 45 | + input: '{"q":"x"}', |
| 46 | + }, |
| 47 | + ], |
| 48 | + finishReason: { unified: 'tool-calls', raw: undefined }, |
| 49 | + usage, |
| 50 | + warnings: [], |
| 51 | + } |
| 52 | + : { |
| 53 | + content: [{ type: 'text', text: 'done' }], |
| 54 | + finishReason: { unified: 'stop', raw: undefined }, |
| 55 | + usage, |
| 56 | + warnings: [], |
| 57 | + }; |
| 58 | + }, |
| 59 | + }); |
| 60 | +}; |
| 61 | + |
| 62 | +const runToolCall = (telemetry: ReturnType<typeof llmTelemetry>) => |
| 63 | + generateText({ |
| 64 | + model: createModel(), |
| 65 | + prompt: 'hi', |
| 66 | + tools: { |
| 67 | + lookup: tool({ |
| 68 | + inputSchema: z.object({ q: z.string() }), |
| 69 | + execute: async ({ q }) => ({ q }), |
| 70 | + }), |
| 71 | + }, |
| 72 | + stopWhen: isStepCount(2), |
| 73 | + ...telemetry, |
| 74 | + }); |
| 75 | + |
| 76 | +const runTracedCall = async (attribution: LLMAttribution) => { |
| 77 | + const exporter = new InMemorySpanExporter(); |
| 78 | + const provider = new BasicTracerProvider({ |
| 79 | + spanProcessors: [new SimpleSpanProcessor(exporter)], |
| 80 | + }); |
| 81 | + await runToolCall( |
| 82 | + llmTelemetry(attribution, { |
| 83 | + functionId: 'test.fn', |
| 84 | + integrations: createAITelemetry({ tracer: provider.getTracer('test') }), |
| 85 | + }), |
| 86 | + ); |
| 87 | + return exporter.getFinishedSpans(); |
| 88 | +}; |
| 89 | + |
| 90 | +const operationNames = (spans: { attributes: Record<string, unknown> }[]) => |
| 91 | + spans.map(s => s.attributes['gen_ai.operation.name']).sort(); |
| 92 | + |
| 93 | +describe('AI SDK OpenTelemetry integration', () => { |
| 94 | + it('stamps attribution onto every span of the call', async () => { |
| 95 | + const spans = await runTracedCall({ |
| 96 | + sessionId: 'session-1', |
| 97 | + teamId: 'team-1', |
| 98 | + userId: 'user-1', |
| 99 | + }); |
| 100 | + |
| 101 | + const operations = spans.map(s => s.attributes['gen_ai.operation.name']); |
| 102 | + expect(operations).toEqual( |
| 103 | + expect.arrayContaining(['chat', 'execute_tool']), |
| 104 | + ); |
| 105 | + for (const span of spans) { |
| 106 | + expect(span.attributes).toMatchObject({ |
| 107 | + 'gen_ai.conversation.id': 'session-1', |
| 108 | + 'hyperdx.team.id': 'team-1', |
| 109 | + 'user.id': 'user-1', |
| 110 | + }); |
| 111 | + } |
| 112 | + }); |
| 113 | + |
| 114 | + it('omits the session attribute when only team and user are known', async () => { |
| 115 | + // The chart assistant has no conversation-scoped id. |
| 116 | + const spans = await runTracedCall({ teamId: 'team-1', userId: 'user-1' }); |
| 117 | + |
| 118 | + expect(spans.length).toBeGreaterThan(0); |
| 119 | + for (const span of spans) { |
| 120 | + expect(span.attributes).toMatchObject({ |
| 121 | + 'hyperdx.team.id': 'team-1', |
| 122 | + 'user.id': 'user-1', |
| 123 | + }); |
| 124 | + expect(span.attributes).not.toHaveProperty('gen_ai.conversation.id'); |
| 125 | + } |
| 126 | + }); |
| 127 | + |
| 128 | + it('emits GenAI semconv attributes the LLM dashboard reads', async () => { |
| 129 | + const spans = await runTracedCall({ sessionId: 'session-1' }); |
| 130 | + |
| 131 | + const chat = spans.find( |
| 132 | + s => s.attributes['gen_ai.operation.name'] === 'chat', |
| 133 | + ); |
| 134 | + expect(chat?.attributes).toMatchObject({ |
| 135 | + 'gen_ai.provider.name': 'anthropic', |
| 136 | + 'gen_ai.request.model': 'mock-model', |
| 137 | + 'gen_ai.usage.input_tokens': 10, |
| 138 | + 'gen_ai.usage.output_tokens': 5, |
| 139 | + }); |
| 140 | + expect( |
| 141 | + spans.some(s => s.attributes['gen_ai.agent.name'] === 'test.fn'), |
| 142 | + ).toBe(true); |
| 143 | + |
| 144 | + // Message content feeds the dashboard's Messages tab. |
| 145 | + expect(chat?.attributes['gen_ai.input.messages']).toEqual( |
| 146 | + expect.stringContaining('"content":"hi"'), |
| 147 | + ); |
| 148 | + expect(chat?.attributes['gen_ai.output.messages']).toEqual( |
| 149 | + expect.stringContaining('"name":"lookup"'), |
| 150 | + ); |
| 151 | + const toolSpan = spans.find( |
| 152 | + s => s.attributes['gen_ai.operation.name'] === 'execute_tool', |
| 153 | + ); |
| 154 | + expect(toolSpan?.attributes).toMatchObject({ |
| 155 | + 'gen_ai.tool.name': 'lookup', |
| 156 | + 'gen_ai.tool.call.arguments': expect.stringContaining('"q":"x"'), |
| 157 | + }); |
| 158 | + }); |
| 159 | +}); |
| 160 | + |
| 161 | +describe('enrichLLMSpan', () => { |
| 162 | + const enrich = (runtimeContext: Record<string, unknown> | undefined) => |
| 163 | + enrichLLMSpan({ |
| 164 | + spanType: 'languageModel', |
| 165 | + operationId: 'ai.generateText', |
| 166 | + callId: 'call-1', |
| 167 | + runtimeContext, |
| 168 | + }); |
| 169 | + |
| 170 | + it('skips missing, empty and non-string values', () => { |
| 171 | + expect(enrich({ sessionId: '', teamId: 42, userId: undefined })).toEqual( |
| 172 | + {}, |
| 173 | + ); |
| 174 | + expect(enrich(undefined)).toEqual({}); |
| 175 | + }); |
| 176 | + |
| 177 | + it('ignores unrelated runtime context keys', () => { |
| 178 | + expect(enrich({ sessionId: 's1', other: 'x' })).toEqual({ |
| 179 | + 'gen_ai.conversation.id': 's1', |
| 180 | + }); |
| 181 | + }); |
| 182 | +}); |
| 183 | + |
| 184 | +describe('registerAITelemetry', () => { |
| 185 | + afterAll(() => trace.disable()); |
| 186 | + |
| 187 | + it('emits each span once through the global tracer provider, even if registered twice', async () => { |
| 188 | + const perCall = operationNames( |
| 189 | + await runTracedCall({ sessionId: 'session-1' }), |
| 190 | + ); |
| 191 | + |
| 192 | + const exporter = new InMemorySpanExporter(); |
| 193 | + trace.setGlobalTracerProvider( |
| 194 | + new BasicTracerProvider({ |
| 195 | + spanProcessors: [new SimpleSpanProcessor(exporter)], |
| 196 | + }), |
| 197 | + ); |
| 198 | + registerAITelemetry(); |
| 199 | + registerAITelemetry(); |
| 200 | + await runToolCall(llmTelemetry({ sessionId: 'session-global' })); |
| 201 | + |
| 202 | + const spans = exporter.getFinishedSpans(); |
| 203 | + expect(perCall.length).toBeGreaterThan(0); |
| 204 | + expect(operationNames(spans)).toEqual(perCall); |
| 205 | + for (const span of spans) { |
| 206 | + expect(span.attributes['gen_ai.conversation.id']).toBe('session-global'); |
| 207 | + } |
| 208 | + }); |
| 209 | +}); |
0 commit comments