Function: streamObject()
streamObject<
T,K>(opts):StreamObjectResult<output<T>,StreamObjectElement<output<T>,K>>
Defined in: packages/agentos/src/api/streamObject.ts:749
Streams a structured object by incrementally parsing JSON as the LLM produces tokens, then validates the final result against a Zod schema.
Returns immediately with a StreamObjectResult containing async
iterables and promises. The underlying LLM call begins lazily when a
consumer starts iterating partialObjectStream or elementStream;
awaiting a promise alone starts no request.
With StreamObjectOptions.elements naming one array field of the
schema, elementStream yields each element of that array as soon as it is
complete, parsed by the array's element schema.
The stream is read through StreamTextResult.fullStream, so the
error part that ends a failed stream ends it as cut:
partialObjectStream ends, elementStream throws the failure, object
rejects with Stream interrupted: <message> and reportedUsage resolves
to undefined. When every iterable that was read stops before the stream
ends, the request is closed and the result settles the same way.
Type Parameters
T
T extends ZodType<unknown, unknown, $ZodTypeInternals<unknown, unknown>>
The Zod schema type. Partial objects are typed as
DeepPartial<z.infer<T>>, and the final object promise resolves
to z.infer<T>.
K
K extends string = never
The field named by elements, inferred from the call;
elementStream yields StreamObjectElement<z.infer<T>, K>.
Parameters
opts
StreamObjectOptions<T, K>
Streaming generation options including the Zod schema, prompt/messages, and optional provider/model overrides.
Returns
StreamObjectResult<output<T>, StreamObjectElement<output<T>, K>>
A StreamObjectResult with partialObjectStream,
elementStream, object, text, usage, reportedUsage and
skipped properties.
Throws
When elements names no array field of the schema,
at the call, before any request is sent.
Examples
import { z } from 'zod';
import { streamObject } from '@framers/agentos';
const result = streamObject({
provider: 'openai',
model: 'gpt-4o',
schema: z.object({ name: z.string(), hobbies: z.array(z.string()) }),
prompt: 'Create a profile for a fictional character.',
});
for await (const partial of result.partialObjectStream) {
console.log('partial:', partial);
}
const final = await result.object;
console.log('final:', final);
const answer = streamObject({
provider: 'openai',
schema: z.object({ sentences: z.array(z.object({ text: z.string(), passage: z.number() })) }),
elements: 'sentences',
prompt: 'Answer from the passages, one sentence per claim.',
});
for await (const sentence of answer.elementStream) {
console.log(sentence.passage, sentence.text); // each sentence once it is complete
}
console.log(await answer.skipped, await answer.reportedUsage);
See
- generateObject for non-streaming structured output.
- streamText for plain text streaming.