Structured Reply
A turn on the full runtime whose reply must match a schema. The request names the schema; the runtime instructs the model, parses and checks the reply, asks again inside the turn when it does not match, and hands the caller the parsed value on the final chunk.
import { AgentOS } from '@framers/agentos';
import { z } from 'zod';
const week = z.object({ items: z.array(z.object({ date: z.string(), title: z.string(), heavy: z.boolean() })) });
// A runtime whose persona list holds a 'planner' persona.
const agentos = await AgentOS.create();
for await (const chunk of agentos.processRequest({
userId: 'user-1', sessionId: 'session-1', selectedPersonaId: 'planner',
textInput: 'Draft my week from the path.',
options: { structuredReply: { schema: week, name: 'week', maxRetries: 2 } },
})) {
if (chunk.type === 'final_response' && chunk.structured?.meta.valid) {
const plan = chunk.structured.value as z.infer<typeof week>;
}
}
The spec
ProcessingOptions.structuredReply:
| Field | Default | Meaning |
|---|---|---|
schema | A Zod schema or a JSON Schema object. | |
schemaRef | A key in AgentOSConfig.structuredSchemas (a Map or anything with get(ref)), resolved before the turn. One of schema and schemaRef is required; a request that names neither, or a ref the registry lacks, is refused with SYS_VALIDATION_ERROR and no model call. | |
name | reply | Named in the instruction and in structured.meta.schemaName. |
description | Added to the instruction. | |
maxRetries | 2 | Repair rounds after a reply that does not match, clamped to 0 to 5. |
onExhausted | error | error: the turn ends with GMI_STRUCTURED_OUTPUT_INVALID (422). return_invalid: the last reply is returned with meta.valid: false and its issues. |
streamDeltas | false | Stream the model's text while it writes. Off, nothing reaches the caller before the check. |
What the turn does
- The schema's instruction (the JSON Schema, in words the model follows) is the last block of the system prompt, after every other instruction the turn adds. A Zod schema also travels to the completion gateway where a GMI has one, which lowers it per provider.
- The model's text is parsed (plain JSON, a code fence, or the first to the last brace), then checked. A reply in which one object holds a key twice is refused as JSON that does not parse, its repair message naming the key and where the object sits (
items[0]):JSON.parsekeeps only a repeated key's last value, so the reply would lose the others. A streamed forced schema tool call that repeats a key stays text, so this check sees it. A single-shot Anthropic call (streamCompletions: false) receives the tool input already parsed by the API, which keeps only a repeated key's last value, so this check cannot see the repeat there. The check: Zod'ssafeParse, with one repair of a container the model string-encoded (an encoded container that repeats a key stays a string, so the reply fails); or Ajv for a JSON Schema. Ajv reads a JSON Schema as draft-07, reports every error, checks the standard formats (date-time,email,uriand the others ofajv-formats), and passes over a keyword it does not know, as JSON Schema says to, and a format it does not know, which it names in the log when it compiles the schema. A host may send its JSON Schema anew with each request, under one$idtoo. - A reply that does not match is answered inside the turn with the issues named and the bad reply quoted, and the model is asked again, up to
maxRetriestimes. The invalid reply and the repair request join the turn's prompt and never the durable history; the turn's text starts over with each attempt. A reply that answers with tool calls runs its tools first; the check waits for a step that answers with text. A reply that holds the model's refusal (OpenAI'srefusalfield) is not checked and not repaired, even when text that parses or a lifted value comes beside it: the schema's check does not run, so a refinement that throws never ends the turn in place of the refusal. A refusal is the model's answer, not JSON to repair, as ingenerateObject(). UnderonExhausted: 'error'the turn ends withGMI_STRUCTURED_OUTPUT_INVALID, its detailsrefused: true,schemaNameandattempts; underreturn_invalidthe final chunk carriesstructuredwithvalue: null,meta.valid: falseand the issueThe model refused the request instead of writing the reply.The refusal message is in neither: it stays on the step'sSTEP_FINISHEDpayload (refusal, besiderefused: true), which the streamprocessRequest()returns does not carry. - The final chunk carries
structured: { value, meta }.meta.attemptscounts the model calls;meta.enforcementisforced_toolwhen the gateway lifted a forced schema tool call into the value,provider_schemawhen the provider payload of the hop that answered carried the schema (a strictjson_schema, Gemini'sresponseSchema, Anthropic's JSON output format, whose JSON text the gateway lifts),prompt_onlywhen the schema reached the model in the system prompt alone (a hop with no schema payload, such as a record schema on a Claude model that refuses a forced tool choice, or a JSON mode without a schema). The label follows the request the provider sent, as its chunks report it (schemaRoute,schemaInPayload: false): an Anthropic request that enables citations answers through the forced tool in place of the format on a model that accepts a forced tool choice (from the prompt on one that refuses it), and one with a thinking budget, or with a passthroughtool_choiceofauto,noneor another tool's name, answers from the prompt in place of the forced tool. An answer the output limit stopped is never lifted into the value: the check reads its text, and the step keeps itslengthfinish.meta.stageismodel. - A guardrail that rewrites a final response withdraws the value parsed from the reply it replaced (a refused reply excepted, below):
structuredreadsvalue: null,meta.valid: falseandmeta.stage: 'post_guardrail', with the reason inmeta.issues. ASANITIZEwhose text equals the reply rewrites nothing and keeps the value. On the streamprocessRequest()returns, the rewritten reply is then checked again as it stands, against the turn's schema:structuredholds what that check finds,stage: 'post_guardrail', and a text that no longer matches ends the request withGMI_STRUCTURED_OUTPUT_INVALIDunderonExhausted: 'error', or arrives withmeta.valid: falseunderreturn_invalid. A stream that holds no schema carries the withdrawn value: a tool-result continuation's (handleToolResult(),handleToolResults(),resumeExternalToolRequest()) and a cross-agent supervisor's (wrapWithCrossAgentGuardrails()).
A refused structured reply stays value: null, meta.valid: false, stage: 'model' with its refusal issue after output sanitization, whether the guardrail changes the text or leaves it unchanged, on every stream: processRequest()'s, a tool-result continuation's and a cross-agent supervisor's. It is never withdrawn, checked again or repaired, even when the sanitized text matches the schema.
A gmi() session's send(input, { responseSchema }) ends a refused turn as agent() does: when any step of the turn was refused, it rejects with ObjectGenerationError (session.send: the model refused the request instead of writing the object) before parsing or checking the schema, with the provider's refusal message in error.refusal (possibly the empty string), even when valid JSON or a lifted object accompanies the refusal, or no text does. The turn leaves nothing in the session's history.
Errors
| Code | Status | When |
|---|---|---|
SYS_VALIDATION_ERROR | 400 | The spec names no schema the runtime can reach, or a JSON Schema that does not compile, such as one whose type is no JSON Schema type, whose $schema names a draft other than draft-07, that takes the draft-07 meta-schema's own $id or that is marked $async (its check would answer a promise). |
GMI_STRUCTURED_OUTPUT_INVALID | 422 | Every attempt failed under onExhausted: 'error', the model refused the request under onExhausted: 'error', or an output guardrail broke the shape. Details: schemaName, attempts or stage, issues; a refusal has refused: true in place of issues. |
generateObject shares the parsers (extractJson, repairStringEncodedContainers, the issue summaries) with the structured turn; they live in src/api/runtime/structuredReply.ts.