Suryanand/ Bootcamp
suryanand.com ↗Let's talk
← FrameworksAI guideBeginner#frameworks#typescript#vercel-ai-sdk#nextjs
Frame · ai-engineering / frameworks / 10-vercel-ai-sdk.mdGuide 046 / 103

Vercel AI SDK for TypeScript apps

The AI SDK from Vercel is the default toolkit for LLM features in TypeScript, especially in Next.js and React apps. It does three jobs well: a single API across model providers (generateText, streamText and friends), a tool calling agent abstraction (ToolLoopAgent), and UI hooks (useChat) that stream messages, tool calls and approvals into your components. As of October 2026 the ai package is on major version 7. If you are building a web product in TypeScript, this is where I would start.

Why it matters

Building chat UIs by hand is surprisingly fiddly. You need server sent events, partial message rendering, tool call states ("calling", "done", "error"), aborts, retries, and a message format that survives a page reload. Each provider streams differently. The AI SDK hides those differences:

  • AI SDK Core (ai): generateText and streamText for text and tool calls, structured output, embeddings, image and speech generation, with providers as plug-ins (@ai-sdk/openai, @ai-sdk/anthropic, @ai-sdk/google and many more) or plain model id strings routed through the Vercel AI Gateway.
  • Agents: ToolLoopAgent bundles a model, instructions and tools into a reusable object that runs the tool calling loop for you. By default an agent runs for up to 20 steps; stopWhen changes that.
  • AI SDK UI (@ai-sdk/react and siblings for Vue, Svelte and Angular): useChat manages messages, status and streaming on the client, including tool approvals.

It is not tied to Vercel hosting. It runs anywhere Node, Bun, Deno or edge runtimes run.

How it works

The core idea is the step. Each step is one model call. If the model asks for tools, the SDK runs their execute functions, appends results and starts another step, until a stop condition is met or the model answers.

Rendering diagram…

Stop conditions such as isStepCount(n) are composable, and prepareStep lets you change the model, tools or messages between steps (for example, switching to a cheaper model after the first step). Tools are defined with tool() and a Zod (or JSON) inputSchema, so input types flow into execute and onward into the UI.

Reference architecture

The usual Next.js shape: the agent lives in a server module, a route handler streams it, and a client component renders the stream with useChat.

Rendering diagram…

Because tools run on the server, secrets and database access stay on the server. The client only sees the message parts you choose to stream.

Code

An order support agent, its route handler, and the client component. Names match the v7 type declarations (ToolLoopAgent, tool, isStepCount, createAgentUIStreamResponse, useChat).

// lib/support-agent.ts
import { ToolLoopAgent, isStepCount, tool } from "ai";
import { z } from "zod";

export const supportAgent = new ToolLoopAgent({
  model: "openai/gpt-5.4-mini", // AI Gateway model id, or a provider instance
  instructions: "You help customers with orders. Use tools; never guess statuses.",
  tools: {
    lookupOrder: tool({
      description: "Look up an order by its id",
      inputSchema: z.object({ orderId: z.string() }),
      execute: async ({ orderId }) => {
        // Query your database here
        return { orderId, status: "shipped", eta: "2 days" };
      },
    }),
  },
  stopWhen: isStepCount(8),
});
// app/api/chat/route.ts
import { createAgentUIStreamResponse } from "ai";
import { supportAgent } from "@/lib/support-agent";

export async function POST(req: Request) {
  const { messages } = await req.json();
  return createAgentUIStreamResponse({ agent: supportAgent, uiMessages: messages });
}
// app/chat.tsx
"use client";
import { useChat } from "@ai-sdk/react";
import { useState } from "react";

export function Chat() {
  const { messages, sendMessage, status } = useChat();
  const [input, setInput] = useState("");

  return (
    <div>
      {messages.map((m) => (
        <div key={m.id}>
          <b>{m.role}:</b>{" "}
          {m.parts.map((part, i) =>
            part.type === "text" ? <span key={i}>{part.text}</span> : null
          )}
        </div>
      ))}
      <form
        onSubmit={(e) => {
          e.preventDefault();
          sendMessage({ text: input });
          setInput("");
        }}
      >
        <input value={input} onChange={(e) => setInput(e.target.value)} />
        <button disabled={status !== "ready"}>Send</button>
      </form>
    </div>
  );
}

Outside a UI you can call the same agent directly: await supportAgent.generate({ prompt: "Where is order 1042?" }) returns a result with .text, and supportAgent.stream(...) gives you a textStream to iterate.

Trade-offs and pitfalls

  • Major versions move. The SDK has had several majors in a short time, with renamed APIs along the way (for example stepCountIs is now an alias of isStepCount). Tutorials from older versions will not compile. Pin ai and @ai-sdk/* packages together and use the official migration guides.
  • Messages have parts. UI messages are lists of typed parts (text, tool calls, reasoning, files). Render parts, not a single content string, or you will drop tool output.
  • It is not a workflow engine. There is no built-in durable checkpointing across hours or days. For long running jobs, put the agent inside a queue or workflow system, or pair it with Mastra or a backend agent service.
  • Serverless timeouts. Multi step agents can exceed function time limits. Keep step counts bounded and configure route timeouts.
  • Default step limit. The default of 20 steps can be too many for cost sensitive paths. Set stopWhen explicitly.
  • Validate tool inputs server side anyway. The schema helps, but treat tool inputs like any untrusted request body.

When to pick it: TypeScript web apps, Next.js or React chat and assistant UIs, products that need streaming tool states and approvals in the UI, and teams that want to switch providers with a string change.

When not to: Python backends (pick a Python framework), heavy RAG ingestion pipelines (LlamaIndex fits better), or long running, durable, multi agent workflows where you want an explicit graph runtime.

Checklist

  • Keep agents and tools in server only modules.
  • Set stopWhen explicitly on every agent.
  • Define every tool with a precise inputSchema and description.
  • Render message parts, including tool call states, in the UI.
  • Require approval in the UI for tools with side effects.
  • Pin ai and provider packages to the same release train.
  • Add telemetry or tracing before launch to see steps and token use.

Further reading

Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.