Sponsored Content
Skip to content
Docs

Build AI agents

Build TypeScript agents and AI applications with one API for models, tools, structured output, and streaming across Next.js, Vue, Svelte, Node.js, and other frameworks.
agent.ts
import { ToolLoopAgent, tool } from 'ai';
import { z } from 'zod';
 
const agent = new ToolLoopAgent({
  model: 'anthropic/claude-fable-5.1',
  tools: {
    getWeather: tool({
      description: 'Get the current weather for a location',
      inputSchema: z.object({ location: z.string() }),
      execute: async ({ location }) => ({
        location,
        temperature: 72,
        condition: 'sunny',
      }),
    }),
  },
});
 
const { text } = await agent.generate({
  prompt: "What's the weather in Tokyo?",
});
 
console.log(text);
index.ts
import { generateText } from 'ai';
 
const { text } = await generateText({
  model: 'openai/gpt-6-astra',
  prompt: 'Explain quantum entanglement in one paragraph.',
});
 
console.log(text);
classify.ts
import { generateObject } from 'ai';
import { z } from 'zod';
 
const { object } = await generateObject({
  model: 'openai/gpt-6-astra',
  schema: z.object({
    sentiment: z.enum(['positive', 'neutral', 'negative']),
  }),
  prompt: 'Classify the sentiment: I love this product.',
});
 
console.log(object);
  • Unified provider API. Switch between models by changing two lines of code
  • Structured outputs. Generate type-safe JSON with generateObject and streamObject
  • Tool calling. Let models interact with external systems
  • Streaming first. Stream text, objects, and UI to your frontend
  • Framework support. Works with React, Next.js, Vue, Svelte, and Node.js

At the center of the AI SDK is AI SDK Core, which provides a unified API to call any LLM.

The following example shows how to generate text with the AI SDK using OpenAI's GPT-6 Astra:

import { generateText } from 'ai';
 
const { text } = await generateText({
  model: 'openai/gpt-6-astra',
  prompt: 'Explain the concept of quantum entanglement.',
});

The unified interface lets you switch providers by changing the model string. For example, to use Anthropic's Claude Fable 5.1:

import { generateText } from 'ai';
 
const { text } = await generateText({
  model: 'anthropic/claude-fable-5.1',
  prompt: 'How many people will live in the world in 2040?',
});

While text generation can be useful, you might want to generate structured JSON data. For example, you might want to extract information from text, classify data, or generate synthetic data. AI SDK Core provides two functions (generateObject and streamObject) to generate structured data, allowing you to constrain model outputs to a specific schema.

The following example shows how to generate a type-safe recipe that conforms to a zod schema:

import { generateObject } from 'ai';
import { z } from 'zod';
 
const { object } = await generateObject({
  model: 'openai/gpt-6-astra',
  schema: z.object({
    recipe: z.object({
      name: z.string(),
      ingredients: z.array(z.object({ name: z.string(), amount: z.string() })),
      steps: z.array(z.string()),
    }),
  }),
  prompt: 'Generate a lasagna recipe.',
});

The AI SDK supports tool calling out of the box, allowing it to interact with external systems and perform discrete tasks. The following example shows how to use tool calling with the AI SDK:

import { generateText, tool } from 'ai';
import { z } from 'zod';
 
const { text } = await generateText({
  model: 'openai/gpt-6-astra',
  prompt: 'What is the weather like today in San Francisco?',
  tools: {
    getWeather: tool({
      description: 'Get the weather in a location',
      inputSchema: z.object({
        location: z.string().describe('The location to get the weather for'),
      }),
      execute: async ({ location }) => ({
        location,
        temperature: 72 + Math.floor(Math.random() * 21) - 10,
      }),
    }),
  },
});

You can also pass tools that a library provides. For example, the @github-tools/sdk package from GitHub Tools returns AI SDK tools for repositories, issues, and pull requests. A preset selects the tools for one job, and the tools read their token from GITHUB_TOKEN:

import { createGithubTools } from '@github-tools/sdk';
import { generateText, stepCountIs } from 'ai';
 
const { text } = await generateText({
  model: 'openai/gpt-6-astra',
  prompt: 'Summarize the last five merged pull requests on vercel/ai.',
  tools: createGithubTools({ preset: 'repo-explorer' }),
  stopWhen: stepCountIs(10),
});

Presets that include write tools, such as issue-triage, request approval before a write runs. Your application answers those requests through the AI SDK's tool approval flow.

The AI SDK is available as a package. To install it, run the following command:

Terminal
pnpm i ai
Terminal
yarn add ai
Terminal
npm i ai
Terminal
bun add ai

See the AI SDK Getting Started guide for more information on how to get started with the AI SDK.

Follow Build AI agents with AI Gateway and AI SDK to set up authentication, stream responses, and add tools and model fallbacks.

Follow Build AI agents in Python with the AI SDK to stream model responses, validate structured output, and run tools in an agent loop. The guide builds a FastAPI support service and deploys it to Vercel. See AI SDK for Python with AI Gateway for model routing and authentication.

Use ToolLoopAgent for a model-and-tool loop in your app, WorkflowAgent for durable execution, or eve for a framework with built-in sessions and channels. See Choosing between eve, AI SDK agents, and WorkflowAgent for the tradeoffs and how to move between them.

Use Chat SDK to handle messages and interactions in platforms such as Slack, and AI SDK to generate responses and call tools. Start with the Chat SDK quickstart, then follow Chat SDK with AI Gateway to stream model responses using conversation history.

Generative UI lets a model respond with interface elements instead of text alone. In a web app, AI SDK UI connects tool results to React components. See Generative User Interfaces.

To let the model compose the interface, use json-render. You define a catalog of components and pass catalog.prompt() to streamText as the model's instructions. The model then streams a JSON spec built from those components. In a web app, render the spec with your React components. For Slack, Microsoft Teams, and other chat platforms, @json-render/chat converts the spec into a card with tables, charts, and buttons, and Chat SDK posts the card in each platform's native format. Follow Stream generative UI with json-render to build the chat version.

Vercel Connect supplies short-lived OAuth tokens to MCP clients built with AI SDK, so models can call tools from services such as Linear without storing provider credentials in your application. The connectAuthProvider() helper requests credentials and supports user consent flows.

Follow the AI SDK and MCP tutorial to configure Vercel Connect, make MCP tools available to an AI SDK application, and handle tool approval.

For GitHub, you can use AI SDK tools without an MCP server. connectGithubTools from GitHub Tools requests a short-lived token from a GitHub connector inside each tool call, with scopes that match the preset you select.

Connect an AI SDK application to Sanity Context with createMCPClient so the model can read your Sanity datasets, and Knowledge Bases built from datasets, websites, and files, through a read-only MCP endpoint. The Sanity Context page shows how to load the endpoint's initial context into your instructions and handle token errors.

Jev, a decision model from TypeSafe AI, returns typed choices, scores, and boolean probabilities that your application can use to classify requests, route work, and assess proposed actions. Call Jev through AI Gateway with the experimental decide API in ai 7.0.128 or later. The previous experimental_evaluate export still works as a deprecated alias.

Learn how to classify, route, and score with Jev and AI SDK, or follow Route form submissions with Jev and AI SDK to build a form router with configurable destinations and a fallback model for uncertain decisions.

Start with an AI SDK template to build a chatbot or route form submissions with Jev:

Use the AI SDK software factory guide to connect GitHub investigation tools, Vercel Sandbox execution, and reviewed draft pull requests. Add Vercel Workflows when runs need to survive interruptions or wait for approval.

Capture token usage, tool calls, estimated cost, and request context with evlog. Follow Capture AI SDK token usage, tool calls, and cost with evlog to investigate expensive or failed requests alongside your existing OpenTelemetry traces.

The AI SDK is a free, open-source TypeScript library from Vercel for building AI applications and agents. It gives you one API to generate text and structured data, call tools, and stream responses across model providers. AI SDK UI adds chat interface helpers for React, Vue, Svelte, and Angular, such as the useChat hook in React. Install the ai package from npm. The source is in the vercel/ai repository under the Apache 2.0 license. The library has no fee. You pay for model usage through AI Gateway or your provider, and for the compute your app runs on.

Yes. The AI SDK is a library, so it runs in your Node.js app on Vercel or any other host. When you pass a model string such as 'anthropic/claude-sonnet-5', the AI SDK sends the request through AI Gateway. AI Gateway authenticates with the AI_GATEWAY_API_KEY environment variable or, on Vercel deployments, an OIDC token. To call a provider directly, install its provider package, such as @ai-sdk/openai or @ai-sdk/anthropic, and pass its model instead of a string. See AI SDK providers for the full list and AI SDK with AI Gateway for authentication.

Use AI SDK 7, the latest major version of the ai package. It requires Node.js 22 or later and supports ESM only, so replace require() calls with import. AI Gateway supports AI SDK 6 and 7. AI SDK 5 is deprecated, and AI Gateway stops accepting AI SDK 5 requests on January 8, 2027. AI SDK 7 renames several options, such as system to instructions and stepCountIs to isStepCount. Run npx @ai-sdk/codemod v7 to apply many of these changes automatically, then follow the AI SDK 7 migration guide.

Use the AI SDK's ToolLoopAgent for an agent that runs inside your app and finishes within one request. Use eve when you want durable sessions, approvals, a sandbox, schedules, and channels such as Slack and GitHub built in. eve is an open-source agent framework built on the AI SDK. You define an agent as Markdown and TypeScript files in an agent/ directory, and eve accepts AI Gateway model strings or any AI SDK LanguageModel. See Choosing between eve, AI SDK agents, and WorkflowAgent to compare them.

Yes. Use WorkflowAgent from @ai-sdk/workflow, which runs the same agent loop as ToolLoopAgent inside a Vercel Workflow. Each model call runs as a durable step. Mark a tool's execute function with 'use step', and its calls also get checkpoints and automatic retries. If the process crashes or times out, the run resumes from the last completed step instead of starting over. Tools with needsApproval pause the run until someone approves or denies them, even hours later. WorkflowAgent requires Workflow 5.1 or later, and its stream() method has no default step limit, so set stopWhen to cap model calls. See the WorkflowAgent guide. eve sessions are durable by default, with no workflow code to write.

Use Chat SDK, an open-source TypeScript library from Vercel for building bots that run on many chat platforms from one codebase. Platform adapters handle each platform's webhooks and message formatting. Pass your agent's stream to thread.post(), and Chat SDK posts the reply into the thread. To reach more platforms, register more adapters in the same Chat instance and keep the same handlers. Start with the Chat SDK quickstart. If you build with eve, use the eve Chat SDK channel to connect any Chat SDK adapter to your agent.


Was this helpful?

supported.