Generating Text and Structured Objects
The Vercel AI SDK provides two primary server-side functions for generating non-streaming content: generateText and generateObject.
1. Using generateText
Use generateText for simple question-and-answer exchanges or summary requests that do not require streaming:
// src/services/aiService.ts
import { generateText } from "ai";
import { defaultModel } from "../lib/models";
export async function askQuestion(prompt: string) {
const response = await generateText({
model: defaultModel,
prompt: prompt,
system: "You are a senior code reviewer. Give short and direct answers.",
});
console.log("Raw output text:", response.text);
console.log("Total tokens consumed:", response.usage.totalTokens);
return response.text;
}2. Using generateObject with Zod
To guarantee that the model outputs structured JSON that matches your database schema, combine generateObject with the Zod library:
import { generateObject } from "ai";
import { z } from "zod";
import { defaultModel } from "../lib/models";
// Define output structure rules using Zod
const UserProfileSchema = z.object({
fullName: z.string(),
companyRole: z.string(),
skills: z.array(z.string()),
});
export async function parseUserProfile(bioText: string) {
const { object } = await generateObject({
model: defaultModel,
schema: UserProfileSchema,
prompt: bioText,
});
// object is typed as: { fullName: string; companyRole: string; skills: string[] }
console.log("Parsed skills count:", object.skills.length);
return object;
}3. Selecting the Right Function
- Use
generateTextfor general copywriting, text translation, markdown summarization, or whenever conversational dialogue is the target. - Use
generateObjectfor parsing search intent, formatting user profile fields, generating charts datasets, or populating relational database columns.
Published on Last updated: