Skip to main content
Generates a structured, typed object for a given prompt and schema using a language model, streaming the output. If you do not want to stream the output, use generateObject instead.
streamObject is deprecated. Use streamText with an output setting instead.
import { streamObject } from 'ai';
import { openai } from '@ai-sdk/openai';
import { z } from 'zod';

const result = 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 result.partialObjectStream) {
  console.log(partialObject);
}

Parameters

model
LanguageModel
required
The language model to use.
schema
FlexibleSchema
The schema of the object that the model should generate. Required unless using output: 'enum' or output: 'no-schema'.
schemaName
string
Optional name of the output that should be generated. Used by some providers for additional LLM guidance, e.g., via tool or schema name.
schemaDescription
string
Optional description of the output that should be generated. Used by some providers for additional LLM guidance, e.g., via tool or schema description.
output
'object' | 'array' | 'enum' | 'no-schema'
The type of the output.
  • 'object': The output is an object.
  • 'array': The output is an array.
  • 'enum': The output is an enum.
  • 'no-schema': The output is not a schema.
enum
Array<string>
The enum values that the model should use. Required when output: 'enum'.
prompt
string
A simple text prompt. You can either use prompt or messages but not both.
messages
Array<CoreMessage>
A list of messages. You can either use prompt or messages but not both.
system
string
A system message that will be part of the prompt.
maxOutputTokens
number
Maximum number of tokens to generate.
temperature
number
Temperature setting. The value is passed through to the provider. The range depends on the provider and model. It is recommended to set either temperature or topP, but not both.
topP
number
Nucleus sampling. The value is passed through to the provider. The range depends on the provider and model. It is recommended to set either temperature or topP, but not both.
topK
number
Only sample from the top K options for each subsequent token. Used to remove “long tail” low probability responses. Recommended for advanced use cases only. You usually only need to use temperature.
presencePenalty
number
Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt. The value is passed through to the provider. The range depends on the provider and model.
frequencyPenalty
number
Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases. The value is passed through to the provider. The range depends on the provider and model.
seed
number
The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results.
maxRetries
number
default:"2"
Maximum number of retries. Set to 0 to disable retries.
abortSignal
AbortSignal
An optional abort signal that can be used to cancel the call.
headers
Record<string, string>
Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.
experimental_repairText
RepairTextFunction
A function that attempts to repair the raw output of the model to enable JSON parsing.
experimental_download
DownloadFunction
Custom download function to use for URLs. By default, files are downloaded if the model does not support the URL for the given media type.
experimental_telemetry
TelemetrySettings
Optional telemetry configuration (experimental).
providerOptions
ProviderOptions
Additional provider-specific options. They are passed through to the provider from the AI SDK and enable provider-specific functionality that can be fully encapsulated in the provider.
onError
(error: Error) => void
Callback that is invoked when an error occurs during streaming. You can use it to log errors. The stream processing will pause until the callback promise is resolved.
onFinish
(event: OnFinishEvent) => void
Callback that is called when the LLM response and the final object validation are finished.

Returns

partialObjectStream
AsyncIterableStream<DeepPartial<RESULT>>
A stream of partial object updates. The stream returns deep partial objects as they are generated.
elementStream
AsyncIterableStream<ELEMENT>
A stream of array elements. Only available when output: 'array'.
textStream
AsyncIterableStream<string>
A text stream that returns only the generated text deltas.
fullStream
AsyncIterableStream<ObjectStreamPart>
A stream with all events, including partial objects, text deltas, and finish events.
object
Promise<RESULT>
A promise that resolves to the final generated object (typed according to the schema).
usage
Promise<LanguageModelUsage>
A promise that resolves to the token usage of the generated response.
finishReason
Promise<FinishReason>
A promise that resolves to the reason why the generation finished.
warnings
Promise<Array<CallWarning>>
A promise that resolves to warnings from the model provider (e.g., unsupported settings).
response
Promise<LanguageModelResponseMetadata>
A promise that resolves to response metadata.
request
Promise<LanguageModelRequestMetadata>
A promise that resolves to request metadata.
providerMetadata
Promise<ProviderMetadata>
A promise that resolves to additional provider-specific metadata.
toTextStreamResponse
(init?: ResponseInit) => Response
Creates a simple text stream response. The response is a text/plain stream that streams the text parts.
pipeTextStreamToResponse
(response: ServerResponse, init?: ResponseInit) => void
Pipes the text stream to a Node.js response-like object.

Examples

Basic streaming

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

const result = 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 result.partialObjectStream) {
  console.clear();
  console.log(partialObject);
}

const finalObject = await result.object;
console.log(finalObject);

Array streaming

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

const result = streamObject({
  model: openai('gpt-4-turbo'),
  output: 'array',
  schema: z.object({
    name: z.string(),
    capital: z.string(),
  }),
  prompt: 'Generate 10 countries and their capitals',
});

for await (const country of result.elementStream) {
  console.log(country);
}

With finish callback

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

const result = streamObject({
  model: openai('gpt-4-turbo'),
  schema: z.object({
    title: z.string(),
    content: z.string(),
  }),
  prompt: 'Generate a blog post about AI',
  onFinish({ object, error }) {
    if (error) {
      console.error('Validation error:', error);
    } else {
      console.log('Final object:', object);
    }
  },
});

for await (const partialObject of result.partialObjectStream) {
  console.log(partialObject);
}