---
title: Build your startup's AI product with the AI SDK
description: Build streaming chat, decision-model triage, structured output, and tool-using agents with the AI SDK, then add tracing and cost controls before customers rely on them.
keywords: ["AI SDK","Startups","AI Agents","AI Gateway","Decision models"]
url: "https://vercel.com/kb/guide/startups-on-vercel-ai-sdk"
published: 2026-12-03
last_updated: 2026-12-03
authors: Ben Sabic
related_resources:
  - title: "Build your startup's AI features on Vercel AI Gateway"
    url: "/kb/guide/startups-on-vercel-ai-gateway"
    description: "Build customer-facing AI features with Vercel AI Gateway, including authentication, model fallbacks, usage attribution for each customer, data controls, and budgets."
  - title: "Build your startup's product on Vercel Sandbox"
    url: "/kb/guide/startups-on-vercel-sandbox"
    description: "Build code interpreters, app previews, and upload-processing features with Vercel Sandbox, including authentication, persistence, security, and cost controls."
  - title: "Build AI agents with AI Gateway and AI SDK"
    url: "/kb/guide/ai-gateway-and-ai-sdk"
    description: "Build AI agents on Vercel with AI Gateway and AI SDK, then make them reliable, capable, and durable with Sandbox, Chat SDK, Vercel Connect, and Workflow."
  - title: "How to classify, route, and score with Jev and AI SDK"
    url: "/kb/guide/typesafe-jev-and-ai-sdk"
    description: "Use Jev from TypeSafe AI with AI SDK's experimental `evaluate` API to classify, route, score, and verify inside your application. Jev returns typed choices, scores, and boolean probabilities through AI Gateway."
install_vercel_plugin: npx plugins add vercel/vercel-plugin
search_with_vercel_cli: npx vercel@latest kb search "<query>"
read_with_vercel_cli: "npx vercel@latest kb inspect startups-on-vercel-ai-sdk"
---

The [AI SDK](https://vercel.com/docs/ai-sdk) is a free, open-source TypeScript library licensed under Apache 2.0. It gives your product APIs to stream model responses, classify requests with decision models, generate typed output, and run agents that call tools. Those APIs work across providers, so your team doesn't maintain an adapter for each one.

Your backend still authenticates users, stores customer records and conversations, enforces rate limits and quotas, and runs evals. The AI SDK handles the model call, the stream, and the tool loop for those requests. If you're still choosing a TypeScript AI toolkit, [compare the AI SDK with TanStack AI](https://vercel.com/kb/guide/vercel-ai-sdk-vs-tanstack-ai).

## Decide whether the AI SDK fits your product

[AI SDK 7](https://vercel.com/blog/ai-sdk-7) is the latest major version of the `ai` package on npm. It requires Node.js 22 or later and supports ESM only. It works with Next.js and Node.js, and provides chat helpers for React, Vue, Svelte, and Angular. The [backend examples](https://ai-sdk.dev/docs/getting-started) cover Express, Hono, Fastify, and Nest.js.

The AI SDK is a library, so it runs in your Node.js application on Vercel or on any other host. When your code names a model as a `creator/model-name` string, such as `anthropic/claude-sonnet-5`, the request goes through AI Gateway, which is the default provider in AI SDK 7. To call a provider directly, install its package, such as `@ai-sdk/openai` or `@ai-sdk/anthropic`, and pass its model in place of the string.

The AI SDK fits when your product is written in TypeScript and an AI feature needs a stream, a typed decision, or a tool loop. The three hands-on sections that follow each build one of these patterns:

| Product pattern                             | What the AI SDK does                                                                                    | Main APIs                                                  |
| ------------------------------------------- | ------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- |
| Streaming chat or in-product copilot        | Streams model output from a route to a React component as it's generated                                | `streamText()`, `toUIMessageStream()`, `useChat()`         |
| Ticket triage, classification, and routing  | Answers typed questions about a request with a choice, a score, and a probability from a decision model | `experimental_decide()`                                    |
| Multi-step agent that acts on customer data | Runs a bounded model-and-tool loop and pauses for approval before sensitive actions                     | `ToolLoopAgent`, `tool()`, `isStepCount()`, `toolApproval` |

[Zo Computer](https://vercel.com/blog/how-zo-computer-improved-ai-reliability-20x-on-vercel) is an 8-person company that replaced its custom adapter code for each provider with the AI SDK and moved retries and fallback routing to AI Gateway. Zo reports that adding a new model went from an hour-long, multi-file code change to adding a config string in 30 seconds.

### Check language and agent requirements

The AI SDK is a TypeScript library. For a Python backend, the [AI SDK for Python](https://vercel.com/kb/guide/python-and-ai-sdk) is a separate `ai` package in public beta that requires Python 3.12 or later, with its own APIs and version cycle. To add a Next.js chat interface, [expose the Python agent through FastAPI](https://vercel.com/i/python-ai-agent-nextjs) and connect its stream with AI SDK UI.

For an agent that finishes within one request, use `ToolLoopAgent`, which runs a model-and-tool loop without checkpoints. `WorkflowAgent` runs that loop as durable steps on Vercel Workflows when it needs to survive an interruption.

eve is an open-source framework built on the AI SDK with durable sessions, approvals, and channels such as Slack. [Compare eve with the AI SDK's agent classes](https://vercel.com/kb/guide/eve-vs-ai-sdk-agents-vs-workflowagent) to choose which responsibilities your application will own.

## Prerequisites

Before you begin, make sure you have:

- An existing Next.js App Router project.
  
- A [Vercel account](https://vercel.com/signup) for AI Gateway, or an API key for a direct provider connection.
  

For local development, use Node.js 24+ and the latest [Vercel CLI](https://vercel.com/docs/cli).

> **Note:**
>
> AI Gateway calls require a positive credit balance. Free credits need a valid payment method and cover a [subset of models](https://vercel.com/ai-gateway/models?freeTier=true); other models require [purchased credits](https://vercel.com/docs/ai-gateway/pricing). The [AI Gateway startup guide](https://vercel.com/kb/guide/startups-on-vercel-ai-gateway) explains credit setup and budgets. Direct provider calls are billed by the provider.

## Build with your agent

Use this prompt in your application's repository to build a streaming chat, ticket triage with a decision model, or a multi-step agent with the AI SDK.

### Agent prompt

```txt
Help me add an AI feature to this application with the AI SDK, using https://vercel.com/kb/guide/startups-on-vercel-ai-sdk and its linked documentation. Read and follow the guide using the Vercel CLI: `npx vercel@latest kb inspect startups-on-vercel-ai-sdk`.

Inspect the repository and its dependencies first. If the intended feature isn't clear, ask whether I want a streaming chat or in-product copilot, ticket triage or routing with a decision model, or a multi-step agent that acts on customer data. For triage, use `experimental_decide` when choices, scores, and probabilities answer the task. Use `Output.object()` for schema-defined output such as extracted entities, numeric fields, or generated prose. Implement the selected pattern using the application's existing framework and conventions.

1. Use AI SDK 7 and its current API names, on Node.js 22 or later with ESM imports. If the repository uses an earlier AI SDK version, tell me before you upgrade, then run `npx @ai-sdk/codemod v7` and review what it leaves unchanged.
2. Configure server-side model access for local development and deployment. Ask whether I want AI Gateway or a direct provider package, and use Vercel OIDC for AI Gateway when available. Explain required environment variables without printing secrets.
3. Apply the application's authentication, rate limiting, and input validation before each model call. Take user and customer IDs from the authenticated session and pass them to tools through `toolsContext`, and don't accept them from the client or from model-generated tool arguments. Identify missing application-specific integrations instead of inventing them.
4. Set a step limit with `stopWhen` and a `timeout` on every tool loop. Require approval with `toolApproval` for tools that change data or spend money, and handle approval requests in the UI.
5. Return a safe message for errors that occur mid-stream. Handle decision refusals, uncertain or missing probabilities, and structured output that fails validation. Keep prompts, model output, and tool inputs out of error messages the client can see.
6. Type-check the implementation and test the success, validation failure, low-probability, tool denial, and timeout paths. Use local mocks where needed and distinguish those results from live model requests.

Return the changed files, required configuration, checks performed, and remaining deployment steps. Explain the expected model usage costs before running live requests.

To find other KB guides, such as ones on related topics or next steps, search the Vercel Knowledge Base with the Vercel CLI: `npx vercel@latest kb search "your topic"`
```

## Set up the AI SDK and connect a model

Install the AI SDK, its React hooks, and Zod in your Next.js project:

**pnpm**

```bash
pnpm i ai @ai-sdk/react zod
```

**npm**

```bash
npm i ai @ai-sdk/react zod
```

**yarn**

```bash
yarn add ai @ai-sdk/react zod
```

**bun**

```bash
bun add ai @ai-sdk/react zod
```

The `ai` package includes the AI Gateway provider, `@ai-sdk/react` provides `useChat`, and Zod defines the schemas for request validation, structured output, and tool inputs.

Applications deployed on Vercel authenticate to AI Gateway with the project's [OIDC token](https://vercel.com/docs/ai-gateway/authentication-and-byok/oidc), which leaves no long-lived key to store. Run these commands from your project directory, and link an existing Vercel project or create one when prompted:

```bash
vercel link
vercel env pull
```

`vercel env pull` saves a `VERCEL_OIDC_TOKEN` in `.env.local` for the AI SDK. [Development tokens expire after 12 hours](https://vercel.com/docs/ai-gateway/authentication-and-byok/oidc), so rerun the command to refresh them. On Vercel, the SDK retrieves and refreshes tokens per request.

Create `app/api/ai-check/route.ts` to confirm that a model call works. Each request to it makes a billed model call, and the route has no access checks, so delete it before you deploy:

```typescript
import { generateText } from 'ai';

export async function GET() {
  const { text } = await generateText({
    model: 'anthropic/claude-sonnet-5',
    prompt: 'Reply with the word ready.',
  });

  return Response.json({ text });
}
```

Start the development server:

**pnpm**

```bash
pnpm dev
```

**npm**

```bash
npm run dev
```

**yarn**

```bash
yarn dev
```

**bun**

```bash
bun dev
```

From another terminal, request the route:

```bash
curl http://localhost:3000/api/ai-check
```

The response is a JSON object with a `text` field, and the wording varies by model.

The AI SDK picks an AI Gateway credential in a fixed order: the `apiKey` passed to `createGateway()`, then the `AI_GATEWAY_API_KEY` environment variable, then the OIDC token. If `AI_GATEWAY_API_KEY` is set and non-empty, it takes priority over OIDC even when the key is invalid, so remove that variable from the project's environment variables to use OIDC on a deployment. When your backend runs on another cloud or in CI, set `AI_GATEWAY_API_KEY` to an AI Gateway API key.

### Call a model provider directly

To skip AI Gateway, install a provider package and pass its model in place of the string. For OpenAI, install `@ai-sdk/openai`:

**pnpm**

```bash
pnpm i @ai-sdk/openai
```

**npm**

```bash
npm i @ai-sdk/openai
```

**yarn**

```bash
yarn add @ai-sdk/openai
```

**bun**

```bash
bun add @ai-sdk/openai
```

Add your OpenAI API key to the `.env.local` env file, replacing `your_openai_api_key` with the key:

```text
OPENAI_API_KEY=your_openai_api_key
```

Then change the model in `app/api/ai-check/route.ts`:

```typescript
import { openai } from '@ai-sdk/openai';
import { generateText } from 'ai';

export async function GET() {
  const { text } = await generateText({
    model: openai('gpt-6-astra'),
    prompt: 'Reply with the word ready.',
  });

  return Response.json({ text });
}
```

Request the route again to confirm the key works. The provider bills this call to your own account, and the rest of the route is unchanged. The chat and agent examples accept a provider model wherever they show a model string, and `@ai-sdk/anthropic` follows the same steps with `ANTHROPIC_API_KEY`.

AI Gateway supports provider-specific options and tools, but some features need a direct connection. Use the provider package when the API or connection setting you need isn't supported through Gateway.

Requests that stay on AI Gateway can use fallback models, your own provider keys (BYOK), prompt caching, and zero data retention (ZDR) routing, which the [AI Gateway startup guide](https://vercel.com/kb/guide/startups-on-vercel-ai-gateway) sets up.

## Ship a streaming chat or in-product copilot

Support assistants and in-product copilots display text as the model produces it. The AI SDK pairs `streamText` in your route handler with `useChat` in React to manage the response stream and UI state.

Create `app/api/chat/route.ts`. Authentication, rate limiting, and input validation depend on your application and are omitted here. Add those checks to this and the other feature routes before deployment:

```typescript
import {
  convertToModelMessages,
  createUIMessageStreamResponse,
  streamText,
  toUIMessageStream,
  type UIMessage,
} from 'ai';

// Allow streaming responses up to 30 seconds.
export const maxDuration = 30;

export async function POST(request: Request) {
  // Authenticate the user and validate the input before this point.
  const { messages }: { messages: UIMessage[] } = await request.json();

  const result = streamText({
    model: 'anthropic/claude-sonnet-5',
    instructions:
      'You are a support assistant for a project management app. ' +
      'Answer in two or three sentences.',
    messages: await convertToModelMessages(messages),
  });

  return createUIMessageStreamResponse({
    stream: toUIMessageStream({
      stream: result.stream,
      onError: (error) => {
        console.error(error);
        return 'Something went wrong. Please try again.';
      },
    }),
  });
}
```

`convertToModelMessages` turns the UI messages that `useChat` sends into model messages, and `instructions` holds the system prompt. To try another model, change the `model` string, for example to `openai/gpt-6-astra`. Nothing else in the route changes.

Create `app/chat/page.tsx` for the client:

```tsx
'use client';

import { useChat } from '@ai-sdk/react';
import { DefaultChatTransport } from 'ai';
import { useState } from 'react';

export default function ChatPage() {
  const [input, setInput] = useState('');
  const { messages, sendMessage, status, error, regenerate } = useChat({
    transport: new DefaultChatTransport({ api: '/api/chat' }),
  });

  const busy = status === 'submitted' || status === 'streaming';

  return (
    <main>
      {messages.map((message) => (
        <div key={message.id}>
          <strong>{message.role === 'user' ? 'You' : 'Assistant'}</strong>
          {message.parts.map((part, index) =>
            part.type === 'text' ? <p key={index}>{part.text}</p> : null,
          )}
        </div>
      ))}

      {busy && <p role="status">Working...</p>}

      {error && (
        <div role="alert">
          <p>Something went wrong.</p>
          <button type="button" onClick={() => regenerate()}>
            Retry
          </button>
        </div>
      )}

      <form
        onSubmit={(event) => {
          event.preventDefault();
          if (!input.trim() || busy) return;
          void sendMessage({ text: input });
          setInput('');
        }}
      >
        <input
          aria-label="Message"
          value={input}
          onChange={(event) => setInput(event.target.value)}
          disabled={busy}
        />
        <button type="submit" disabled={busy || !input.trim()}>
          Send
        </button>
      </form>
    </main>
  );
}
```

With the development server running, open `http://localhost:3000/chat` and send a message. The reply appears in pieces as the model generates it.

`useChat` doesn't manage the input field, so the page keeps the text in `useState`. Each message is a list of `parts`, and the page renders the ones whose `type` is `text`. `status` moves through `submitted`, `streaming`, `ready`, and `error`, which the page uses to disable the form and show the retry button. To accept images and files in the same chat, read how the AI SDK handles [multimodal input](https://vercel.com/i/multimodal-ai).

[Featured](https://vercel.com/blog/how-featureds-users-make-100k-media-pitches-per-month-on-vercel) reports that its team of three engineers runs its chatbot across 17 models through the AI SDK and AI Gateway, where swapping providers is a configuration change. [ChatPRD](https://vercel.com/blog/leveraging-vercel-and-the-ai-sdk-to-deliver-a-seamless-ai-powered-experience) was built by a solo founder on the AI SDK's streaming features, and its customer story from October 2024 reports 20,000 users in nine months.

### Handle stream errors and retries

Once streaming begins, the HTTP status may already be 200, so errors arrive as parts of the stream. By default, the client receives the masked message "An error occurred." The `onError` function in the route logs the real error on the server and returns the text your customer sees.

`maxRetries` retries failures that happen while a model call is starting, twice by default. `streamRetries` is opt-in and retries provider errors that arrive after streaming has begun. It reruns only the failed step, and output already sent can't be retracted, so a retried step can append repeated or divergent partial text. Leave it off for chat unless your interface can replace a partial message. See [stream error handling](https://ai-sdk.dev/docs/ai-sdk-core/error-handling) for both options.

### Save conversations

Persistence is your application's job. Pass `originalMessages: messages` and an `onEnd` callback to `toUIMessageStream`. `onEnd` receives the complete `UIMessage[]`, including the new response, for you to write to your database. Call `result.consumeStream()` without awaiting it, so the stream runs to completion and `onEnd` fires even after the client disconnects.

When you load a stored conversation that contains tool calls, metadata, or data parts, validate it with `validateUIMessages` before you send it to the model. The [message persistence guide](https://ai-sdk.dev/docs/ai-sdk-ui/chatbot-message-persistence) shows the full route.

## Triage and route requests with a decision model

Ticket triage asks which team owns a request, how severe it is, and whether a person needs to review it. [Decision models](https://vercel.com/i/what-are-decision-models) answer these questions with typed choices, scores, and probabilities without generating text.

In Vercel's [November 2026 Production Index](https://vercel.com/blog/ai-gateway-production-index-november-2026), decision models received 26% of AI Gateway requests in October and accounted for 0.53% of estimated spend. Across that traffic, their average cost per request was about one-seventieth of the language-model average, with spend estimated at published list prices.

The AI SDK calls decision models with `experimental_decide`, available in `ai` 7.0.128 or later. The API is experimental and can change in patch releases, and decision support on AI Gateway is in beta. Commit your lockfile and check compatibility before you upgrade. If your project has an earlier release, update it:

**pnpm**

```bash
pnpm i ai@latest
```

**npm**

```bash
npm i ai@latest
```

**yarn**

```bash
yarn add ai@latest
```

**bun**

```bash
bun add ai@latest
```

Create `app/api/triage/route.ts`. The model string `typesafe-ai/jev` sends the request through AI Gateway to Jev, a decision model from TypeSafe AI:

```typescript
import {
  experimental_decide as decide,
  Experimental_DecisionRefusalError,
  InvalidResponseDataError,
} from 'ai';
import { z } from 'zod';

const requestSchema = z.object({
  ticket: z.string().min(1).max(10_000),
});

export async function POST(request: Request) {
  // Authenticate the user before this point.
  const body: unknown = await request.json().catch(() => null);
  const parsed = requestSchema.safeParse(body);
  if (!parsed.success) {
    return Response.json(
      { error: 'Send a ticket of 1 to 10,000 characters.' },
      { status: 400 },
    );
  }

  try {
    const result = await decide({
      model: 'typesafe-ai/jev',
      state: { ticket: parsed.data.ticket },
      questions: {
        category: {
          type: 'choice',
          instructions: 'Which team should handle this support ticket?',
          criteria: {
            billing: 'Charges, invoices, refunds, and plan changes',
            bug: 'Product features that fail or produce errors',
            account: 'Sign-in, permissions, and profile changes',
            other: 'Anything that does not fit the other teams',
          },
        },
        severity: {
          type: 'score',
          instructions: 'How severe is the issue for the customer?',
          criteria: [
            'Cosmetic or informational',
            'Degraded, but a workaround exists',
            'Blocking with no workaround',
            'Blocking and causing financial or data loss',
          ],
        },
        needsHumanReview: {
          type: 'boolean',
          instructions:
            'Does the ticket mention legal action, ' +
            'a security issue, or data loss?',
        },
      },
    });

    const categoryAnswer = result.answers.category;
    const categoryProbability =
      categoryAnswer.probabilities?.[categoryAnswer.choice];
    const reviewProbability = result.answers.needsHumanReview.probability;

    const autoRoute =
      categoryProbability != null &&
      categoryProbability >= 0.85 &&
      reviewProbability < 0.5;

    return Response.json({
      category: categoryAnswer.choice,
      categoryProbability: categoryProbability ?? null,
      severity: result.answers.severity.score,
      needsHumanReview: reviewProbability,
      autoRoute,
    });
  } catch (error) {
    if (
      Experimental_DecisionRefusalError.isInstance(error) ||
      InvalidResponseDataError.isInstance(error)
    ) {
      return Response.json(
        { error: 'The ticket could not be classified.' },
        { status: 422 },
      );
    }
    throw error;
  }
}
```

With the development server running, send a ticket:

```bash
curl http://localhost:3000/api/triage \
  -H 'Content-Type: application/json' \
  --data-binary \
  '{"ticket":"We were charged twice for the Pro plan this month '\
'and need a refund before Friday."}'
```

The response is a JSON object, and its numbers vary from run to run:

- `category` is one of the keys in the choice question's `criteria`. `categoryProbability` is the probability the model gave that choice, or `null` when it returned no distribution.
  
- `severity` is a fractional score from 0 to 3, the index range of the four rubric levels.
  
- `needsHumanReview` is the model's estimated probability that the answer is yes, where 0.98 is a strong yes and 0.02 is a strong no. It isn't confidence in whichever answer is more likely.
  
- `autoRoute` is `true` when the category probability is at least 0.85 and the review probability is below 0.5. Send every other ticket to a person.
  

### Handle uncertain or invalid answers

Choice and score distributions are optional. Native decision models such as Jev return them, while language-model adapters omit them. The route uses `?.` to handle missing distributions and sets `autoRoute` to `false` so your application can send those tickets for review. Test the 0.85 and 0.5 thresholds against labeled tickets from your queue using the same questions, because the AI SDK doesn't promise calibration across providers.

`experimental_decide` throws `Experimental_DecisionRefusalError` when the model refuses any question, without retrying, and `InvalidResponseDataError` when an answer is missing or invalid. The route returns a 422 for both so your application can queue those tickets for human review.

### Choose a provider and fallbacks

For a direct connection, use the provider's decision-model API, such as `openai.decisionModel('gpt-6-luna')` from `@ai-sdk/openai`, or the `@ai-sdk/typesafe-ai` package for Jev.

On AI Gateway, [decision fallbacks](https://vercel.com/docs/ai-gateway/models-and-providers/decision-fallbacks) can rerun a successful decision with another model when an answer is uncertain. This feature is in beta, and both calls are billed when a fallback triggers. Read [how confidence-based decision fallbacks work](https://vercel.com/i/confidence-based-decision-fallbacks) before enabling them.

Test branching with the [Jev guide's mock model](https://vercel.com/kb/guide/typesafe-jev-and-ai-sdk), or send uncertain submissions to a language model using the [form router](https://vercel.com/kb/guide/jev-ai-sdk-form-router). The [decisions reference](https://ai-sdk.dev/docs/ai-sdk-core/decisions) covers question types and errors, and [five Decision API examples](https://vercel.com/i/ai-gateway-decision-api-use-cases) show other applications.

The [Searchable](https://vercel.com/blog/how-searchable-ships-customer-requested-features-in-30-minutes-on-vercel) team builds on the AI SDK and AI Gateway to test new models without rotating API keys or SDKs, and reports shipping customer-requested features in as little as 30 minutes.

### When to use structured output instead

When a workflow needs generated fields, such as a written summary, extracted entities, or a drafted reply, a decision model can't supply them. Call `generateText` with `output: Output.object({ schema })`, which returns an object validated against your Zod schema and replaces the deprecated `generateObject()`.

`generateText` rejects with `NoObjectGeneratedError` when the model's response can't be parsed or doesn't match the schema, and reading `output` throws `NoOutputGeneratedError` when the call produced no output. Handle both, and run evals on the results, because schema validation checks the shape of the data and can't tell whether the content is right.

The [comparison of Jev and GPT-6 Astra](https://vercel.com/i/jev-vs-gpt-6-astra) routes the same support ticket both ways, and the [structured data guide](https://ai-sdk.dev/docs/ai-sdk-core/generating-structured-data) covers schemas and streaming partial objects.

## Build a bounded multi-step agent with tools and approvals

An account assistant has to read a customer's data and sometimes act on it. `ToolLoopAgent` calls the model, runs the tools it asks for, and sends the results back until the model answers or a limit stops the loop.

[Sandstone](https://vercel.com/blog/how-sandstone-grew-40x-in-147-days-on-vercel) builds multi-step agentic legal workflows end to end with the AI SDK. Its system searches thousands of procurement agreements, surfaces the ones most at risk, and alerts their owners in Slack.

Create `app/api/agent/route.ts`. In this file, `getCustomerId()` returns a fixed test ID so that you can run the route locally, and `loadAccount()` and `createRefundRequest()` return placeholder data. Replace all three with your session lookup and data layer before you deploy:

```typescript
import {
  createAgentUIStreamResponse,
  isStepCount,
  tool,
  ToolLoopAgent,
} from 'ai';
import { z } from 'zod';

export const maxDuration = 90;

// Replace with your session lookup. Return null when the user is signed out.
async function getCustomerId(): Promise<string | null> {
  return 'cus_test_123';
}

// Replace with a query against your own database.
async function loadAccount(customerId: string) {
  return {
    customerId,
    plan: 'pro',
    seats: 12,
    lastInvoiceId: 'inv_1042',
    lastInvoiceAmountUsd: 240,
  };
}

// Replace with a call to your billing system. Check that the invoice
// belongs to the customer and that the amount is within your policy.
async function createRefundRequest(refund: {
  customerId: string;
  invoiceId: string;
  amountUsd: number;
  reason: string;
}) {
  return { status: 'submitted', ...refund };
}

const customerContextSchema = z.object({ customerId: z.string() });

const getAccountSummary = tool({
  description: "Get the signed-in customer's plan, seats, and latest invoice.",
  inputSchema: z.object({}),
  contextSchema: customerContextSchema,
  execute: async (_input, { context }) => loadAccount(context.customerId),
});

const requestRefund = tool({
  description: "Request a refund for one of the signed-in customer's invoices.",
  inputSchema: z.object({
    invoiceId: z.string().describe('Invoice ID, such as inv_1042'),
    amountUsd: z.number().positive(),
    reason: z.string(),
  }),
  contextSchema: customerContextSchema,
  execute: async (input, { context }) =>
    createRefundRequest({ customerId: context.customerId, ...input }),
});

export async function POST(request: Request) {
  const customerId = await getCustomerId();
  if (!customerId) {
    return Response.json({ error: 'Sign in first' }, { status: 401 });
  }

  const { messages } = await request.json();

  const agent = new ToolLoopAgent({
    model: 'anthropic/claude-sonnet-5',
    instructions:
      'You are an account assistant. Look up the account before you ' +
      'answer questions about it. Do not retry a denied tool call.',
    tools: { getAccountSummary, requestRefund },
    toolsContext: {
      getAccountSummary: { customerId },
      requestRefund: { customerId },
    },
    toolApproval: { requestRefund: 'user-approval' },
    stopWhen: isStepCount(5),
  });

  return createAgentUIStreamResponse({
    agent,
    uiMessages: messages,
    abortSignal: request.signal,
    timeout: { totalMs: 60_000 },
  });
}
```

These settings scope the tools and bound the loop:

- `contextSchema` declares the context a tool expects, and `toolsContext` supplies it from the server. The model generates only the `inputSchema` arguments, so it cannot choose the customer ID.
  
- `toolApproval` pauses the run for consent before `requestRefund` executes. The client must send the approval decision back to the route to continue.
  
- `stopWhen` limits this loop to five steps. The `ToolLoopAgent` default is 20, so this lower limit bounds latency and spend.
  
- `timeout` limits the run to 60 seconds, within the route's 90-second `maxDuration`. The request's abort signal also lets the agent stop when the caller disconnects, if the host forwards that cancellation.
  

On Vercel, enable [request cancellation](https://vercel.com/docs/functions/functions-api-reference#cancel-requests) for this Node.js route by merging its configuration into `vercel.json`. Scope it to the agent route so saved chat conversations can still finish after a disconnect. For a project with `src/app`, prefix the configured route path with `src/`:

```json
{
  "functions": {
    "app/api/agent/route.ts": {
      "supportsCancellation": true
    }
  }
}
```

The UI response helper and direct agent calls accept the same [timeout settings](https://ai-sdk.dev/docs/ai-sdk-core/settings#timeout). Beyond `totalMs`, use `stepMs` for a complete step, `toolMs` or `tools` overrides for tool executions, and `firstChunkMs` or `chunkMs` for streaming. When a tool times out, it returns a tool error that the model can respond to or retry.

### Test the agent and handle approvals

To try the agent, point the transport in `app/chat/page.tsx` at `/api/agent` and ask which plan the account is on. The response should name the `pro` plan from the placeholder data. The route's `createAgentUIStreamResponse` helper validates and converts UI messages, so you don't need a separate `convertToModelMessages` call.

For refunds, the page must show the proposed input and let the customer approve or deny it. Configure `sendAutomaticallyWhen` so that recording the decision also sends the updated conversation back to the route, where the agent can run the approved tool or report the denial.

```tsx
'use client';

import { useChat } from '@ai-sdk/react';
import {
  DefaultChatTransport,
  isToolUIPart,
  lastAssistantMessageIsCompleteWithApprovalResponses,
} from 'ai';
import { useState } from 'react';

export default function ChatPage() {
  const [input, setInput] = useState('');
  const [submittingApproval, setSubmittingApproval] = useState(false);
  const [approvalError, setApprovalError] = useState(false);
  const {
    messages,
    sendMessage,
    addToolApprovalResponse,
    status,
    error,
    regenerate,
  } = useChat({
    transport: new DefaultChatTransport({ api: '/api/agent' }),
    sendAutomaticallyWhen:
      lastAssistantMessageIsCompleteWithApprovalResponses,
  });

  const busy = status === 'submitted' || status === 'streaming';
  const lastParts = messages.at(-1)?.parts ?? [];
  const awaitingApproval = lastParts.some(
    (part) => isToolUIPart(part) && part.state === 'approval-requested',
  );
  const approvalResponded = lastParts.some(
    (part) => isToolUIPart(part) && part.state === 'approval-responded',
  );
  const blocked =
    busy || submittingApproval || awaitingApproval || approvalResponded;

  async function respond(id: string, approved: boolean) {
    setSubmittingApproval(true);
    setApprovalError(false);
    try {
      await addToolApprovalResponse({ id, approved });
    } catch {
      setApprovalError(true);
    } finally {
      setSubmittingApproval(false);
    }
  }

  return (
    <main>
      {messages.map((message) => (
        <div key={message.id}>
          <strong>{message.role === 'user' ? 'You' : 'Assistant'}</strong>
          {message.parts.map((part, index) => {
            if (part.type === 'text') {
              return <p key={index}>{part.text}</p>;
            }
            if (part.type !== 'tool-requestRefund') return null;

            return (
              <div key={part.toolCallId}>
                <p>Proposed refund request</p>
                <pre style={{ whiteSpace: 'pre-wrap' }}>
                  {JSON.stringify(part.input, null, 2)}
                </pre>
                {part.state === 'approval-requested' && (
                  <>
                    <button
                      type="button"
                      disabled={busy || submittingApproval}
                      onClick={() => void respond(part.approval.id, true)}
                    >
                      Approve
                    </button>
                    <button
                      type="button"
                      disabled={busy || submittingApproval}
                      onClick={() => void respond(part.approval.id, false)}
                    >
                      Deny
                    </button>
                  </>
                )}
                {part.state === 'approval-responded' && (
                  <p>Decision recorded.</p>
                )}
                {part.state === 'output-available' && (
                  <p>Refund request submitted.</p>
                )}
                {part.state === 'output-denied' && <p>Refund denied.</p>}
                {part.state === 'output-error' && (
                  <p>
                    The refund request failed. Check its status before retrying.
                  </p>
                )}
              </div>
            );
          })}
        </div>
      ))}

      {busy && <p role="status">Working...</p>}
      {approvalError && (
        <p role="alert">
          The decision wasn't recorded. Try approving or denying again.
        </p>
      )}
      {error && (
        <div role="alert">
          <p>Something went wrong.</p>
          <button
            type="button"
            disabled={busy || submittingApproval}
            onClick={() => {
              if (approvalResponded) void sendMessage();
              else void regenerate();
            }}
          >
            Retry
          </button>
        </div>
      )}

      <form
        onSubmit={(event) => {
          event.preventDefault();
          if (!input.trim() || blocked) return;
          void sendMessage({ text: input });
          setInput('');
        }}
      >
        <input
          aria-label="Message"
          value={input}
          onChange={(event) => setInput(event.target.value)}
          disabled={blocked}
        />
        <button type="submit" disabled={blocked || !input.trim()}>
          Send
        </button>
      </form>
    </main>
  );
}
```

Approval records consent, so `createRefundRequest()` must still check the invoice's owner and enforce your refund policy. If sending a recorded decision back to the route fails, retry with `sendMessage()`; `regenerate()` would remove the assistant message containing that decision.

The [tool approval documentation](https://ai-sdk.dev/docs/agents/tool-approvals#use-with-usechat) explains the request flow. The [chatbot tool example](https://ai-sdk.dev/docs/ai-sdk-ui/chatbot-tool-usage) and [Shopify agent](https://vercel.com/kb/guide/shopify-agent-ai-sdk-vercel-connect) show how to apply it in a UI.

### Connect external tools with MCP

An existing MCP server lets the agent call external tools without a hand-written `tool()` for each one. Install `@ai-sdk/mcp`, create an HTTP client with `createMCPClient`, and pass `client.tools()` to the agent. For streaming calls, close the client in both `onEnd` and `onAbort`, and if setup fails before streaming starts. Use a `finally` block for non-streaming calls.

MCP annotations such as `readOnlyHint` do not enforce approval. Apply your own `toolApproval` policy, allowlist, and scoped credentials. Follow the [AI SDK integration](https://vercel.com/docs/mcp/integrations/ai-sdk) for client setup, or use the [Shopify agent's shopper add-on](https://vercel.com/kb/guide/shopify-agent-ai-sdk-vercel-connect) to connect to Shopify's Customer Accounts MCP server.

### Make long-running agents durable with WorkflowAgent

`ToolLoopAgent` keeps its progress in memory, so a crash or a function timeout loses the run. When an agent has to outlast one request, or wait hours for an approval, use `WorkflowAgent` from `@ai-sdk/workflow`. It runs the same loop inside a `'use workflow'` function on [Vercel Workflows](https://vercel.com/docs/workflows). Each model call is a durable step, and a tool whose `execute` function starts with `'use step'` gets checkpoints and automatic retries. `WorkflowAgent` requires [Workflow SDK](https://vercel.com/blog/workflow-sdk-5) 5.1 or later.

Two differences matter when you move code from `ToolLoopAgent`. `WorkflowAgent.stream()` has no default step limit, so set `stopWhen`. `WorkflowAgent` also doesn't implement the `Agent` interface, so your route starts the workflow and streams its output in place of calling `createAgentUIStreamResponse`.

`WorkflowChatTransport` from `@ai-sdk/workflow/client` reconnects when a stream ends without a `finish` event. Follow the [WorkflowAgent guide](https://ai-sdk.dev/docs/agents/workflow-agent) for the route and workflow implementation. For the execution model, read [how durable AI agents work](https://vercel.com/i/what-is-a-durable-ai-agent), then apply it with the [web research agent tutorial](https://vercel.com/kb/guide/durable-web-research-agent-with-workflow-sdk) built from journaled steps.

In its customer story, [FLORA](https://vercel.com/blog/how-flora-shipped-a-creative-agent-on-vercels-ai-stack) describes starting with LangChain building blocks and then building its creative agent, FAUNA, on the AI SDK, the Workflow SDK's `DurableAgent`, and Fluid compute. `WorkflowAgent` replaces `DurableAgent` in AI SDK 7.

### Add code execution, memory, and more agents

To run code that the model writes, give the agent a tool that executes it in a [Vercel Sandbox microVM](https://vercel.com/kb/guide/startups-on-vercel-sandbox), outside your route's process. Vercel replaced most of its internal agent tooling with [filesystem and bash tools](https://vercel.com/blog/how-to-build-agents-with-filesystems-and-bash) that execute code in a sandbox.

To carry facts between conversations, choose an [agent memory](https://vercel.com/i/agent-memory) design before you add storage. Before you split one agent into several, check [when multi-agent systems earn their token cost](https://vercel.com/i/multi-agent-systems) and [when one agent is enough](https://vercel.com/i/ai-agents-vs-agentic-ai).

## Harden, observe, and evaluate before customers rely on it

### Scope tools and protect prompts on the server

Apply these four controls to every route that runs tools:

- Pass tenant and user IDs through `toolsContext` from the authenticated session. Values in `inputSchema` come from the model and can be influenced by a prompt.
  
- Keep `allowSystemInMessages` off. AI SDK 7 rejects system messages inside `messages` by default, so a user who can edit the message list can't add a system message that overrides your instructions. Enable this only for trusted histories.
  
- Gate tools that change data or spend money with `toolApproval`, and repeat the authorization check inside the tool.
  
- Bound every loop with `isStepCount()` and a `timeout`.
  

When a tool's `execute` function throws, the client receives the same error text as the model. Use messages that are safe to show customers.

### Debug locally and trace in production

During local development, AI SDK DevTools captures each `generateText` and `streamText` call for inspection in a local viewer. Install the package:

**pnpm**

```bash
pnpm i @ai-sdk/devtools
```

**npm**

```bash
npm i @ai-sdk/devtools
```

**yarn**

```bash
yarn add @ai-sdk/devtools
```

**bun**

```bash
bun add @ai-sdk/devtools
```

Register `DevToolsTelemetry()` with `registerTelemetry` from `ai` when your application starts, then start the viewer:

```bash
npx @ai-sdk/devtools@latest
```

The viewer runs at `http://localhost:4983`. DevTools stores what it captures in a local JSON file, `.devtools/generations.json`, and is for local development only. Don't register it in production.

For production traces, install the OpenTelemetry integration, which AI SDK 7 ships in a separate package:

**pnpm**

```bash
pnpm i @ai-sdk/otel @vercel/otel
```

**npm**

```bash
npm i @ai-sdk/otel @vercel/otel
```

**yarn**

```bash
yarn add @ai-sdk/otel @vercel/otel
```

**bun**

```bash
bun add @ai-sdk/otel @vercel/otel
```

Create `instrumentation.ts` in your project root, replacing `your-service-name` with the name your traces should carry:

```typescript
import { OpenTelemetry } from '@ai-sdk/otel';
import { registerOTel } from '@vercel/otel';
import { registerTelemetry } from 'ai';

export function register() {
  registerOTel({ serviceName: 'your-service-name' });
  registerTelemetry(new OpenTelemetry());
}
```

`registerOTel` is your OpenTelemetry provider setup, and `registerTelemetry` connects the AI SDK to it. Once an integration is registered, every AI SDK call emits telemetry without a per-call flag. Add the `telemetry` option to a call to change what it records:

- `functionId` labels the call, for example `telemetry: { functionId: 'support-chat' }`.
  
- `recordInputs: false` and `recordOutputs: false` keep prompts and responses out of your traces. Both are recorded by default, so set them on calls that carry customer data.
  
- `includeRuntimeContext` opts selected runtime context properties in. None are included when you leave it out.
  
- `isEnabled: false` turns telemetry off for that call.
  

Use [evlog/ai](https://vercel.com/kb/guide/ai-sdk-and-evlog) to record model, token, and estimated cost data for each request, so you can compare usage across customers and routes. For production tracing, compare [observability tools](https://vercel.com/i/ai-observability-tools) and plan [which agent events to record](https://vercel.com/i/ai-agent-observability).

### Evaluate changes before shipping

Changing a prompt or a model string can change any response a feature produces. Save a set of real inputs for each feature with the results you expect, and run them before a prompt or model change merges. Vercel's approach to [evaluating agents in production](https://vercel.com/i/ai-agent-evaluation-frameworks-production) uses ordered checks, binary metrics, trace grading, and CI gates.

## Control what you spend

The AI SDK has no license fee, but your startup still pays for model usage through AI Gateway or its provider and for application compute. Track and manage these costs as usage grows:

- Measure tokens on every call. The `usage` field on `generateText` and `streamText` results covers all steps; in `onEnd`, read `totalUsage` for the run.
  
- Attribute usage to each customer. With AI Gateway, send a customer ID and tags with each request, as the [AI Gateway startup guide](https://vercel.com/kb/guide/startups-on-vercel-ai-gateway) shows, and read about [LLM cost management](https://vercel.com/i/llm-cost-management-track-control-model-spend) for budgets.
  
- Move high-volume classification and routing to a decision model, as the triage route does, and send other routine requests to a lower-cost language model with [cost-aware model routing](https://vercel.com/kb/guide/cost-aware-model-routing-with-ai-gateway).
  
- Keep step limits and timeouts on every agent, because each extra model call adds token usage.
  

### Get credits through Vercel's startup programs

#### Vercel startups program

The [Vercel startups program](https://vercel.com/startups) accepts companies affiliated with an approved Startups Partner, such as an accelerator or venture firm. Eligible startups have raised a Series A or less, apply within 12 months of their latest funding round, and have not received Vercel for Startups credits before.

Startups accepted on or after August 6, 2026 receive a Flexible Commitment Amount of up to $30,000 that can cover AI Gateway usage; earlier legacy credits cannot. The [AI Gateway allocation](https://vercel.com/startups/credits) is capped at 50%, with excess usage billed at standard rates. Confirm how that cap applies to your allocation with the startups team before budgeting.

#### Vercel X

[Vercel X](https://vercel.com/x) is a six-week, in-person accelerator for pre-seed founders building AI companies. It takes no equity and offers a program-wide pool of more than $9M in Vercel and partner credits for hosting, compute, and model API usage. Confirm AI Gateway credit coverage and application dates with the program team.

## Plan for limits as you grow

On Vercel, your routes run as Vercel Functions with [Fluid compute](https://vercel.com/docs/fluid-compute), which is enabled by default for new projects. Several invocations can share one function instance while they wait on a model.

Function [duration](https://vercel.com/docs/functions/configuring-functions/duration) defaults to 300 seconds. The maximum is 300 seconds on Hobby and 800 seconds on Pro and Enterprise, with an extended maximum of 1,800 seconds in beta on Pro and Enterprise. Set `maxDuration` in each route to the ceiling that route needs, and move agents that outgrow it to `WorkflowAgent`.

### Upgrade an existing application

AI Gateway supports AI SDK 6 and 7 and stops accepting AI SDK 5 requests on January 8, 2027. [Migrate an existing application to AI SDK 7](https://ai-sdk.dev/docs/migration-guides/migration-guide-7-0) with the codemod, then review the remaining changes to ESM imports and tool approval policies:

```bash
npx @ai-sdk/codemod v7
```

## Troubleshooting

| What you observe                                                                                                   | What to check                                                                                                                                                                                                 |
| ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Local requests fail with a `GatewayAuthenticationError`                                                            | No API key is set and the development OIDC token is missing or has expired, which happens after 12 hours. Run `vercel env pull` again.                                                                        |
| A deployment fails to authenticate although OIDC is set up                                                         | `AI_GATEWAY_API_KEY` is set and takes priority over OIDC, even when the key is invalid. Remove it or replace it.                                                                                              |
| Your code loads `ai` with `require()`, or runs on Node.js 18 or 20                                                 | AI SDK 7 supports ESM only and requires Node.js 22 or later. Replace `require()` with `import`, and upgrade Node.js.                                                                                          |
| Code from an older example uses `system`, `stepCountIs`, `onFinish`, `experimental_telemetry`, or `generateObject` | AI SDK 7 renames or deprecates those names. Use `instructions`, `isStepCount`, `onEnd`, `telemetry`, and `Output.object()`, and run `npx @ai-sdk/codemod v7` on existing code.                                |
| A stored chat that contains system messages is rejected after you upgrade                                          | AI SDK 7 rejects system messages inside `messages` by default. Move the text to `instructions`, or set `allowSystemInMessages: true` for histories you trust.                                                 |
| A `generateText` call with tools returns empty `text` and `finishReason: 'tool-calls'`                             | `generateText` and `streamText` run one step by default. Set `stopWhen: isStepCount(5)` so the model can answer after the tool runs.                                                                          |
| `experimental_decide` throws `Experimental_DecisionRefusalError` or `InvalidResponseDataError`                     | The model refused a question, or an answer was missing or invalid. Refusals aren't retried. Catch both errors and send the request to human review.                                                           |
| A choice or score answer has no `probabilities`                                                                    | The model answered through a language-model adapter, which omits distributions. Guard the field with `?.` and review those requests, or use a native decision model such as `typesafe-ai/jev`.                |
| Older code calls `experimental_evaluate` or `gateway.evaluationModel()`                                            | Both are deprecated aliases. Rename them to `experimental_decide` and `gateway.decisionModel()`, and check [what else changes in your code](https://vercel.com/i/ai-sdk-evaluation-to-decisions).             |
| Reading `output` throws `NoOutputGeneratedError` on an `Output.object()` call that also has tools                  | Structured output counts as a step. Raise the `stopWhen` limit so the final step can produce the object.                                                                                                      |
| The agent stops in the middle of a task                                                                            | The run reached its `stopWhen` limit, which is 20 steps by default for `ToolLoopAgent`, or its `timeout`. The AI SDK logs a warning when the default step limit stops the loop. Raise the limit that applies. |

## Next steps

- Set up [AI Gateway fallbacks, usage attribution, and budgets](https://vercel.com/kb/guide/startups-on-vercel-ai-gateway) for your startup
  
- Run [model-written code in Vercel Sandbox](https://vercel.com/kb/guide/startups-on-vercel-sandbox) for your customers
  
- Extend your agent with [Sandbox, Chat SDK, Vercel Connect, and Workflows](https://vercel.com/kb/guide/ai-gateway-and-ai-sdk)
  
- Choose between [eve, ToolLoopAgent, and WorkflowAgent](https://vercel.com/kb/guide/eve-vs-ai-sdk-agents-vs-workflowagent) for your next agent
  
- Record token usage, tool calls, and estimated cost for each request with [evlog](https://vercel.com/kb/guide/ai-sdk-and-evlog)
  
- Test [decision-model branching with Jev and a mock model](https://vercel.com/kb/guide/typesafe-jev-and-ai-sdk)
  
- Find [AI SDK templates](https://vercel.com/docs/ai-sdk) and explore the [API reference](https://ai-sdk.dev/docs/introduction)
  

## Frequently asked questions

### Is the AI SDK free to use in a commercial product?

Yes. The AI SDK is open source under the Apache 2.0 license, with no library fee. Your startup pays for model usage through AI Gateway or its provider and for the compute that runs the application.

### Do I need Vercel or AI Gateway to use the AI SDK?

No. The AI SDK runs in a Node.js application on any host. Model strings such as `anthropic/claude-sonnet-5` go through AI Gateway, which authenticates with an API key when the application runs outside Vercel. To leave AI Gateway out, install a provider package such as `@ai-sdk/openai` and pass its model object to the same AI SDK functions.

### Should my startup build its agent with ToolLoopAgent, WorkflowAgent, or eve?

Start with the AI SDK's `ToolLoopAgent` when the agent finishes inside one request. Move to `WorkflowAgent` when a run has to survive a crash, a deployment, or a long wait for approval, because it runs the agent loop as durable steps on Vercel Workflows. Choose eve when you want durable sessions, approvals, a sandbox, and channels such as Slack supplied by a framework. All three accept AI Gateway model strings.

### Can I use the AI SDK with a Python backend?

The TypeScript package doesn't run in Python. The separate [AI SDK for Python](https://vercel.com/kb/guide/python-and-ai-sdk) requires Python 3.12 or later and is in public beta, so its APIs may change before general availability. To add a Next.js interface, [connect the Python agent through FastAPI](https://vercel.com/i/python-ai-agent-nextjs) using the Python SDK's message and stream adapters for AI SDK UI.

## Related Resources

- [Build your startup's AI features on Vercel AI Gateway](/kb/guide/startups-on-vercel-ai-gateway): Build customer-facing AI features with Vercel AI Gateway, including authentication, model fallbacks, usage attribution for each customer, data controls, and budgets.
- [Build your startup's product on Vercel Sandbox](/kb/guide/startups-on-vercel-sandbox): Build code interpreters, app previews, and upload-processing features with Vercel Sandbox, including authentication, persistence, security, and cost controls.
- [Build AI agents with AI Gateway and AI SDK](/kb/guide/ai-gateway-and-ai-sdk): Build AI agents on Vercel with AI Gateway and AI SDK, then make them reliable, capable, and durable with Sandbox, Chat SDK, Vercel Connect, and Workflow.
- [How to classify, route, and score with Jev and AI SDK](/kb/guide/typesafe-jev-and-ai-sdk): Use Jev from TypeSafe AI with AI SDK's experimental \`evaluate\` API to classify, route, score, and verify inside your application. Jev returns typed choices, scores, and boolean probabilities through AI Gateway.

## More AI SDK guides

- [Build your startup's AI features on Vercel AI Gateway](/kb/guide/startups-on-vercel-ai-gateway): Build customer-facing AI features with Vercel AI Gateway, including authentication, model fallbacks, usage attribution for each customer, data controls, and budgets.
- [Migrate from Neon AI Gateway to Vercel AI Gateway](/kb/guide/neon-aig-to-vercel-aig): Swap Neon's per-branch base URL and credential for Vercel's, map each short model ID to a creator/model slug, and replace the Gemini endpoint, rate limits, and daily spend cap.
- [Migrate from Netlify AI Gateway to Vercel AI Gateway](/kb/guide/netlify-aig-to-vercel-aig): Replace Netlify's injected provider keys and base URLs with a Vercel AI Gateway credential, map each model to a creator/model slug, and move Gemini SDK calls to a supported API.

## Reference Architecture

Choose a stack and work through the decisions behind it, with curated documentation, guides, templates, and courses to help you build.

- [Agent stack](/kb/architecture/agents): Build and operate agents with models, tools, and durable workflows.
- [Web applications](/kb/architecture/web): Choose rendering, data, authentication, and caching approaches.
- [Backends](/kb/architecture/backends): Choose a runtime, connect services, and run background work.

[Browse all stacks](/kb/architecture)

## Build with prompts

Build an app, extend an agent, or improve your project with ready-to-use prompts for your coding agent.

[Browse the prompt library](/kb/prompts) · [Read the Markdown index](/kb/prompts.md)

## Search guides from your terminal

Search the Knowledge Base and read guides as Markdown with the Vercel CLI. No login required.

```bash
# Find guides by keyword
npx vercel@latest kb search "rewrites and redirects"
npx vercel@latest kb search "AI SDK streaming"

# Show the latest guides
npx vercel@latest kb

# Print a guide as Markdown, by slug or URL
npx vercel@latest kb inspect <guide>
```
