Track Vercel AI SDK costs and calls in Next.js
Add Sentry to your Next.js app to see Vercel AI SDK token usage, LLM costs, tool calls, and agent traces with full-stack trace context. Spot which models drive spend without leaving Sentry.
Before you start
SDKs & packages
- A Next.js 14+ app (App Router recommended) with Sentry set up, on
@sentry/nextjs11 or later. If Sentry isn't set up yet, follow the Next.js setup guide first - Vercel AI SDK installed (
aipackage) - Node.js 22+ if you're on AI SDK 7
Accounts & access
- Sentry account with a Next.js project created
Knowledge
- Basic familiarity with Next.js API routes or Route Handlers
- Basic understanding of the Vercel AI SDK (
streamText,generateText)
1 Enable tracing
Open sentry.server.config.ts and make sure tracesSampleRate is greater than zero. In Sentry JavaScript SDK v11, vercelAIIntegration is enabled by default once tracing is on, so you don't need to add it yourself. Add it to integrations only if you want to change its options, like turning off input and output recording.
sentry.server.config.tsimport * as Sentry from '@sentry/nextjs';
Sentry.init({
dsn: process.env.SENTRY_DSN,
// Tracing must be on. vercelAIIntegration is enabled by default.
tracesSampleRate: 1.0,
}); 2 Name your AI SDK calls and set a conversation ID
In any Route Handler that uses the Vercel AI SDK, add a functionId to the telemetry option of your streamText or generateText call. Sentry uses it as the agent name, so you can find and filter each agent in Explore → Agents. On AI SDK 6 and earlier, the option is called experimental_telemetry.
Then call Sentry.setConversationId() with the chat ID. useChat sends the same id with each message of a chat, and Sentry uses it to group all turns of that chat into one conversation.
Sentry records the full prompts and completions by default. To turn this off for one route, set recordInputs and recordOutputs to false in that call's telemetry option. Keep these routes on the Node.js runtime, because Sentry doesn't instrument AI calls on the Edge runtime.
app/api/chat/route.tsimport * as Sentry from '@sentry/nextjs';
import { convertToModelMessages, streamText, type UIMessage } from 'ai';
import { openai } from '@ai-sdk/openai';
export async function POST(req: Request) {
// useChat sends the same chat id with every turn
const { id, messages }: { id: string; messages: UIMessage[] } = await req.json();
// Groups all turns of this chat into one conversation in Sentry
Sentry.setConversationId(id);
const result = streamText({
model: openai('gpt-5-mini'),
messages: await convertToModelMessages(messages),
telemetry: {
functionId: 'chat-route', // shows up as the agent name in Sentry
},
});
return result.toUIMessageStreamResponse();
} 3 Find your conversations in Sentry
Chat with your app a few times, then open Explore → Agents in Sentry. The charts at the top show estimated cost split by model, agent runs, and tool calls over time.
The Conversations tab lists each chat with its timespan, number of messages, errors, cost, and the tools it called. Search by user, model, or message to find a specific chat. The Traces tab shows single agent runs, and the LLM Calls tab shows each model request with its tokens and cost.
Conversations documentation
4 Read a conversation turn by turn
Click a conversation to open it. The header shows the totals for the whole chat: LLM calls, errors, tokens, and cost. The Transcript tab shows each user message, each tool call with its inputs, and each agent reply with its cost and duration. A failed tool call shows in red, so you can see which turn broke and what the agent told the user. The Timeline tab shows when each step ran and how long it took.
How Sentry calculates model costs
5 Drill into the full trace
Click the trace link in the conversation header to open the trace. The Agent Activity tab shows each LLM call and tool call in order, with tokens, cost, and duration. Select a call to see its model, prompt, and output.
Switch to the Waterfall tab to see the entire request lifecycle, from the page load or API call all the way down to each LLM request and tool execution. This gives you the full-stack context to understand whether a slow tool call is a database issue, a network problem, or an AI provider timeout.
Trace Explorer documentation
That's it.
You know exactly what your agents cost.
Every token, tool call, and model request shows up in Sentry with full trace context, so you can optimize cost and debug performance without switching tabs.
- Configured Sentry tracing in your Next.js app
- Turned on automatic LLM instrumentation with the Vercel AI integration
- Named your AI SDK calls and grouped the turns of each chat into one conversation
- Found the cost, tool calls, and errors of each conversation in Explore → Agents
- Read a conversation turn by turn and followed it into the full trace
Pro tips
- 💡 Use a meaningful
functionIdfor eachstreamTextorgenerateTextcall (for example'chat-route'or'summarize-document'). It becomes the agent name in Sentry and makes runs much easier to filter. - 💡 Set
tracesSampleRateto a lower value like0.2in production to reduce volume, then raise it temporarily when debugging a specific issue. - 💡 To compare cost and token types (input, cached input, output, and reasoning) by model, open the prebuilt AI Agents Model Details dashboard from Dashboards.
- 💡 Tool calls that hit your database appear as child spans inside the agent trace. If a tool is slow, check whether the database span is the actual bottleneck.
Common pitfalls
- ⚠️ Forgetting to set
tracesSampleRategreater than zero. AI spans are only captured when tracing is active. - ⚠️ Running AI calls on the Edge runtime. In SDK v11,
vercelAIIntegrationrelies on diagnostics channels, which Edge doesn't support, so those routes send no AI spans. Keep AI routes on the Node.js runtime. - ⚠️ Calling the AI SDK's
registerTelemetryalongside Sentry.vercelAIIntegrationalready instruments the AI SDK, so registering telemetry separately gives you duplicate spans. - ⚠️ Not wrapping tool calls in Sentry spans. If your agent calls external APIs or runs database queries as tools, they won't appear in the trace unless instrumented. Use the Sentry SDK or auto-instrumented libraries so tool performance shows up alongside your LLM spans.
- ⚠️ Miscounting cached tokens in manual instrumentation.
gen_ai.usage.input_tokensshould be the total including cached tokens, with the cached portion reported separately asgen_ai.usage.cache_read.input_tokens. Reporting only the non-cached portion causes Sentry to calculate negative costs. - ⚠️ Forgetting that prompts are captured by default. Opt out per call with
telemetry: { recordInputs: false, recordOutputs: false }, or for the whole app withdataCollection.genAI. Setting these options onvercelAIIntegration()overrides every per-call setting.
Frequently asked questions
gen_ai.chat operation.telemetry option and functionId naming in this recipe are specific to the Vercel AI SDK.tracesSampleRate to control exactly how many traces you send.recordInputs: false and recordOutputs: false in that call's telemetry option. To turn it off for the whole app, use dataCollection: { genAI: { inputs: false, outputs: false } } in Sentry.init(). Sentry then captures only metadata like token counts and model names.What's next?
Fix it, don't observe it.
Get started with the only application monitoring platform that empowers developers to fix application problems without compromising on velocity.