Use generateObject to get structured data from an LLM with the AI SDK

9/2/2025

#ai#typescript

LLMs often return free-form text, which can be hard to parse.
With the AI SDK, you can use generateObject to directly enforce a typed JSON schema — no more brittle regex or string parsing.

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

const result = await generateObject({
  model: openai('gpt-4.1'),
  schema: z.object({
    name: z.string(),
    age: z.number(),
  }), 
  prompt: "Extract the person's name and age: John is 42 years old.",
});

console.log(result.object);
// → { name: "John", age: 42 }

Why it’s great:

  • Enforces strict structure with Zod
  • No messy post-processing
  • Safer integration with TypeScript

Use generateObject whenever you want predictable, typed data from an LLM.

Learn more about generateObject in the AI SDK documentation.

Start your scalable and production-ready SaaS today

Save endless hours of development time and focus on what's important for your customers with our SaaS starter kits for Next.js, Nuxt 3, and TanStack Start

Get started

Stay up to date

Sign up for our newsletter and we will keep you updated on everything going on with supastarter.