generateObject()

Generates a typed, structured object for a given prompt and schema using a language model.

It can be used to force the language model to return structured data, e.g. for information extraction, synthetic data generation, or classification tasks.

Example: generate an object using a schema

import { openai } from '@ai-sdk/openai';
import { generateObject } from 'ai';
import { z } from 'zod';
const { object } = await generateObject({
model: openai('gpt-4-turbo'),
schema: z.object({
recipe: z.object({
name: z.string(),
ingredients: z.array(z.string()),
steps: z.array(z.string()),
}),
}),
prompt: 'Generate a lasagna recipe.',
});
console.log(JSON.stringify(object, null, 2));

Example: generate an array using a schema

For arrays, you specify the schema of the array items.

import { openai } from '@ai-sdk/openai';
import { generateObject } from 'ai';
import { z } from 'zod';
const { object } = await generateObject({
model: openai('gpt-4-turbo'),
output: 'array',
schema: z.object({
name: z.string(),
class: z
.string()
.describe('Character class, e.g. warrior, mage, or thief.'),
description: z.string(),
}),
prompt: 'Generate 3 hero descriptions for a fantasy role playing game.',
});

Example: generate an enum

When you want to generate a specific enum value, you can set the output strategy to enum and provide the list of possible values in the enum parameter.

import { generateObject } from 'ai';
const { object } = await generateObject({
model: yourModel,
output: 'enum',
enum: ['action', 'comedy', 'drama', 'horror', 'sci-fi'],
prompt:
'Classify the genre of this movie plot: ' +
'"A group of astronauts travel through a wormhole in search of a ' +
'new habitable planet for humanity."',
});

Example: generate JSON without a schema

import { openai } from '@ai-sdk/openai';
import { generateObject } from 'ai';
const { object } = await generateObject({
model: openai('gpt-4-turbo'),
output: 'no-schema',
prompt: 'Generate a lasagna recipe.',
});

To see generateObject in action, check out the additional examples.

Import

import { generateObject } from "ai"

API Signature

Parameters

model:

LanguageModel

output:

'object' | 'array' | 'enum' | 'no-schema' | undefined

mode:

'auto' | 'json' | 'tool'

schema:

Zod Schema | JSON Schema

schemaName:

string | undefined

schemaDescription:

string | undefined

enum:

string[]

system:

string

prompt:

string

messages:

Array<CoreSystemMessage | CoreUserMessage | CoreAssistantMessage | CoreToolMessage> | Array<UIMessage>
CoreSystemMessage

role:

'system'

content:

string
CoreUserMessage

role:

'user'

content:

string | Array<TextPart | ImagePart | FilePart>
TextPart

type:

'text'

text:

string
ImagePart

type:

'image'

image:

string | Uint8Array | Buffer | ArrayBuffer | URL

mimeType?:

string
FilePart

type:

'file'

data:

string | Uint8Array | Buffer | ArrayBuffer | URL

mimeType:

string
CoreAssistantMessage

role:

'assistant'

content:

string | Array<TextPart | ReasoningPart | RedactedReasoningPart | ToolCallPart>
TextPart

type:

'text'

text:

string
ReasoningPart

type:

'reasoning'

text:

string

signature?:

string
RedactedReasoningPart

type:

'redacted-reasoning'

data:

string
ToolCallPart

type:

'tool-call'

toolCallId:

string

toolName:

string

args:

object based on schema
CoreToolMessage

role:

'tool'

content:

Array<ToolResultPart>
ToolResultPart

type:

'tool-result'

toolCallId:

string

toolName:

string

result:

unknown

isError?:

boolean

maxTokens?:

number

temperature?:

number

topP?:

number

topK?:

number

presencePenalty?:

number

frequencyPenalty?:

number

seed?:

number

maxRetries?:

number

abortSignal?:

AbortSignal

headers?:

Record<string, string>

experimental_repairText?:

(options: RepairTextOptions) => Promise<string>
RepairTextOptions

text:

string

error:

JSONParseError | TypeValidationError

experimental_telemetry?:

TelemetrySettings
TelemetrySettings

isEnabled?:

boolean

recordInputs?:

boolean

recordOutputs?:

boolean

functionId?:

string

metadata?:

Record<string, string | number | boolean | Array<null | undefined | string> | Array<null | undefined | number> | Array<null | undefined | boolean>>

providerOptions?:

Record<string,Record<string,JSONValue>> | undefined

Returns

object:

based on the schema

finishReason:

'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'other' | 'unknown'

usage:

CompletionTokenUsage
CompletionTokenUsage

promptTokens:

number

completionTokens:

number

totalTokens:

number

request?:

RequestMetadata
RequestMetadata

body:

string

response?:

ResponseMetadata
ResponseMetadata

id:

string

modelId:

string

timestamp:

Date

headers?:

Record<string, string>

body?:

unknown

warnings:

Warning[] | undefined

providerMetadata:

Record<string,Record<string,JSONValue>> | undefined

toJsonResponse:

(init?: ResponseInit) => Response

More Examples

Learn to generate structured data using a language model in Next.js
Learn to generate structured data using a language model in Node.js