Skip to content
Star33Playground

Typed Structured Output

StableLast updated 2026-11-17 · 1d314a00a

Agents produce prose. Sometimes you need a typed object — an invoice, a parsed entity, a classification result — not a string. Typed structured output gives you that: call .withOutputSchema(schema) in the builder chain and the agent populates result.object as your declared type, while result.output carries the steered JSON answer the agent was guided to emit.

Two engines handle the extraction depending on what your stack supports:

  • Fast — single-shot native JSON enforcement (frontier models with native function calling and no tool overlap). Lowest latency.
  • Grounded — extracts, grounds each field against the tool-result evidence corpus from the run, surgically re-extracts missing required fields, and scores per-field confidence. Enables provenance + abstention. The differentiator for research or data-extraction agents.

The mode is auto-selected by default and can be overridden.

Stability: .withOutputSchema(), result.object / result.objectError and agent.streamObject() are stable. Grounded mode’s provenance, per-field confidence and abstention fields are unstable (see API Stability).

Works across all supported providers and tiers — Anthropic, OpenAI, Gemini, Groq, xAI, and local Ollama models (qwen, gemma, etc.) — making it a practical option even on self-hosted infrastructure.

.withOutputSchema() is a builder method — call it in the builder chain before .build(), then use agent.run() or agent.streamObject() on the built agent.

import { ReactiveAgents } from "reactive-agents";
import { z } from "zod";
const InvoiceSchema = z.object({
vendor: z.string(),
total: z.number(),
currency: z.string(),
lineItems: z.array(
z.object({ description: z.string(), amount: z.number() })
),
});
const agent = await ReactiveAgents.create()
.withName("invoice-extractor")
.withSystemPrompt("You extract structured data from documents.")
.withTools({ builtins: ["file-read"] })
.withOutputSchema(InvoiceSchema)
.build();
const result = await agent.run(
"Extract the invoice details from invoice.pdf"
);
if (result.object) {
// result.object is typed as z.infer<typeof InvoiceSchema>
console.log(`${result.object.vendor}: ${result.object.total} ${result.object.currency}`);
}

.withOutputSchema() accepts any Standard Schema v1 validator (Zod 3.24+, Valibot, ArkType) or an Effect Schema.Schema<A> imported from "effect" (not "@effect/schema"). The returned builder is re-typed so result.object is A at compile time. Reactive Agents supports all four of these schema libraries out of the box — most frameworks support only one or two.

All four schema libraries support top-level array schemas directly:

import { z } from "zod";
const LineItemList = z.array(
z.object({ description: z.string(), amount: z.number() })
);
const agent = await ReactiveAgents.create()
.withOutputSchema(LineItemList)
.build();
const result = await agent.run("List all line items from the invoice");
// result.object is typed as Array<{ description: string; amount: number }>
if (result.object) {
result.object.forEach((item) => console.log(item.description, item.amount));
}

When .withOutputSchema() is set, the agent is steered to emit JSON matching the schema as its final answer. As a result:

  • result.output is the raw JSON string the agent produced (not prose).
  • result.object is the parsed, typed value derived from that JSON.

If you have existing code that reads result.output as prose, be aware it will contain JSON when structured output is active. Use result.object for the typed value and fall back to result.output only as a last resort (e.g., when result.object is undefined after a parse failure).

By default the agent is lenient: a parse failure does not throw. Instead:

  • result.object is undefined.
  • result.objectError is set to a human-readable description of what went wrong.
const result = await agent.run("Extract invoice details");
if (result.object) {
// happy path
} else if (result.objectError) {
console.error("Extraction failed:", result.objectError);
// fall back to result.output (the raw JSON / text answer)
}

result.objectReport says how the value was obtained, or why it was not: the winning layer, attempts, JSON repairs, coercion and field errors (see Extraction provenance). It is set whenever the extraction pipeline ran, on success and on failure. It is absent when the agent’s own answer already matched the schema (no extraction call was made) and on the grounded engine. With onParseFail: "throw", the same report is on StructuredOutputError.report.

JSON Schema, and saving the schema with the agent

Section titled “JSON Schema, and saving the schema with the agent ”

.withOutputSchema() also takes a plain JSON Schema object. It is the only form that is plain data, so it is what toConfig() saves: an agent built with an Effect, Zod, Valibot or ArkType schema saves that schema’s JSON Schema form as AgentConfig.outputSchema, and agentConfigToBuilder() applies it again.

import { ReactiveAgents, agentConfigToBuilder } from "reactive-agents";
const builder = ReactiveAgents.create()
.withName("city-extractor")
.withOutputSchema(
{
type: "object",
properties: { city: { type: "string" }, population: { type: "integer", minimum: 0 } },
required: ["city"],
additionalProperties: false,
},
{ mode: "fast" },
);
const config = builder.toConfig(); // config.outputSchema is the JSON Schema above
const restored = await agentConfigToBuilder(config); // same schema and options

A JSON Schema is validated deterministically, without a model call. Supported keywords: type, enum, const, properties, required, additionalProperties, patternProperties, propertyNames, min/maxProperties, items (schema or tuple array), additionalItems, min/maxItems, uniqueItems, minimum, maximum, exclusiveMinimum/exclusiveMaximum (numbers), multipleOf, min/maxLength, pattern, anyOf, oneOf, allOf, not, and local $refs into $defs or definitions. Annotations (title, description, format, default, examples, $schema, …) are kept but not checked. Any other keyword (for example if/then) makes .withOutputSchema() throw OutputSchemaError, naming the keyword and where it is, so a schema is never validated loosely. result.object is typed unknown with a JSON Schema; use an Effect or Standard Schema when you want a static type.

runStream(task, { outputSchema }) asks for a typed answer on a single turn without changing the agent (for example one message in a chat). It takes the same schema forms as .withOutputSchema(). The turn is steered to answer as JSON, and the final StreamCompleted carries object, or objectError, plus objectReport when the extraction pipeline ran. AgentStream.collect() copies them onto the result.

import { ReactiveAgents, AgentStream } from "reactive-agents";
const agent = await ReactiveAgents.create()
.withTestScenario([{ text: '{"city":"Lima"}' }])
.build();
const result = await AgentStream.collect(
agent.runStream("Name the capital of Peru", {
outputSchema: { type: "object", properties: { city: { type: "string" } }, required: ["city"] },
}),
);
console.log(result.object); // { city: "Lima" }
await agent.dispose();

A per-turn schema is lenient: a failed extraction sets objectError and never fails the stream. An unsupported JSON Schema ends the stream with one StreamError before the run starts. Paused or failed runs are passed through without extraction. runStream() does not use the agent’s own .withOutputSchema().

Choose between two failure modes via the onParseFail option:

Mode Behaviour
"degrade" (default) object is undefined, objectError is set. Never throws.
"throw" Throws StructuredOutputError (carries .rawText + .issues).
import { StructuredOutputError } from "reactive-agents";
const strictAgent = await ReactiveAgents.create()
.withOutputSchema(InvoiceSchema, { onParseFail: "throw" })
.build();
try {
const result = await strictAgent.run("Extract invoice details");
console.log(result.object);
} catch (e) {
if (e instanceof StructuredOutputError) {
console.error("Parse failed:", e.issues);
console.log("Raw text was:", e.rawText);
}
}

The grounded path — provenance, confidence, and abstention

Section titled “The grounded path — provenance, confidence, and abstention”

For extraction tasks where you need to know why a value was chosen — or when model hallucination is a concern — use mode: "grounded". Grounded mode is most useful when tools are registered: the engine grounds each field against the actual tool-result evidence corpus the agent accumulated during the run. Without tools there is no evidence corpus, so the grounded path falls back to a best-effort extraction.

The grounded engine:

  1. Extracts fields from the agent’s final answer.
  2. Grounds each field against the tool-result evidence corpus accumulated during the run (the actual data the agent read, not its prose summary).
  3. Scores per-field confidence (0–1).
  4. Surgically re-extracts missing required fields if they were omitted.
const agent = await ReactiveAgents.create()
.withSystemPrompt("You extract financial data from SEC filings.")
.withTools({ builtins: ["web-search", "file-read"] })
.withOutputSchema(InvoiceSchema, { mode: "grounded" })
.build();
const result = await agent.run("Extract Q3 revenue from the attached 10-Q");
if (result.object) {
console.log(result.object.total);
// Per-field evidence trace
console.log(result.provenance?.total);
// → { source: "10-Q page 4", evidence: "Net revenues for Q3 were $..." }
// Per-field confidence (0..1)
console.log(result.confidence?.total); // → 0.97
}

Set abstainBelow to have the grounded engine omit non-required fields whose confidence falls below a threshold, rather than emitting a low-confidence guess:

const agent = await ReactiveAgents.create()
.withOutputSchema(InvoiceSchema, {
mode: "grounded",
abstainBelow: 0.7,
})
.build();
const result = await agent.run("...");
// Fields below 0.7 confidence are omitted from result.object
// and recorded here instead:
console.log(result.abstained);
// → { currency: "confidence 0.42 below abstainBelow threshold" }

abstainBelow is opt-in (off by default) and requires the grounded path.

Field Type When present
result.object A | undefined Parse succeeded
result.objectError string Parse failed (lenient mode)
result.provenance Record<string, { source, evidence }> Grounded path
result.confidence Record<string, number> Grounded path
result.abstained Record<string, string> Grounded path + abstainBelow set
Value Behaviour
"auto" (default) fast for frontier models with native JSON + no tool overlap; else grounded.
"fast" Single-shot extraction. No grounding, provenance, or abstention.
"grounded" Loop-integrated extraction with evidence grounding.

Streaming structured output (streamObject)

Section titled “Streaming structured output (streamObject)”

Use streamObject() to receive a DeepPartial<A> as tokens arrive, finishing with the complete validated object:

const agent = await ReactiveAgents.create()
.withOutputSchema(InvoiceSchema)
.build();
for await (const { object } of agent.streamObject("Extract invoice details")) {
// object is DeepPartial<Invoice> — fields appear as the model emits them
if (object.vendor) process.stdout.write(`\rVendor so far: ${object.vendor}`);
}
// Final iteration carries the full validated object

streamObject() throws synchronously if .withOutputSchema() was not called. When onParseFail: "throw" is set, it throws StructuredOutputError at the end if the final buffer fails validation.

runStream() carries a typed object only when you pass a per-turn outputSchema (A schema for one turn). resumeRun() does not carry it; use run() or streamObject() for typed structured output.

.withOutputSchema() composes with the full builder chain, including Compose API killswitches. The agent loop runs under the composed harness; structured extraction fires after the loop completes.

import { ReactiveAgents } from "reactive-agents";
import { budgetLimit } from "@reactive-agents/compose";
import { z } from "zod";
const ReportSchema = z.object({
summary: z.string(),
riskLevel: z.enum(["low", "medium", "high"]),
findings: z.array(z.string()),
});
const agent = await ReactiveAgents.create()
.withSystemPrompt("You are a risk analysis agent.")
.withTools({ builtins: ["web-search", "file-read"] })
.compose(budgetLimit({ maxTokens: 50_000 }))
.withOutputSchema(ReportSchema)
.build();
const result = await agent.run("Analyse the attached contract for risk");
if (result.object) {
console.log(result.object.riskLevel, result.object.findings);
}

Note: structured output is not itself a composable chokepoint — it runs as a post-loop extraction step. The harness governs the reasoning loop; the extraction call (when the parse-first path misses) happens outside harness governance.

Extraction provenance (extractStructuredOutput)

Section titled “Extraction provenance (extractStructuredOutput) ”

The low-level extractStructuredOutput() in @reactive-agents/reasoning reports how each extraction went. A success carries result.report. A failure is a StructuredOutputExtractionError (_tag: "StructuredOutputExtractionError") with the same report. The error message is unchanged.

import { Effect, Schema } from "effect";
import { extractStructuredOutput } from "@reactive-agents/reasoning";
const Invoice = Schema.Struct({ id: Schema.String, total: Schema.Number });
const prompt = "Extract the invoice id and total from: INV-7, $42.50";
const program = extractStructuredOutput({ schema: Invoice, prompt }).pipe(
Effect.tap((r) => Effect.log(r.report.layer, r.report.repairs)),
Effect.catchTag("StructuredOutputExtractionError", (e) =>
Effect.log(e.report.failure?.kind, e.report.fieldErrors),
),
);
Field Meaning
outcome "success" or "failure"
layer The furthest fallback needed: native, retried, repaired, coerced or prompt. null on failure
native not-attempted, succeeded, failed or contract-rejected
attempts / promptAttempts Model requests in total, and in prompt mode only
repairs Text repairs applied to the deciding response, in order (extract-json-block, single-quotes, trailing-commas, …)
coerced The validator returned a value that differs from the parsed JSON
fieldErrors { path, message }[] from the last failed validation. path is a JSON Pointer such as /items/1/id
failure { kind, message } on failure. kind is invalid-json, schema-mismatch, empty-output or llm-error

Every field is computed from what the pipeline observed, so the same responses always produce the same report. Effect Schema failures list every field error. Contract failures list the validator’s own issues. On an agent, the report of the run’s extraction is result.objectReport. At density "full", runStream() forwards every StructuredOutputReported EventBus event as a StructuredOutputReported stream event ({ taskId, strategy?, report }).

  • Lenient by default — onParseFail: "degrade" means failures are silent unless you check result.objectError. Use "throw" when you want failures to be loud.
  • Grounded field-level features are richest with Effect Schema. Standard Schema inputs (Zod/Valibot/ArkType) get provenance and confidence scoring, but requirement-tracking and surgical re-extraction of missing required fields are Effect-Schema-only today.
  • abstainBelow and grounded-default routing are opt-in pending cross-tier ablation (project lift rule). Auto-mode selects grounded only when the fast path is not applicable.
  • runStream() carries object only with a per-turn outputSchema, and resumeRun() results never do. Use run() or streamObject() with the agent’s own schema.
  • JSON Schema support is a subset (listed above). Unsupported keywords are refused with OutputSchemaError, never ignored.
  • On slow local models, the extraction adds latency only when the parse-first path misses (the agent is steered to emit JSON, so the common path is a free parse of the model’s own output).
  • result.output is JSON, not prose, when structured output is active. Code relying on result.output as a human-readable string should switch to result.object for the typed value.
  • Reasoning — the kernel loop that populates the evidence corpus the grounded engine draws from.
  • Durable Execution — crash-resume for long extraction runs.
  • Tools — tools produce the evidence that grounded extraction grounds against.

Install

Bun (recommended)bun add reactive-agents
Node 22.5+npm install reactive-agents

Get notified on new releases