Skip to content

Commit 0ec2ca7

Browse files
authored
chore(deps): migrate to AI SDK 7 (#972)
Bump ai to 7.0.66 and the provider packages to their v7 lines. AI SDK 7 no longer emits OpenTelemetry spans from the core package, so Langfuse tracing goes silent unless a telemetry integration is registered. Register LangfuseVercelAiSdkIntegration in instrumentation and keep the existing span processor as the exporter. telemetry.metadata was removed from TelemetryOptions. The per-observation metadata now goes through runtimeContext and is allowlisted with telemetry.includeRuntimeContext. Other required changes: system becomes instructions, stepCountIs becomes isStepCount, onStepFinish and onFinish become onStepEnd and onEnd on the stream helpers (useChat keeps onFinish), and ToolExecutionOptions now requires context.
1 parent 989a056 commit 0ec2ca7

17 files changed

Lines changed: 190 additions & 79 deletions

‎bun.lock‎

Lines changed: 46 additions & 28 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎components/chat.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -209,7 +209,7 @@ export function Chat({
209209
toast.error(publicError.error)
210210
}
211211
},
212-
experimental_throttle: 100,
212+
throttle: 100,
213213
generateId
214214
})
215215

‎instrumentation.test.ts‎

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { describe, expect, it, vi } from 'vitest'
1+
import { afterEach, describe, expect, it, vi } from 'vitest'
22

33
// Mock the modules before any imports
44
vi.mock('@langfuse/otel', () => ({
@@ -7,14 +7,33 @@ vi.mock('@langfuse/otel', () => ({
77
vi.mock('@vercel/otel', () => ({
88
registerOTel: vi.fn()
99
}))
10+
vi.mock('@langfuse/vercel-ai-sdk', () => ({
11+
LangfuseVercelAiSdkIntegration: vi.fn()
12+
}))
13+
vi.mock('ai', async importOriginal => ({
14+
...(await importOriginal<typeof import('ai')>()),
15+
registerTelemetry: vi.fn()
16+
}))
1017

1118
// Import after mocking
1219
import { LangfuseSpanProcessor } from '@langfuse/otel'
20+
import { LangfuseVercelAiSdkIntegration } from '@langfuse/vercel-ai-sdk'
1321
import { registerOTel } from '@vercel/otel'
22+
import { registerTelemetry } from 'ai'
1423

1524
import { langfuseSpanProcessor, register } from './instrumentation'
1625

26+
const originalTracingFlag = process.env.ENABLE_LANGFUSE_TRACING
27+
1728
describe('instrumentation', () => {
29+
afterEach(() => {
30+
if (originalTracingFlag === undefined) {
31+
delete process.env.ENABLE_LANGFUSE_TRACING
32+
} else {
33+
process.env.ENABLE_LANGFUSE_TRACING = originalTracingFlag
34+
}
35+
})
36+
1837
it('exports a shared LangfuseSpanProcessor instance for force-flushing', () => {
1938
expect(LangfuseSpanProcessor).toHaveBeenCalledTimes(1)
2039
expect(langfuseSpanProcessor).toBeInstanceOf(LangfuseSpanProcessor)
@@ -30,4 +49,32 @@ describe('instrumentation', () => {
3049
spanProcessors: [langfuseSpanProcessor]
3150
})
3251
})
52+
53+
it('registers the AI SDK telemetry integration once when tracing is enabled', async () => {
54+
delete process.env.OLLAMA_BASE_URL
55+
process.env.ENABLE_LANGFUSE_TRACING = 'true'
56+
vi.mocked(LangfuseVercelAiSdkIntegration).mockClear()
57+
vi.mocked(registerTelemetry).mockClear()
58+
vi.resetModules()
59+
60+
// Fresh module so the registered-once guard starts from its initial state
61+
const instrumentation = await import('./instrumentation')
62+
await instrumentation.register()
63+
await instrumentation.register()
64+
65+
expect(LangfuseVercelAiSdkIntegration).toHaveBeenCalledTimes(1)
66+
expect(registerTelemetry).toHaveBeenCalledTimes(1)
67+
})
68+
69+
it('skips the telemetry integration when tracing is disabled', async () => {
70+
delete process.env.OLLAMA_BASE_URL
71+
delete process.env.ENABLE_LANGFUSE_TRACING
72+
vi.mocked(registerTelemetry).mockClear()
73+
vi.resetModules()
74+
75+
const instrumentation = await import('./instrumentation')
76+
await instrumentation.register()
77+
78+
expect(registerTelemetry).not.toHaveBeenCalled()
79+
})
3380
})

‎instrumentation.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,31 @@
11
import { LangfuseSpanProcessor } from '@langfuse/otel'
2+
import { LangfuseVercelAiSdkIntegration } from '@langfuse/vercel-ai-sdk'
23
import { registerOTel } from '@vercel/otel'
4+
import { registerTelemetry } from 'ai'
5+
6+
import { isTracingEnabled } from '@/lib/utils/telemetry'
37

48
// Exported so request handlers can force-flush pending spans before the
59
// serverless function exits
610
export const langfuseSpanProcessor = new LangfuseSpanProcessor()
711

12+
// registerTelemetry appends without deduping, so a second register() would
13+
// double every span.
14+
let telemetryRegistered = false
15+
816
export async function register() {
917
registerOTel({
1018
serviceName: 'morphic-ai-search',
1119
spanProcessors: [langfuseSpanProcessor]
1220
})
1321

22+
// The AI SDK emits no spans until a telemetry integration is registered.
23+
// The integration creates the spans, the processor above exports them.
24+
if (isTracingEnabled() && !telemetryRegistered) {
25+
registerTelemetry(new LangfuseVercelAiSdkIntegration())
26+
telemetryRegistered = true
27+
}
28+
1429
// Initialize Ollama validation on server startup (only when configured)
1530
if (process.env.OLLAMA_BASE_URL) {
1631
const { initializeOllamaValidation } = await import(

‎lib/agents/__tests__/researcher.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ const mocks = vi.hoisted(() => ({
77
}))
88

99
vi.mock('ai', () => ({
10-
stepCountIs: vi.fn(),
10+
isStepCount: vi.fn(),
1111
tool: vi.fn(options => options),
1212
ToolLoopAgent: vi.fn(function (
1313
this: { tools: unknown },

‎lib/agents/researcher.ts‎

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
1-
import { stepCountIs, tool, ToolLoopAgent } from 'ai'
1+
import { isStepCount, tool, ToolLoopAgent } from 'ai'
22

3-
import type { ResearcherTools } from '@/lib/types/agent'
3+
import type {
4+
ResearcherRuntimeContext,
5+
ResearcherTools
6+
} from '@/lib/types/agent'
47
import { type Model } from '@/lib/types/models'
58

69
import { fetchTool } from '../tools/fetch'
@@ -142,16 +145,21 @@ export function createResearcher({
142145
instructions: `${systemPrompt}\nCurrent date: ${currentDate}`,
143146
tools,
144147
activeTools: activeToolsList,
145-
stopWhen: stepCountIs(maxSteps),
148+
stopWhen: isStepCount(maxSteps),
146149
...(providerOptions && { providerOptions }),
150+
runtimeContext: {
151+
modelId: model,
152+
agentType: 'researcher',
153+
searchMode
154+
} satisfies ResearcherRuntimeContext,
147155
// Spans join the parent Langfuse trace via OTel context propagation
148-
experimental_telemetry: {
156+
telemetry: {
149157
isEnabled: isTracingEnabled(),
150158
functionId: 'research-agent',
151-
metadata: {
152-
modelId: model,
153-
agentType: 'researcher',
154-
searchMode
159+
includeRuntimeContext: {
160+
modelId: true,
161+
agentType: true,
162+
searchMode: true
155163
}
156164
}
157165
})
@@ -165,7 +173,7 @@ export function createResearcher({
165173

166174
// Helper function to access agent tools
167175
export function getResearcherTools(
168-
agent: ToolLoopAgent<never, ResearcherTools, never>
176+
agent: ToolLoopAgent<never, ResearcherTools, ResearcherRuntimeContext>
169177
): ResearcherTools {
170178
return agent.tools
171179
}

‎lib/agents/title-generator.ts‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -40,18 +40,23 @@ export async function generateChatTitle({
4040

4141
const { text: generatedTitle } = await generateText({
4242
model: getModel(modelId),
43-
system: systemPrompt,
43+
instructions: systemPrompt,
4444
prompt: userMessageContent,
4545
abortSignal,
4646
providerOptions: getTitleProviderOptions(modelId),
47+
runtimeContext: {
48+
modelId,
49+
agentType: 'title-generator',
50+
promptLength: userMessageContent.length
51+
},
4752
// Spans join the parent Langfuse trace via OTel context propagation
48-
experimental_telemetry: {
53+
telemetry: {
4954
isEnabled: isTracingEnabled(),
5055
functionId: 'title-generation',
51-
metadata: {
52-
modelId: modelId,
53-
agentType: 'title-generator',
54-
promptLength: userMessageContent.length
56+
includeRuntimeContext: {
57+
modelId: true,
58+
agentType: true,
59+
promptLength: true
5560
}
5661
}
5762
})

‎lib/render/__tests__/llm-image-output.e2e.test.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
*
1010
* RUN_LLM_E2E=1 OPENAI_API_KEY=sk-... bun run test llm-image-output.e2e
1111
*/
12-
import { generateText, stepCountIs, tool } from 'ai'
12+
import { generateText, isStepCount, tool } from 'ai'
1313
import { describe, expect, test } from 'vitest'
1414
import { z } from 'zod'
1515

@@ -86,11 +86,11 @@ describe.skipIf(!RUN)('LLM inline image output (E2E)', () => {
8686
test('LLM emits inline image spec block using search tool images', async () => {
8787
const { text } = await generateText({
8888
model: getModel(MODEL),
89-
system: getAdaptiveModePrompt(),
89+
instructions: getAdaptiveModePrompt(),
9090
tools: {
9191
search: createMockSearchTool()
9292
},
93-
stopWhen: stepCountIs(6),
93+
stopWhen: isStepCount(6),
9494
prompt:
9595
'Show me photos of Mount Fuji and a brief description. Please include relevant images inline.'
9696
})

‎lib/render/__tests__/llm-related-questions.e2e.test.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
*
99
* RUN_LLM_E2E=1 OPENAI_API_KEY=sk-... bun run test llm-related-questions.e2e
1010
*/
11-
import { generateText, stepCountIs, tool } from 'ai'
11+
import { generateText, isStepCount, tool } from 'ai'
1212
import { describe, expect, test } from 'vitest'
1313
import { z } from 'zod'
1414

@@ -100,11 +100,11 @@ function findRelatedBlocks(markdown: string): SpecElement[][] {
100100
async function generateAnswer(prompt: string): Promise<string> {
101101
const { text } = await generateText({
102102
model: getModel(MODEL),
103-
system: getAdaptiveModePrompt(),
103+
instructions: getAdaptiveModePrompt(),
104104
tools: {
105105
search: createMockSearchTool()
106106
},
107-
stopWhen: stepCountIs(6),
107+
stopWhen: isStepCount(6),
108108
providerOptions: PROVIDER_OPTIONS,
109109
prompt
110110
})

‎lib/streaming/__tests__/create-chat-stream-response.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ type StreamOptions = {
7676
}
7777

7878
type UIMessageStreamResponseOptions = {
79-
onFinish: (event: {
79+
onEnd: (event: {
8080
responseMessage: {
8181
id: string
8282
role: 'assistant'
@@ -91,7 +91,7 @@ function createFakeResult(isAborted = false) {
9191
consumeStream: vi.fn(),
9292
toUIMessageStreamResponse: vi.fn(
9393
(options: UIMessageStreamResponseOptions) => {
94-
mocks.finishPromise = options.onFinish({
94+
mocks.finishPromise = options.onEnd({
9595
responseMessage: {
9696
id: 'response-id',
9797
role: 'assistant',

0 commit comments

Comments
 (0)