Skip to main content

Overview

The public surface of the cognesy/instructor-struct package is intentionally small. Most interactions happen through a handful of classes that form a clear request-build-execute pipeline. Most users should stay at this level. The sections below explain each type in detail.

StructuredOutput

StructuredOutput is the main entry point to the library. It is an immutable builder — every with*() call returns a new copy, so you can safely reuse a configured instance across multiple requests.

Creating an Instance

Setting Request Parameters

The builder exposes fine-grained setters as well as a convenience with() method that accepts all parameters at once:
Or equivalently:

Executing and Retrieving Results

All of the above are shortcuts that internally call create() to obtain a PendingStructuredOutput, then forward to the appropriate method.

StructuredOutputRuntime

StructuredOutputRuntime assembles the runtime dependencies — inference provider, event dispatcher, configuration, and optional pipeline customizations (validators, transformers, deserializers, extractors).

Event Listeners

The runtime owns the event dispatcher. Attach listeners here for logging, monitoring, or debugging:

Pipeline Customization

You can inject custom validators, transformers, deserializers, and extractors at the runtime level. These apply to every request processed through the runtime:

PendingStructuredOutput

PendingStructuredOutput is the lazy execution handle returned by create(). No network call is made until you ask for a result. It coordinates one-shot access across get(), response(), inferenceResponse(), and stream().
The handle also provides typed accessors via the HandlesResultTypecasting trait: getString(), getInt(), getFloat(), getBoolean(), getArray(), getObject(), and getInstanceOf(SomeClass::class).

StructuredOutputStream

StructuredOutputStream exposes streaming reads when the request is executed with streaming enabled. It provides several iteration modes:

StructuredOutputResponse

StructuredOutputResponse is a read-only envelope that pairs the parsed value with the raw provider response:

Error Handling

When a request fails validation or deserialization, the package uses its retry mechanism (controlled by maxRetries in StructuredOutputConfig) to re-prompt the LLM with error feedback. If all retries are exhausted, an exception is thrown. Unrecoverable errors (e.g., network failures, missing response model) throw immediately without retry.