streamObject

Stream a structured object as its fields fill in.

Streams partial versions of a structured result while the model is still generating it, so a UI can render fields as they land instead of waiting for the closing brace.

For array schemas, elementStream yields each complete element as it finishes, which is usually what you want for a list that renders row by row.

let stream = streamObject(
  model: AnthropicModel("claude-sonnet-5"),
  schema: schema,
  prompt: "Three startup ideas."
)

for try await partial in stream.partialObjectStream {
  render(partial)
}

Signature

func streamObject(
    model: any LanguageModel,
    schema: JSONValue,
    schemaName: String = "response",
    schemaDescription: String? = nil,
    messages: [Message] = [],
    system: String? = nil,
    prompt: String? = nil,
    maxOutputTokens: Int = 1024,
    temperature: Double? = nil,
    providerOptions: JSONValue? = nil,
    maxRetries: Int = 2
) -> StreamObjectResult

Defined in Sources/AI/Core/GenerateObject.swift.

Parameters

ParameterTypeDefault
modelany LanguageModelrequired
schemaJSONValuerequired
schemaNameString"response"
schemaDescriptionString?nil
messages[Message][]
systemString?nil
promptString?nil
maxOutputTokensInt1024
temperatureDouble?nil
providerOptionsJSONValue?nil
maxRetriesInt2

Overloads

1 other form of this function exists:

func streamObject(
    model: any LanguageModel,
    schema: Schema,
    schemaName: String = "response",
    schemaDescription: String? = nil,
    messages: [Message] = [],
    system: String? = nil,
    prompt: String? = nil,
    maxOutputTokens: Int = 1024,
    temperature: Double? = nil,
    providerOptions: JSONValue? = nil,
    maxRetries: Int = 2
) -> StreamObjectResult

Returns

StreamObjectResult with partialObjectStream, elementStream for array schemas, and awaitable object, usage, and finishReason.

See also