Function streamObject

  • 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 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 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<z.infer<T>, StreamObjectElement<z.infer<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.

    Example

    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);

    Example

    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