streamObject()

Streams 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: stream an object using a schema

import { streamObject } from 'ai';
import { z } from 'zod';
const { partialObjectStream } = streamObject({
model: "anthropic/claude-sonnet-4.5",
schema: z.object({
recipe: z.object({
name: z.string(),
ingredients: z.array(z.string()),
steps: z.array(z.string()),
}),
}),
prompt: 'Generate a lasagna recipe.',
});
for await (const partialObject of partialObjectStream) {
console.clear();
console.log(partialObject);
}

Example: stream an array using a schema

For arrays, you specify the schema of the array items. You can use elementStream to get the stream of complete array elements.

import { streamObject } from 'ai';
import { z } from 'zod';
const { elementStream } = streamObject({
model: "anthropic/claude-sonnet-4.5",
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.',
});
for await (const hero of elementStream) {
console.log(hero);
}

Example: generate JSON without a schema

import { streamObject } from 'ai';
const { partialObjectStream } = streamObject({
model: "anthropic/claude-sonnet-4.5",
output: 'no-schema',
prompt: 'Generate a lasagna recipe.',
});
for await (const partialObject of partialObjectStream) {
console.clear();
console.log(partialObject);
}

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 { streamObject } from 'ai';
const { partialObjectStream } = streamObject({
model: "anthropic/claude-sonnet-4.5",
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."',
});

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

Import

import { streamObject } from "ai"

API Signature

Parameters

model:

LanguageModel

output:

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

schema:

Zod Schema | JSON Schema

schemaName:

string | undefined

schemaDescription:

string | undefined

system:

string

prompt:

string | Array<SystemModelMessage | UserModelMessage | AssistantModelMessage | ToolModelMessage>

messages:

Array<SystemModelMessage | UserModelMessage | AssistantModelMessage | ToolModelMessage>
SystemModelMessage

role:

'system'

content:

string
UserModelMessage

role:

'user'

content:

string | Array<TextPart | ImagePart | FilePart>
TextPart

type:

'text'

text:

string
ImagePart

type:

'image'

image:

string | Uint8Array | Buffer | ArrayBuffer | URL

mediaType?:

string
FilePart

type:

'file'

data:

string | Uint8Array | Buffer | ArrayBuffer | URL

mediaType:

string
AssistantModelMessage

role:

'assistant'

content:

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

type:

'text'

text:

string
ReasoningPart

type:

'reasoning'

text:

string
FilePart

type:

'file'

data:

string | Uint8Array | Buffer | ArrayBuffer | URL

mediaType:

string

filename?:

string
ToolCallPart

type:

'tool-call'

toolCallId:

string

toolName:

string

args:

object based on zod schema
ToolModelMessage

role:

'tool'

content:

Array<ToolResultPart>
ToolResultPart

type:

'tool-result'

toolCallId:

string

toolName:

string

result:

unknown

isError?:

boolean

maxOutputTokens?:

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_download?:

(requestedDownloads: Array<{ url: URL; isUrlSupportedByModel: boolean }>) => Promise<Array<null | { data: Uint8Array; mediaType?: string }>>

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

onError?:

(event: OnErrorResult) => Promise<void> |void
OnErrorResult

error:

unknown

onFinish?:

(result: OnFinishResult) => void
OnFinishResult

usage:

LanguageModelUsage
LanguageModelUsage

inputTokens:

number | undefined

outputTokens:

number | undefined

totalTokens:

number | undefined

reasoningTokens?:

number | undefined

cachedInputTokens?:

number | undefined

providerMetadata:

ProviderMetadata | undefined

object:

T | undefined

error:

unknown | undefined

warnings:

CallWarning[] | undefined

response?:

Response
Response

id:

string

model:

string

timestamp:

Date

headers?:

Record<string, string>

Returns

usage:

Promise<LanguageModelUsage>
LanguageModelUsage

inputTokens:

number | undefined

outputTokens:

number | undefined

totalTokens:

number | undefined

reasoningTokens?:

number | undefined

cachedInputTokens?:

number | undefined

providerMetadata:

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

object:

Promise<T>

partialObjectStream:

AsyncIterableStream<DeepPartial<T>>

elementStream:

AsyncIterableStream<ELEMENT>

textStream:

AsyncIterableStream<string>

fullStream:

AsyncIterableStream<ObjectStreamPart<T>>
ObjectPart

type:

'object'

object:

DeepPartial<T>
TextDeltaPart

type:

'text-delta'

textDelta:

string
ErrorPart

type:

'error'

error:

unknown
FinishPart

type:

'finish'

finishReason:

FinishReason

logprobs?:

Logprobs

usage:

Usage

response?:

Response
Response

id:

string

model:

string

timestamp:

Date

request:

Promise<LanguageModelRequestMetadata>
LanguageModelRequestMetadata

body:

string

response:

Promise<LanguageModelResponseMetadata>
LanguageModelResponseMetadata

id:

string

model:

string

timestamp:

Date

headers?:

Record<string, string>

warnings:

CallWarning[] | undefined

pipeTextStreamToResponse:

(response: ServerResponse, init?: ResponseInit => void
ResponseInit

status?:

number

statusText?:

string

headers?:

Record<string, string>

toTextStreamResponse:

(init?: ResponseInit) => Response
ResponseInit

status?:

number

statusText?:

string

headers?:

Record<string, string>

More Examples

Streaming Object Generation with RSC
Streaming Object Generation with useObject
Streaming Partial Objects
Recording Token Usage
Recording Final Object