Skip to main content
← Guides

Guide

Vercel AI SDK v4: generateText, streamText, Tools 2026

Updated PkgPulse Team9 min read
0

Maintain an app pinned to Vercel AI SDK v4. Compare generateText, streamText, and generateObject, and use the v4 data stream with React.

Contents

TL;DR

This guide describes apps pinned to Vercel AI SDK v4. Use generateText for a complete text result, streamText for a progressive response, and generateObject for schema-validated data. For a React chat UI, return streamText(...).toDataStreamResponse() from the route handler and read the stream with the v4 useChat hook. Vercel’s archived v4 docs mark this release line as unsupported.

Key Takeaways

  • generateText is for non-streaming LLM calls with text output — simple Q&A, batch processing, classification
  • streamText is for real-time streaming — chat interfaces, progressive content generation, anything where waiting for the full response hurts UX
  • generateObject returns structured, schema-validated objects — the single best feature in v4 for structured AI outputs without prompt engineering
  • Tool calling (function calling) lets LLMs invoke TypeScript functions — the foundation of AI agents
  • maxSteps enables automatic multi-step tool execution — the LLM calls a tool, gets results, calls another tool, without your code managing the loop
  • Provider middleware in v4 lets you add caching, logging, and rate limiting to any provider call

Install the v4 dependencies

npm install --save-exact ai@4.3.19 @ai-sdk/react@1.2.12 zod@3.25.76 @ai-sdk/openai@1.3.24 @ai-sdk/anthropic@1.2.12

Use these versions in an existing React app. Set OPENAI_API_KEY and OPENAI_MODEL on the server for the OpenAI examples. Set ANTHROPIC_API_KEY and ANTHROPIC_MODEL for the Anthropic call. Pick model IDs your account and the pinned adapters support.

Why the AI SDK Matters

Without an abstraction layer, every LLM provider has a different API:

// OpenAI
const response = await openai.chat.completions.create({ model, messages, stream })

// Anthropic
const response = await anthropic.messages.create({ model, messages, max_tokens })

// Google Gemini
const response = await generativeModel.generateContent({ contents, config })

Every provider has different request formats, response shapes, streaming protocols, error codes, and token counting semantics. The Vercel AI SDK normalizes all of this:

import { generateText } from 'ai'
import { openai } from '@ai-sdk/openai'
import { anthropic } from '@ai-sdk/anthropic'

const prompt = 'Explain the difference between async and defer in HTML script tags.'
const { text: openaiText } = await generateText({
  model: openai(process.env.OPENAI_MODEL!),
  prompt,
})
const { text: anthropicText } = await generateText({
  model: anthropic(process.env.ANTHROPIC_MODEL!),
  prompt,
})
console.log(openaiText, anthropicText)

The calls use the same SDK interface. Check model capabilities and provider-specific options before switching.


Core APIs in AI SDK v4

generateText — Non-Streaming Text Generation

generateText makes a complete LLM request and returns when the model is done:

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

const { text, usage, finishReason } = await generateText({
  model: openai(process.env.OPENAI_MODEL!),
  system: 'You are a helpful assistant.',
  prompt: 'Explain the difference between async and defer in HTML script tags.',
})

console.log(text)
// → "The `async` attribute..."

console.log(usage)
// → { promptTokens: 42, completionTokens: 187, totalTokens: 229 }

When to use generateText:

  • Classification tasks (tag this email, categorize this content)
  • Batch processing where you want to wait for complete output
  • Generating content that gets stored (product descriptions, summaries)
  • Single-turn Q&A where streaming adds complexity without UX benefit

The messages array supports full conversation history:

const { text } = await generateText({
  model: openai(process.env.OPENAI_MODEL!),
  messages: [
    { role: 'user', content: 'What is tRPC?' },
    { role: 'assistant', content: 'tRPC is a library...' },
    { role: 'user', content: 'How does it compare to GraphQL?' },
  ],
})

streamText — Streaming Text Generation

streamText lets you render text as chunks arrive.

import { streamText } from 'ai'
import { openai } from '@ai-sdk/openai'

const result = streamText({
  model: openai(process.env.OPENAI_MODEL!),
  prompt: 'Write a haiku about TypeScript.',
})

// Stream to stdout
for await (const chunk of result.textStream) {
  process.stdout.write(chunk)
}

toDataStreamResponse() returns an HTTP Response whose body streams the v4 data stream protocol. Use result.textStream to consume plain text chunks on the server. On the client, v4 useChat handles chat messages and tool calls. v4 useCompletion reads the text and data parts only.

In a Next.js App Router route handler:

// app/api/chat/route.ts
import { streamText } from 'ai'
import { openai } from '@ai-sdk/openai'

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

  const result = streamText({
    model: openai(process.env.OPENAI_MODEL!),
    messages,
  })

  return result.toDataStreamResponse()
}

Client-side with useChat:

// app/chat/page.tsx
'use client'
import { useChat } from '@ai-sdk/react'

export default function ChatPage() {
  const { messages, input, handleInputChange, handleSubmit } = useChat()

  return (
    <div>
      {messages.map(m => (
        <div key={m.id}>{m.role}: {m.content}</div>
      ))}
      <form onSubmit={handleSubmit}>
        <input value={input} onChange={handleInputChange} />
        <button type="submit">Send</button>
      </form>
    </div>
  )
}

useChat manages message state and reads the stream from the chat endpoint.

generateObject — Structured Output

generateObject is the feature that makes AI SDK v4 indispensable for production applications. Instead of returning text, it returns a schema-validated TypeScript object:

import { generateObject } from 'ai'
import { openai } from '@ai-sdk/openai'
import { z } from 'zod'

const { object } = await generateObject({
  model: openai(process.env.OPENAI_MODEL!),
  schema: z.object({
    title: z.string(),
    tags: z.array(z.string()).max(5),
    sentiment: z.enum(['positive', 'neutral', 'negative']),
    confidence: z.number().min(0).max(1),
  }),
  prompt: 'Analyze this review: "Great product, fast shipping, would buy again!"',
})

// object is typed as:
// {
//   title: string,
//   tags: string[],
//   sentiment: 'positive' | 'neutral' | 'negative',
//   confidence: number
// }
console.log(object.sentiment) // → 'positive'
console.log(object.confidence) // → 0.97

generateObject can use JSON mode or tool calling to get structured output, then validates the result against the schema. In the pinned fixture, a mock returned valid JSON with the wrong field type. The SDK raised AI_NoObjectGeneratedError after one model call with maxRetries: 2. Handle validation failures separately from retryable provider errors. v4 generateObject reference · v4 object error reference

streamObject — the streaming equivalent — progressively yields object properties as they arrive, enabling UI that populates fields in real time rather than waiting for the complete object.


Tool Calling in v4

Tools let LLMs call TypeScript functions during generation — the primitive behind AI agents, RAG, and any LLM that needs to take actions or retrieve information.

Defining Tools

import { generateText, tool } from 'ai'
import { openai } from '@ai-sdk/openai'
import { z } from 'zod'

const { text, toolCalls, toolResults } = await generateText({
  model: openai(process.env.OPENAI_MODEL!),
  tools: {
    getWeather: tool({
      description: 'Get the current weather for a city',
      parameters: z.object({
        city: z.string().describe('The city name'),
        unit: z.enum(['celsius', 'fahrenheit']).default('celsius'),
      }),
      execute: async ({ city, unit }) => {
        // Your actual implementation
        return { temperature: 18, condition: 'partly cloudy', unit }
      },
    }),
  },
  prompt: 'What is the weather like in Paris right now?',
})

The model supplies the tool arguments. Here execute returns sample weather data. An application can instead look up the requested city with its own weather service.

Multi-Step Tool Calling with maxSteps

To let the model summarize the weather result, add maxSteps: 2 to the generateText options above. The first generation can request the tool. The second can use its result to write the answer. The limit counts every generation step, including a final text response. Inspect the returned steps array to see the tool calls, results and text for each step. AI SDK v4 multi-step calls


useObject — Streaming Structured Data to React

Pair experimental_useObject with streamObject when the React UI needs to show partial structured data.

'use client'
import { experimental_useObject as useObject } from '@ai-sdk/react'
import { z } from 'zod'

const schema = z.object({
  summary: z.string(),
  keyPoints: z.array(z.string()),
  readingTime: z.number(),
})

export default function SummaryPage() {
  const { object, submit, isLoading } = useObject({
    api: '/api/summarize',
    schema,
  })

  return (
    <div>
      <button onClick={() => submit({ url: 'https://example.com/article' })}>
        Summarize
      </button>
      {isLoading && <p role="status">Generating summary…</p>}
      {object?.summary && <p>{object.summary}</p>}
      <ul>
        {object?.keyPoints?.map(point => point && <li key={point}>{point}</li>)}
      </ul>
    </div>
  )
}

The object is typed from the schema and populates field by field as the LLM generates — object.summary might be available before object.keyPoints finishes streaming.


Provider Middleware

Use wrapLanguageModel when several callers need the same behavior around model requests. For example, a wrapGenerate hook can time the call to doGenerate() and return its result. Streaming requests use a separate wrapStream hook. AI SDK v4 language model middleware


AI SDK vs Alternatives

FactorAI SDK (ai)LangChain.jsDirect SDK
Provider abstractionShared interface through provider adaptersProvider integrationsProvider-specific API
Streaming✅ Native⚠️ ComplexVaries
React hooks✅ useChat, useCompletion, useObject❌ None❌
Structured output✅ generateObject✅ (via chains)⚠️ Manual
Agent support✅ maxSteps✅ LangGraph❌
Learning curveLowHighLow

For most Next.js applications building AI features, the AI SDK is the right starting point. LangChain.js is worth considering for complex agent workflows with memory, retrieval, and multi-agent orchestration.


When Not to Use the AI SDK

The AI SDK is not always the right choice:

  • Pure Python data pipelines — use the provider's Python SDK directly or LangChain Python
  • Complex agentic workflows — consider Mastra (TypeScript), LangGraph (Python/TS), or AutoGen
  • On-device inference — the AI SDK targets API-based providers; for on-device models, use onnxruntime or llama.cpp bindings
  • High-throughput batch processing — the AI SDK's abstractions add overhead; direct provider calls may be better for 100K+ batch jobs

Error Handling and Retry Patterns in Production

Production LLM applications need robust error handling because provider APIs have rate limits, transient network failures, and occasional model-level errors (content filters, context length exceeded). The AI SDK surfaces these as typed errors that you can pattern-match against: APICallError for HTTP errors from the provider, NoTextGeneratedError when a tool-only response produces no text, and RetryError when all retry attempts are exhausted.

The SDK's built-in maxRetries option (default: 2) handles transient failures automatically with exponential backoff. For production use, configure a higher value and add provider middleware for circuit-breaking: if a provider returns 5xx errors for three consecutive requests, pause further calls for 30 seconds before retrying. This prevents a cascading failure where your application hammers a degraded provider endpoint. Cloudflare Workers AI and Together AI are common fallback providers when OpenAI's API is degraded — the AI SDK's one-line provider swap makes this fallback straightforward to implement.

Cost Management and Token Budgets

Read token usage from generateText or await streamText’s usage promise. Keep counts by provider and model so you can apply the rate for the deployment you run. Use maxTokens to cap the output and record a finishReason of length when the model stops at that limit.


Source notes

Methodology

  • Fixtures use ai@4.3.19 and zod@3.25.76 with mock models. They check the streaming HTTP response, data framing, and schema-validation failure.
  • Provider and UI examples illustrate the v4 APIs.

Compare AI SDK with other LLM client libraries on PkgPulse — download trends, bundle sizes, and dependency health.

Related: Vercel AI SDK vs OpenAI SDK vs Anthropic SDK 2026 · LangChain.js vs Vercel AI SDK 2026 · Mastra vs LangChain.js vs Genkit 2026