generateText is a Vercel AI SDK utility for producing a complete text response from a prompt or message sequence. It fits noninteractive tasks such as drafting emails, summarizing web pages, and replacing nonstreaming chat-completions calls. section 3.1.3
Use generateText to connect application behavior with a provider-neutral language model interface:
- Pass a model returned by a Vercel AI SDK provider, such as OpenAI, Anthropic, Google Generative AI, or another supported provider. section 3.1.3 section 3.3.2
- Supply either a prompt or structured system and user messages, then read the generated content from the returned text property. section 3.1.3
- Change the model parameter to switch providers without rewriting the surrounding generation logic. section 3.3.2
Next.js route handler
Install the SDK and provider package, configure the provider with an environment variable, and call generateText from a POST handler. The handler can prepend a system message, preserve incoming messages, extract result.text, and return an assistant message as JSON. import { createGoogleGenerativeAI } from '@ai-sdk/google'; import { generateText } from 'ai'; const model = createGoogleGenerativeAI({ apiKey: process.env.GEMINI_API_KEY || '' }); const result = await generateText({ model: model('gemini-2.0-flash'), maxTokens: 512, messages: [ { role: 'system', content: 'I am happy to assist you.' }, ...messages ] }); return Response.json({ message: { role: 'assistant', content: result.text } }); section 3.1.3
Listing 3.1 generateText example
import { generateText } from 'ai';
const { text } = await generateText({ #1
model, #2
messages: [
{
role: 'system',
content: "I'm happy to assistyou in any way I can.
How can I be of service today?",
},
{ role: 'user', content: text },
],
});
Inspect the minimal generateText call using a model, system message, and user content. section 3.1.3
Listing 3.10 Calling the generateText function with different models
import { generateText } from 'ai';
import { openai } from '@ai-sdk/openai';
import { anthropic } from '@ai-sdk/anthropic';
// OpenAI example
const openaiResponse = await generateText({.
model: openai('gpt-3.5-turbo'),
prompt: 'What is 7+7 and why? ',
});
// Anthropic example
const anthropicResponse = await generateText({.
model: anthropic('claude-v1'),
prompt: ''What is 7+7 and why?',
});
Compare equivalent calls using OpenAI and Anthropic models while keeping the generation interface unchanged. section 3.3.2
