> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/vercel/ai/llms.txt
> Use this file to discover all available pages before exploring further.

# streamObject

> API reference for the streamObject function

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`](/reference/ai-sdk-core/generate-object) instead.

<Note>
  `streamObject` is deprecated. Use [`streamText`](/reference/ai-sdk-core/stream-text) with an `output` setting instead.
</Note>

```typescript theme={null}
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

<ParamField path="model" type="LanguageModel" required>
  The language model to use.
</ParamField>

<ParamField path="schema" type="FlexibleSchema">
  The schema of the object that the model should generate.
  Required unless using `output: 'enum'` or `output: 'no-schema'`.
</ParamField>

<ParamField path="schemaName" type="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.
</ParamField>

<ParamField path="schemaDescription" type="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.
</ParamField>

<ParamField path="output" type="'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.
</ParamField>

<ParamField path="enum" type="Array<string>">
  The enum values that the model should use. Required when `output: 'enum'`.
</ParamField>

<ParamField path="prompt" type="string">
  A simple text prompt. You can either use `prompt` or `messages` but not both.
</ParamField>

<ParamField path="messages" type="Array<CoreMessage>">
  A list of messages. You can either use `prompt` or `messages` but not both.
</ParamField>

<ParamField path="system" type="string">
  A system message that will be part of the prompt.
</ParamField>

<ParamField path="maxOutputTokens" type="number">
  Maximum number of tokens to generate.
</ParamField>

<ParamField path="temperature" type="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.
</ParamField>

<ParamField path="topP" type="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.
</ParamField>

<ParamField path="topK" type="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.
</ParamField>

<ParamField path="presencePenalty" type="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.
</ParamField>

<ParamField path="frequencyPenalty" type="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.
</ParamField>

<ParamField path="seed" type="number">
  The seed (integer) to use for random sampling.
  If set and supported by the model, calls will generate deterministic results.
</ParamField>

<ParamField path="maxRetries" type="number" default="2">
  Maximum number of retries. Set to 0 to disable retries.
</ParamField>

<ParamField path="abortSignal" type="AbortSignal">
  An optional abort signal that can be used to cancel the call.
</ParamField>

<ParamField path="headers" type="Record<string, string>">
  Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.
</ParamField>

<ParamField path="experimental_repairText" type="RepairTextFunction">
  A function that attempts to repair the raw output of the model to enable JSON parsing.
</ParamField>

<ParamField path="experimental_download" type="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.
</ParamField>

<ParamField path="experimental_telemetry" type="TelemetrySettings">
  Optional telemetry configuration (experimental).
</ParamField>

<ParamField path="providerOptions" type="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.
</ParamField>

<ParamField path="onError" type="(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.
</ParamField>

<ParamField path="onFinish" type="(event: OnFinishEvent) => void">
  Callback that is called when the LLM response and the final object validation are finished.
</ParamField>

## Returns

<ResponseField name="partialObjectStream" type="AsyncIterableStream<DeepPartial<RESULT>>">
  A stream of partial object updates. The stream returns deep partial objects as they are generated.
</ResponseField>

<ResponseField name="elementStream" type="AsyncIterableStream<ELEMENT>">
  A stream of array elements. Only available when `output: 'array'`.
</ResponseField>

<ResponseField name="textStream" type="AsyncIterableStream<string>">
  A text stream that returns only the generated text deltas.
</ResponseField>

<ResponseField name="fullStream" type="AsyncIterableStream<ObjectStreamPart>">
  A stream with all events, including partial objects, text deltas, and finish events.
</ResponseField>

<ResponseField name="object" type="Promise<RESULT>">
  A promise that resolves to the final generated object (typed according to the schema).
</ResponseField>

<ResponseField name="usage" type="Promise<LanguageModelUsage>">
  A promise that resolves to the token usage of the generated response.
</ResponseField>

<ResponseField name="finishReason" type="Promise<FinishReason>">
  A promise that resolves to the reason why the generation finished.
</ResponseField>

<ResponseField name="warnings" type="Promise<Array<CallWarning>>">
  A promise that resolves to warnings from the model provider (e.g., unsupported settings).
</ResponseField>

<ResponseField name="response" type="Promise<LanguageModelResponseMetadata>">
  A promise that resolves to response metadata.
</ResponseField>

<ResponseField name="request" type="Promise<LanguageModelRequestMetadata>">
  A promise that resolves to request metadata.
</ResponseField>

<ResponseField name="providerMetadata" type="Promise<ProviderMetadata>">
  A promise that resolves to additional provider-specific metadata.
</ResponseField>

<ResponseField name="toTextStreamResponse" type="(init?: ResponseInit) => Response">
  Creates a simple text stream response. The response is a `text/plain` stream that streams the text parts.
</ResponseField>

<ResponseField name="pipeTextStreamToResponse" type="(response: ServerResponse, init?: ResponseInit) => void">
  Pipes the text stream to a Node.js response-like object.
</ResponseField>

## Examples

### Basic streaming

```typescript theme={null}
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

```typescript theme={null}
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

```typescript theme={null}
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);
}
```
