Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/ai-sdk-v7-genai-spans.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@hyperdx/api': patch
---

feat: upgrade the AI SDK to v7 and trace AI calls with GenAI semantic conventions

AI assistant calls now emit OpenTelemetry spans that follow the GenAI semantic conventions (`invoke_agent` / `chat` / `execute_tool` spans with `gen_ai.*` attributes) instead of the legacy `ai.*` span shape. Team and user attribution moves from `ai.telemetry.metadata.*` to `hyperdx.team.id` and `user.id` (plus `gen_ai.conversation.id` when a session is known). Saved searches, alerts or dashboards keyed on the old `ai.*` span names or attributes need updating.
5 changes: 5 additions & 0 deletions packages/api/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ const tsJestTransformCfg = createJsWithTsPreset({
// TypeScript 6 requires an explicit rootDir when compiling a subset of
// files (ts-jest compiles per-file), otherwise it errors with TS5011.
rootDir: './src',
// The AI SDK (v7+) ships ESM-only builds that Jest's CJS loader can't
// parse, so they are transpiled like source (see transformIgnorePatterns).
allowJs: true,
},
});

Expand All @@ -22,4 +25,6 @@ module.exports = {
moduleNameMapper: {
'@/(.*)$': '<rootDir>/$1',
},
// Keep in sync with jest.int.config.js.
transformIgnorePatterns: ['/node_modules/(?!(ai|@ai-sdk|@workflow/serde)/)'],
};
3 changes: 2 additions & 1 deletion packages/api/jest.int.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,9 @@ module.exports = {
'^.+\\.mjs$': esmDepsTransformCfg.transform['^.+\\.[tj]sx?$'],
},
moduleFileExtensions: ['js', 'mjs', 'json', 'ts', 'tsx', 'node'],
// Superset of the unit config's list (AI SDK packages) plus the proxy deps.
transformIgnorePatterns: [
'/node_modules/(?!(http-proxy-middleware|httpxy|is-plain-obj)/)',
'/node_modules/(?!(ai|@ai-sdk|@workflow/serde|http-proxy-middleware|httpxy|is-plain-obj)/)',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — Integration config restates the unit config's ESM transpile setup by hand

jest.config.js now sets rootDir: './src' and allowJs: true, so esmDepsTransformCfg here (lines 9-14) builds the same transform as base, and the AI-SDK package list is copied with a "keep in sync" comment. Keep only the .mjs transform entry on top of base.transform, and build transformIgnorePatterns from one shared array of ESM package names exported by jest.config.js plus the three proxy packages. Then the two configs can't drift apart.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

],
testMatch: ['**/__tests__/**/*.int.test.ts?(x)'],
// Override the unit config's ignore list: it excludes `.int.test.ts`, which
Expand Down
8 changes: 5 additions & 3 deletions packages/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@
}
},
"dependencies": {
"@ai-sdk/anthropic": "^3.0.58",
"@ai-sdk/openai": "^3.0.47",
"@ai-sdk/anthropic": "^4.0.65",
"@ai-sdk/openai": "^4.0.78",
"@ai-sdk/otel": "^1.0.116",
"@braintree/sanitize-url": "^7.1.1",
"@clickhouse/client-common": "1.23.0-head.fae5998.1",
"@esm2cjs/p-queue": "^7.3.0",
Expand All @@ -30,7 +31,7 @@
"@opentelemetry/sdk-metrics": "^1.30.1",
"@slack/webhook": "^7.0.0",
"@types/node": "^22.15.18",
"ai": "^6.0.116",
"ai": "^7.0.116",
"aws4": "^1.13.2",
"chrono-node": "^2.9.0",
"compression": "^1.7.4",
Expand Down Expand Up @@ -65,6 +66,7 @@
"zod-express-middleware": "^1.4.0"
},
"devDependencies": {
"@opentelemetry/sdk-trace-base": "^1.30.1",
"@stoplight/spectral-cli": "^6.15.0",
"@types/compression": "^1.7.3",
"@types/cors": "^2.8.14",
Expand Down
3 changes: 3 additions & 0 deletions packages/api/src/api-app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,12 @@ import savedSearchRouter from './routers/api/savedSearch';
import sourcesRouter from './routers/api/sources';
import externalRoutersV2 from './routers/external-api/v2';
import usageStats from './tasks/usageStats';
import { registerAITelemetry } from './utils/aiTelemetry';
import logger, { expressLogger } from './utils/logger';
import passport from './utils/passport';

registerAITelemetry();

const app: express.Application = express();

const sess: session.SessionOptions & { cookie: session.CookieOptions } = {
Expand Down
20 changes: 1 addition & 19 deletions packages/api/src/controllers/__tests__/ai.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ function setConfig(overrides: Record<string, string | undefined>) {
Object.assign(mockConfig, overrides);
}

import { getAIModel, llmTelemetry } from '@/controllers/ai';
import { getAIModel } from '@/controllers/ai';

beforeEach(() => {
setConfig({});
Expand Down Expand Up @@ -252,21 +252,3 @@ describe('openai provider', () => {
});
});
});

describe('llmTelemetry', () => {
it('enables telemetry and passes through string metadata', () => {
expect(
llmTelemetry({ sessionId: 'notebook-1', teamId: 't1', userId: 'u1' }),
).toEqual({
isEnabled: true,
metadata: { sessionId: 'notebook-1', teamId: 't1', userId: 'u1' },
});
});

it('drops nullish metadata values', () => {
expect(llmTelemetry({ sessionId: undefined, teamId: 't1' })).toEqual({
isEnabled: true,
metadata: { teamId: 't1' },
});
});
});
22 changes: 0 additions & 22 deletions packages/api/src/controllers/ai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,28 +73,6 @@ export function getAIModel(): LanguageModel {
}
}

/**
* Vercel AI SDK telemetry settings for LLM calls. The SDK flattens each
* metadata entry onto every span of the call as
* `ai.telemetry.metadata.<key>`, which the LLM dashboard reads:
* `sessionId` groups the call's spans into a session on the Sessions tab
* (pass a stable conversation-scoped id, e.g. a notebook id) and `userId`
* feeds per-user attribution. Nullish values are dropped.
*/
export function llmTelemetry(metadata: Record<string, string | undefined>): {
isEnabled: boolean;
metadata: Record<string, string>;
} {
return {
isEnabled: true,
metadata: Object.fromEntries(
Object.entries(metadata).filter(
(entry): entry is [string, string] => entry[1] != null,
),
),
};
}

export async function getAIMetadata(source: ISource) {
const connectionId = source.connection.toString();

Expand Down
8 changes: 2 additions & 6 deletions packages/api/src/routers/api/ai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ import {
getAIMetadata,
getAIModel,
getChartConfigFromResolvedConfig,
llmTelemetry,
} from '@/controllers/ai';
import { getSource } from '@/controllers/sources';
import { getNonNullUserWithTeam } from '@/middleware/auth';
import { llmTelemetry } from '@/utils/aiTelemetry';
import { Api404Error, Api500Error } from '@/utils/errors';
import { withOperationMetrics } from '@/utils/instrumentation';
import logger from '@/utils/logger';
Expand Down Expand Up @@ -106,11 +106,7 @@ ${JSON.stringify(allFieldsWithKeys.slice(0, 200).map(f => ({ field: f.key, type:
output: Output.object({
schema: AssistantLineTableConfigSchema,
}),
// teamId/userId flatten to ai.telemetry.metadata.* span
// attributes for attribution on the LLM dashboard. Callers
// with a conversation-scoped id should also pass sessionId so
// their calls group into a session (see llmTelemetry).
experimental_telemetry: llmTelemetry({
...llmTelemetry({
teamId: teamId.toString(),
userId: userId.toString(),
}),
Expand Down
209 changes: 209 additions & 0 deletions packages/api/src/utils/__tests__/aiTelemetry.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
import { trace } from '@opentelemetry/api';
import {
BasicTracerProvider,
InMemorySpanExporter,
SimpleSpanProcessor,
} from '@opentelemetry/sdk-trace-base';
import { generateText, isStepCount, tool } from 'ai';
import { MockLanguageModelV4 } from 'ai/test';
import { z } from 'zod';

import {
createAITelemetry,
enrichLLMSpan,
type LLMAttribution,
llmTelemetry,
registerAITelemetry,
} from '@/utils/aiTelemetry';

const usage: Awaited<ReturnType<MockLanguageModelV4['doGenerate']>>['usage'] = {
inputTokens: {
total: 10,
noCache: 10,
cacheRead: undefined,
cacheWrite: undefined,
},
outputTokens: { total: 5, text: 5, reasoning: undefined },
};

// Step 1 calls a tool, step 2 answers, so the call produces operation, step,
// chat and execute_tool spans.
const createModel = () => {
let call = 0;
return new MockLanguageModelV4({
provider: 'anthropic',
modelId: 'mock-model',
doGenerate: async () => {
call += 1;
return call === 1
? {
content: [
{
type: 'tool-call',
toolCallId: 'tc-1',
toolName: 'lookup',
input: '{"q":"x"}',
},
],
finishReason: { unified: 'tool-calls', raw: undefined },
usage,
warnings: [],
}
: {
content: [{ type: 'text', text: 'done' }],
finishReason: { unified: 'stop', raw: undefined },
usage,
warnings: [],
};
},
});
};

const runToolCall = (telemetry: ReturnType<typeof llmTelemetry>) =>
generateText({
model: createModel(),
prompt: 'hi',
tools: {
lookup: tool({
inputSchema: z.object({ q: z.string() }),
execute: async ({ q }) => ({ q }),
}),
},
stopWhen: isStepCount(2),
...telemetry,
});

const runTracedCall = async (attribution: LLMAttribution) => {
const exporter = new InMemorySpanExporter();
const provider = new BasicTracerProvider({
spanProcessors: [new SimpleSpanProcessor(exporter)],
});
await runToolCall(
llmTelemetry(attribution, {
functionId: 'test.fn',
integrations: createAITelemetry({ tracer: provider.getTracer('test') }),
}),
);
return exporter.getFinishedSpans();
};

const operationNames = (spans: { attributes: Record<string, unknown> }[]) =>
spans.map(s => s.attributes['gen_ai.operation.name']).sort();

describe('AI SDK OpenTelemetry integration', () => {
it('stamps attribution onto every span of the call', async () => {
const spans = await runTracedCall({
sessionId: 'session-1',
teamId: 'team-1',
userId: 'user-1',
});

const operations = spans.map(s => s.attributes['gen_ai.operation.name']);
expect(operations).toEqual(
expect.arrayContaining(['chat', 'execute_tool']),
);
for (const span of spans) {
expect(span.attributes).toMatchObject({
'gen_ai.conversation.id': 'session-1',
'hyperdx.team.id': 'team-1',
'user.id': 'user-1',
});
}
});

it('omits the session attribute when only team and user are known', async () => {
// The chart assistant has no conversation-scoped id.
const spans = await runTracedCall({ teamId: 'team-1', userId: 'user-1' });

expect(spans.length).toBeGreaterThan(0);
for (const span of spans) {
expect(span.attributes).toMatchObject({
'hyperdx.team.id': 'team-1',
'user.id': 'user-1',
});
expect(span.attributes).not.toHaveProperty('gen_ai.conversation.id');
}
});

it('emits GenAI semconv attributes the LLM dashboard reads', async () => {
const spans = await runTracedCall({ sessionId: 'session-1' });

const chat = spans.find(
s => s.attributes['gen_ai.operation.name'] === 'chat',
);
expect(chat?.attributes).toMatchObject({
'gen_ai.provider.name': 'anthropic',
'gen_ai.request.model': 'mock-model',
'gen_ai.usage.input_tokens': 10,
'gen_ai.usage.output_tokens': 5,
});
expect(
spans.some(s => s.attributes['gen_ai.agent.name'] === 'test.fn'),
).toBe(true);

// Message content feeds the dashboard's Messages tab.
expect(chat?.attributes['gen_ai.input.messages']).toEqual(
expect.stringContaining('"content":"hi"'),
);
expect(chat?.attributes['gen_ai.output.messages']).toEqual(
expect.stringContaining('"name":"lookup"'),
);
const toolSpan = spans.find(
s => s.attributes['gen_ai.operation.name'] === 'execute_tool',
);
expect(toolSpan?.attributes).toMatchObject({
'gen_ai.tool.name': 'lookup',
'gen_ai.tool.call.arguments': expect.stringContaining('"q":"x"'),
});
});
});

describe('enrichLLMSpan', () => {
const enrich = (runtimeContext: Record<string, unknown> | undefined) =>
enrichLLMSpan({
spanType: 'languageModel',
operationId: 'ai.generateText',
callId: 'call-1',
runtimeContext,
});

it('skips missing, empty and non-string values', () => {
expect(enrich({ sessionId: '', teamId: 42, userId: undefined })).toEqual(
{},
);
expect(enrich(undefined)).toEqual({});
});

it('ignores unrelated runtime context keys', () => {
expect(enrich({ sessionId: 's1', other: 'x' })).toEqual({
'gen_ai.conversation.id': 's1',
});
});
});

describe('registerAITelemetry', () => {
afterAll(() => trace.disable());

it('emits each span once through the global tracer provider, even if registered twice', async () => {
const perCall = operationNames(
await runTracedCall({ sessionId: 'session-1' }),
);

const exporter = new InMemorySpanExporter();
trace.setGlobalTracerProvider(
new BasicTracerProvider({
spanProcessors: [new SimpleSpanProcessor(exporter)],
}),
);
registerAITelemetry();
registerAITelemetry();
await runToolCall(llmTelemetry({ sessionId: 'session-global' }));

const spans = exporter.getFinishedSpans();
expect(perCall.length).toBeGreaterThan(0);
expect(operationNames(spans)).toEqual(perCall);
for (const span of spans) {
expect(span.attributes['gen_ai.conversation.id']).toBe('session-global');
}
});
});
Loading
Loading