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 { openai } from '@ai-sdk/openai';import { streamObject } from 'ai';import { z } from 'zod';
const { partialObjectStream } = streamObject({ 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.',});
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 { openai } from '@ai-sdk/openai';import { streamObject } from 'ai';import { z } from 'zod';
const { elementStream } = streamObject({ 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.',});
for await (const hero of elementStream) { console.log(hero);}Example: generate JSON without a schema
import { openai } from '@ai-sdk/openai';import { streamObject } from 'ai';
const { partialObjectStream } = streamObject({ model: openai('gpt-4-turbo'), output: 'no-schema', prompt: 'Generate a lasagna recipe.',});
for await (const partialObject of partialObjectStream) { console.clear(); console.log(partialObject);}To see streamObject in action, check out the additional examples.
Import
import { streamObject } from "ai"API Signature
Parameters
model:
LanguageModel
output:
'object' | 'array' | 'no-schema' | undefined
mode:
'auto' | 'json' | 'tool'
schema:
Zod Schema | JSON Schema
schemaName:
string | undefined
schemaDescription:
string | undefined
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_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:
CompletionTokenUsage
CompletionTokenUsage
promptTokens:
number
completionTokens:
number
totalTokens:
number
providerMetadata:
Record<string,Record<string,JSONValue>> | undefined
object:
T | undefined
error:
unknown | undefined
warnings:
Warning[] | undefined
response?:
Response
Response
id:
string
model:
string
timestamp:
Date
headers?:
Record<string, string>
Returns
usage:
Promise<CompletionTokenUsage>
CompletionTokenUsage
promptTokens:
number
completionTokens:
number
totalTokens:
number
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<RequestMetadata>
RequestMetadata
body:
string
response?:
Promise<ResponseMetadata>
ResponseMetadata
id:
string
model:
string
timestamp:
Date
headers?:
Record<string, string>
warnings:
Warning[] | 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>