Skip to content

Vercel AI SDK Guide ​

The Vercel AI SDK is the standard library for building AI-powered user interfaces in React, Next.js, Vue, and Svelte. It abstracts away the complexity of stream parsing and state management.

Core Concepts ​

The SDK is split into two parts:

  1. AI SDK Core: Server-side library for generating text/objects (ai).
  2. AI SDK UI: Client-side hooks and transports for building interfaces (@ai-sdk/react).

1. Server-Side: streamText ​

In your API route (Next.js App Router), use streamText to call an LLM and return a stream.

typescript
// app/api/chat/route.ts
import {
  convertToModelMessages,
  createUIMessageStreamResponse,
  streamText,
  toUIMessageStream,
} from `ai`;

export async function POST(req: Request) {
  const { messages } = await req.json();

  const result = await streamText({
    model: "anthropic/claude-sonnet-5.5",
    messages: await convertToModelMessages(messages),
  });

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

2. Client-Side: useChat ​

The useChat hook is the easiest way to build a ChatGPT-like interface.

tsx
'use client';
import { useChat } from `@ai-sdk/react`;
import { DefaultChatTransport } from `ai`;
import { useState } from 'react';

export default function Chat() {
  const [input, setInput] = useState('');
  const { messages, sendMessage, status, stop } = useChat({
    transport: new DefaultChatTransport({ api: '/api/chat' }),
  });
  const busy = status === 'submitted' || status === 'streaming';

  return (
    <div>
      {messages.map(message => (
        <div key={message.id}>
          {message.role === 'user' ? 'User: ' : 'AI: '}
          {message.parts.map((part, index) => (
            part.type === 'text' ? <span key={index}>{part.text}</span> : null
          ))}
        </div>
      ))}

      {busy && <button type="button" onClick={() => stop()}>Stop</button>}
      <form onSubmit={event => {
        event.preventDefault();
        if (!input.trim() || busy) return;
        void sendMessage({ text: input.trim() });
        setInput('');
      }}>
        <input value={input} onChange={event => setInput(event.target.value)} />
        <button disabled={busy || !input.trim()}>Send</button>
      </form>
    </div>
  );
}

Key features of useChat ​

  • Message parts: Render text and tool-result parts without assuming every message is plain text.
  • Transport: DefaultChatTransport posts to /api/chat.
  • Status: submitted and streaming make loading and stop controls explicit.

3. Client-Side: useCompletion ​

Use this for "Autocomplete" or "Generate Text" scenarios where you aren't in a chat loop.

tsx
'use client';
import { useCompletion } from '@ai-sdk/react';

export default function SloganGenerator() {
  const { completion, input, handleInputChange, handleSubmit } = useCompletion({
    api: '/api/generate-slogan',
  });

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input value={input} onChange={handleInputChange} placeholder="Enter your company name..." />
      </form>
      
      {completion && <div className="result">{completion}</div>}
    </div>
  );
}

4. Generative UI ​

AI SDK UI can stream text, tool calls, and tool results as typed message parts. For the current protocol, use toUIMessageStream on the server and render message.parts on the client as shown above. The older RSC streamUI helper is not used in this current route pattern.

Best Practices ​

  1. Error Handling: Handle request errors on the client and return a non-2xx response when validation or provider setup fails.
    tsx
    const { error } = useChat()
    if (error) return <p role="alert">The reply could not be completed.</p>
  2. Initial Messages: Load saved messages through the transport or pass them as the initial state supported by your installed UI version.
    tsx
    useChat({ messages: dbMessages })
  3. Request data: Send extra fields through the transport when the server needs a user or conversation identifier.
    tsx
    new DefaultChatTransport({
      api: '/api/chat',
      body: { userId: '123' },
    })

AI SDK Core Quick Reference ​

Verified against the official AI SDK documentation on 2026-11-01 (pages labelled "v7 Latest"). The current examples use AI SDK 7 APIs. Provider-specific model setup and versioned options still require checking the installed provider documentation.

TopicWhat the official docs say
Text generationAI SDK Core has two entry points: generateText (one-shot) and streamText (streaming).
StreamingConsume textStream or adapt result.stream to UI. Backpressure means an unconsumed stream can stall.
Tool definitionDefine a tool with description, a required inputSchema, and an optional execute function. The input schema validates tool-call arguments.
Multi-step callsPass stopWhen: isStepCount(5) to bound a loop. A step contains one model generation and any tool executions requested in that step.
Structured outputPass an independent output: Output.object({ schema }) to validate a generated object. Use Output.json() when only valid JSON is required.

Practical notes ​

  • Write the tool schema carefully: it defines the input shape the model sees. Structured output takes its own, separate schema through output; the two schemas are independent.
  • Set an explicit stopWhen condition for multi-step tool loops so the step count is bounded.
  • Always consume the stream, otherwise the call does not finish.

Not confirmed by this review ​

  • This page does not prescribe provider-specific package names or model IDs. Verify those against the provider you install.
  • The exact UI message shape and transport options are versioned APIs. Keep ai and @ai-sdk/react on compatible major versions.

Sources (fetched 2026-11-30):

Next Steps ​

Built for frontend engineers · Powered by VitePress