Migrate to Vercel AI SDK 7: a tool-calling guide

Authors
  • avatar
    Name
    Hamza Rahman
Published on
-
11 mins read

Upgrading a tool-calling app from Vercel AI SDK 6 to 7 takes more than running the codemod. You'll run it, move the tool context it leaves behind, and check a few result fields that change behavior without raising a type error.

If you haven't used tools in the SDK yet, start with the AI SDK tool calling example. It uses stepCountIs, which still works in v7 as a deprecated name for isStepCount.

Checked on December 4, 2026 against ai@7.1.0, ai@6.0.342 and @ai-sdk/codemod@4.0.4. The examples ran on Node.js 25.2.1 with the SDK's mock models, so the output below comes from the SDK rather than a paid model.

Before you upgrade

AI SDK 7.0.0 was published on June 25, 2026, and 7.1.0 on December 3, 2026 (npm). Two requirements apply to every app, according to the release announcement:

  • Node.js 22 or later. Check your CI images and serverless runtimes as well as your laptop.
  • ESM imports. The packages no longer ship CommonJS builds.

Plan to convert require('ai') to import. Recent Node versions can load ES modules through require(), so require('ai') still returns working exports on Node 22.23.5 and 25.2.1, but Vercel doesn't support it and you shouldn't rely on it.

If you are on v5, upgrade to v6 first, using the v6 guide. The codemods are grouped by major version, and the v7 set assumes v6 code.

Start from a clean commit, then upgrade every AI SDK package together:

npm install ai@7 @ai-sdk/openai@4 @ai-sdk/react@4
npx @ai-sdk/codemod v7
git diff
npx tsc --noEmit

Leave out @ai-sdk/react if you do not use it. Keep only the provider packages you need.

The v6 agent

This agent looks up an order and can issue a refund. Refunds above 50 need approval. model stands for any AI SDK model.

import { generateText, stepCountIs, tool } from 'ai'
import { z } from 'zod'
import { model } from './model.js'

const getOrder = tool({
  description: 'Look up an order by id.',
  inputSchema: z.object({ orderId: z.string() }),
  execute: async ({ orderId }, { experimental_context }) => {
    const { tenantId } = experimental_context as { tenantId: string }
    return { orderId, tenantId, status: 'shipped' }
  },
})

const refundOrder = tool({
  description: 'Refund an order.',
  inputSchema: z.object({ orderId: z.string(), amount: z.number() }),
  needsApproval: async ({ amount }) => amount > 50,
  execute: async ({ orderId, amount }) => ({ orderId, refunded: amount }),
})

const result = await generateText({
  model,
  system: 'You are a support agent.',
  prompt: 'Where is order A-17?',
  tools: { getOrder, refundOrder },
  stopWhen: stepCountIs(5),
  experimental_context: { tenantId: 'acme', requestId: 'req-1' },
  onStepFinish: ({ stepNumber }) => console.log('step', stepNumber),
})

console.log(result.text)
console.log('usage', result.usage.totalTokens)
console.log('totalUsage', result.totalUsage.totalTokens)
console.log('toolCalls', result.toolCalls.length)

What the codemod changes

On that file, the codemod made these edits:

stepCountIs              -> isStepCount
system                   -> instructions
onStepFinish             -> onStepEnd
{ experimental_context } -> { context: experimental_context }   (inside execute)

It leaves needsApproval, totalUsage and the top-level experimental_context option alone. needsApproval and totalUsage are deprecated but still work. The experimental_context option doesn't.

npx tsc --noEmit reports the unknown experimental_context option, but plain JavaScript gets no such warning. Running the unmodified v6 code on v7 finishes normally, prints the model's answer, and hides this inside the first step:

tool-error Cannot destructure property 'tenantId' of 'experimental_context' as it is undefined.

Because tool exceptions become tool-error parts and go back to the model, a broken tool can look like a normal run if you only check result.text. Assert on result.content in at least one test so those errors surface.

Watch where you run the codemod, because it ignores paths that contain a dot directory. Run under a folder inside ~/.cache, it reported v7 codemods complete and changed nothing, while the same files in a normal directory were converted. If your checkout is in something like .worktrees/, check git diff to confirm the edits happened.

The v7 agent

Here's the same agent on v7. The old experimental_context is split into toolsContext and runtimeContext, needsApproval becomes toolApproval on the call, and result.content is checked for tool-error parts:

import { generateText, isStepCount, tool } from 'ai'
import { z } from 'zod'
import { model } from './model.js'

const getOrder = tool({
  description: 'Look up an order by id.',
  inputSchema: z.object({ orderId: z.string() }),
  contextSchema: z.object({ tenantId: z.string() }),
  execute: async ({ orderId }, { context: { tenantId } }) => {
    return { orderId, tenantId, status: 'shipped' }
  },
})

const refundOrder = tool({
  description: 'Refund an order.',
  inputSchema: z.object({ orderId: z.string(), amount: z.number() }),
  execute: async ({ orderId, amount }) => ({ orderId, refunded: amount }),
})

const result = await generateText({
  model,
  instructions: 'You are a support agent.',
  prompt: 'Where is order A-17?',
  tools: { getOrder, refundOrder },
  toolsContext: { getOrder: { tenantId: 'acme' } },
  runtimeContext: { requestId: 'req-1' },
  toolApproval: {
    refundOrder: ({ amount }) => (amount > 50 ? 'user-approval' : undefined),
  },
  stopWhen: isStepCount(5),
  onStepEnd: ({ stepNumber }) => console.log('step', stepNumber),
})

const toolErrors = result.content.filter((part) => part.type === 'tool-error')
if (toolErrors.length > 0) console.error('tool errors', toolErrors)

console.log(result.text)
console.log('final step usage', result.finalStep.usage.totalTokens)
console.log('total usage', result.usage.totalTokens)
console.log('toolCalls', result.toolCalls.length)

The old shared context object is now two things. toolsContext holds values for one named tool, typed by that tool's contextSchema. runtimeContext holds request state for prepareStep and lifecycle events. A tool only receives its own entry, so a third-party tool cannot read another tool's API key from the context.

Approval policy moved from the tool to the call, so the same tool can have different rules per route. Requiring approval doesn't pause the call. generateText returns a tool-approval-request part without running the refund, and you call it again with a tool-approval-response message.

Suppose the agent above ran with the prompt Refund 80 on order A-17. and the model asked for the refund. This is the second call, with the same tools and policy:

import type { ModelMessage, ToolApprovalResponse } from 'ai'

const approvals: ToolApprovalResponse[] = []
for (const part of result.content) {
  if (part.type === 'tool-approval-request' && !part.isAutomatic) {
    // Replace true with the user's decision.
    approvals.push({ type: 'tool-approval-response', approvalId: part.approvalId, approved: true })
  }
}

const messages: ModelMessage[] = [
  { role: 'user', content: 'Refund 80 on order A-17.' },
  ...result.responseMessages,
  { role: 'tool', content: approvals },
]

const final = await generateText({
  model,
  instructions: 'You are a support agent.',
  messages,
  tools: { getOrder, refundOrder },
  toolsContext: { getOrder: { tenantId: 'acme' } },
  toolApproval: {
    refundOrder: ({ amount }) => (amount > 50 ? 'user-approval' : undefined),
  },
  stopWhen: isStepCount(5),
})

With a mock model, the refund executes only on this second call. The tool approval docs cover denials and the useChat version.

Changes that compile but behave differently

You'll have to search for these by hand. The same two-step mock run gives:

Valuev6v7
result.usage.totalTokens160280
result.totalUsage.totalTokens280280
result.toolCalls.length01
Last step's response.messages.length31

In v6, the top-level usage, toolCalls, toolResults, content, files, sources and warnings described only the final step. In v7 they cover every step, and result.finalStep holds the old meaning. If you bill from usage or add up steps yourself, check that code first.

step.response.messages no longer accumulates earlier steps. Use result.responseMessages when you save a conversation, because code that saves the last step's messages will now silently drop the earlier tool calls.

Other changes from the official migration guide that affect tool apps:

  • A system message inside prompt or messages now throws AI_InvalidPromptError. Move it to instructions. Only set allowSystemInMessages: true for history that users cannot edit.
  • instructions and messages returned from prepareStep carry into later steps. In v6 they applied to one step.
  • Request bodies are left out of results by default, and so are response bodies for generateText. Opt in with include.
  • OpenTelemetry moved to @ai-sdk/otel. Install it with npm install @ai-sdk/otel and register it once with registerTelemetry(new OpenTelemetry()). After that, telemetry is on for every call unless you turn it off, so review what your prompts contain.
  • The @ai-sdk/mcp HTTP transports reject redirects by default.
  • fullStream is now stream. The old name works for now.
  • Response methods such as toUIMessageStreamResponse() are deprecated in favor of standalone helpers. They also work for now.

With the standalone helpers, a route handler looks like this:

import { createUIMessageStreamResponse, toUIMessageStream } from 'ai'

return createUIMessageStreamResponse({
  stream: toUIMessageStream({ stream: result.stream }),
})

New features worth adopting

Some of these arrived in 7.0.x releases after launch. The package changelog gives the exact versions noted here. The snippets below are partial. They continue from the agent's imports and model, and getWeather, writeFile and readFile stand for your own tools.

Use toolSearch(), added in 7.0.104, when you have so many tools that their definitions crowd the prompt. Mark them with deferLoading:

import { generateText, isStepCount, tool, toolSearch } from 'ai'
import { z } from 'zod'

const refundOrder = tool({
  deferLoading: true,
  description: 'Refund an order.',
  inputSchema: z.object({ orderId: z.string() }),
  execute: async ({ orderId }) => ({ refunded: orderId }),
})

const result = await generateText({
  model,
  tools: { search: toolSearch({ maxResults: 3 }), refundOrder, getWeather },
  stopWhen: isStepCount(5),
  prompt: 'Refund order A-17.',
})

With getWeather also deferred, the mock model sees only search in step one, then search and refundOrder. Each search costs a step, and changing the tool list can invalidate the provider's cached prompt, so skip it if you only have five tools.

Tool concurrency and timeouts

Tool calls in one step run concurrently by default, which is wrong when a later call reads what an earlier call wrote. Set toolCallConcurrency, added in 7.0.140, to run them in order:

const result = await generateText({
  model,
  tools: { writeFile, readFile },
  toolCallConcurrency: 1,
  timeout: { toolMs: 10_000, totalMs: 60_000 },
  stopWhen: isStepCount(5),
  prompt: 'Update the file, then read it.',
})

With a slow write and a fast read, the default starts both calls at once, so the read finishes before the write does. With 1, the write finishes before the read starts, and a higher number is an easy way to protect a small database pool. For streams, firstChunkMs also catches a connection that opens but never produces content.

Stream retries

maxRetries covers failures while a call is starting. streamRetries, added in 7.0.91, covers provider error events after the stream has begun:

import { streamText } from 'ai'

const result = streamText({
  model,
  prompt: 'Summarize this order history.',
  streamRetries: 2,
})

Only the failed step reruns, so completed tool calls from earlier steps aren't repeated. Text that already reached the reader stays there, though. When a mock stream fails after Hel and the retry succeeds with Hello world, the collected textStream is HelHello world, while await result.text is Hello world. Save result.text, and decide how your UI replaces partial output before turning this on.

Features to leave for later

WebSocketChatTransport (7.0.135) keeps useChat on one WebSocket. It needs a server that can hold the connection open. Harness adapters let HarnessAgent drive existing coding agents. Both are useful for specific products, but neither belongs in a routine upgrade.

Before you deploy

Search your code for usage, toolCalls, response.messages, experimental_context and prepareStep, then run one multi-step conversation and compare the saved messages with the v6 output.

For typed final answers, see structured outputs with Zod.

References