OpenProgram Docs

JSON Schema structured output

Runtime.exec(..., response_format=...) is the one public entry. Whatever the provider claims, the result is strictly parsed and validated against the caller's original schema. Ordinary calls still return str.

Modes

modeHowChosen when
nativeProvider JSON Schema fieldAdapter supports it, model field not False, schema projects losslessly, current tools supported
toolHidden tool __openprogram_submit_jsonfallback="auto", strict tool schemas, lossless, tool_choice allows it
promptCompact schema in the system layer; local check onlyOnly with explicit fallback="prompt"
noneStructuredOutputUnsupportedError before sendingOtherwise

An invalid schema fails first. Model.structured_output=None means unknown, never False. A lossy projection reports its exact path and disables native.

Adapters

APINative payloadCapability
openai-completionsresponse_format={type:"json_schema", json_schema:{…}}supported, with tools
openai-responsestext.format={type:"json_schema", …}supported, with tools
anthropic-messagesoutput_config.format, merged with effortsupported, with tools
google-generative-airesponse_mime_type and response_json_schemasupported, no tools, Google subset
azure-openai-responsesResponses text.formatper model, opt-in
bedrock-converse-streamoutputConfig.textFormat.structure.jsonSchema, as a JSON stringper model, opt-in
openai-codexnonetool fallback
gemini-subscriptionnoneunknown: explicit prompt only

One attempt

  1. Text and tool deltas go to a client candidate buffer, with output_attempt; nothing persists.
  2. After the provider's raw done, parse and validate. Success: structured_output_end, then one done. Stream end with no terminal fails as incomplete.
  3. Repairable failure: structured_output_retry; clients clear the buffer; a new provider stream starts.
  4. Budget gone: error, no done, no invalid assistant message persisted.

Failure handling

FailureRequestRepair
Invalid schemaNot sent: StructuredOutputSchemaErrorNo
Unsupported or conflictingNot sent: StructuredOutputUnsupportedErrorNo
JSON syntax, schema violation, missing or mixed submissionSentYes, up to max_validation_retries
Refusal, content filterSentNo: refusal
max_tokens, incomplete, context lengthSentNo: reason kept, limits unchanged
Transport, rate limit, provider internalSentExisting retry, shared budget
Cancellation, deadlineSentNo: propagates

max_validation_retries (0, 1 or 2; default 2) caps repairs; max_retries caps every provider call at the Runtime boundary, so repair needs both. Retry events fire only when a repair will really run. Repair prompts hold only the failure type and bounded issues, and last for this exec.

With tools

CaseBehaviour
Native, adapter with_toolsEvery round carries the schema; the no-tool round's text is validated
Native, tools unverifiedHidden tool if auto, else preflight failure
Hidden tool, user toolsOffered together; ordinary tools run for many rounds; submit ends. parallel_tool_calls=False.
Submit with ordinary tools in one responsemixed_submission: rejected, no tool runs
Plain text, no submitmissing_submission
Forced tool, none, or requested parallelNot overridden: native if possible, else unsupported

Submit is not executed and has no ToolResultMessage. Validation sits at the Agent-loop no-tool boundary; there is no separate provider path, so tools, deadlines, DAG and record/replay stay one.

Surfaces

SurfaceContract
PythonReturns JsonValue; raises StructuredOutputError with code, provider, model, attempts, issues
openprogram --print --json-schema PATH (- for stdin)Stdout is one compact UTF-8 JSON document. Exit 2 invalid, 3 unsupported, 4 generation or validation failure; stderr has only the code.
WebSocket chat, POST /api/function/{name}response_format?; result in chat_response with structured_output and structured_output_mode; the HTTP route still only acknowledges with {session_id,msg_id}
Web chatNo schema by default, no schema editor; retry clears candidate text
Session historyCanonical JSON content; mode, attempt, schema hash in metadata; invalid candidates never enter
Types
@dataclass(frozen=True)
class JsonSchemaOutput:
    schema: dict[str, Any]     # never mutated
    name: str = "response"     # ^[A-Za-z_][A-Za-z0-9_-]{0,63}$
    description: str | None = None
    strict: bool = True
    fallback: Literal["auto", "none", "prompt"] = "auto"
    max_validation_retries: Literal[0, 1, 2] = 2
    type: Literal["json_schema"] = "json_schema"

Runtime.exec(content=..., response_format={"type": "object", ...}) -> JsonValue
Runtime.exec(content=..., response_format=JsonSchemaOutput(...)) -> JsonValue
Runtime.exec(content=..., response_format=None) -> str

A bare dict is the schema, not a provider payload. Model.structured_output, StreamOptions.response_format, and AssistantMessage.structured_output, structured_output_mode, structured_output_attempt. Raw JSON text stays in assistant content for history and audit. jsonschema>=4.23 is a direct dependency. Error code: invalid_schema, unsupported, invalid_json, validation_failed, missing_submission, mixed_submission, refusal, incomplete.

Parsing and limits
  • json.loads rejecting NaN, Infinity, Markdown fences, surrounding text and trailing content; no forgiving parser, also for hidden-tool arguments.
  • validator_for(schema), a registry with no external access, errors sorted by instance path, schema path, message.
  • Preflight rejects any $ref, $dynamicRef, $recursiveRef that does not resolve inside the schema, and direct reference cycles. Finite recursion is allowed.
  • Schema budget: 1 MiB, 4096 container nodes, 8192 edges, depth 100; over it is invalid_schema.
  • At most 20 issues, 500 characters each.
  • Tool arguments: strict export turns optional fields into required nullable ones; shared normalization restores only added nulls, on a copy, before canonical validation. Enum, conditional and combinator constraints stay.
Record and replay

RECORDING_FORMAT_VERSION is 2. Requests record normalized response_format; raw provider events are recorded, and retry, end and error are rebuilt deterministically on replay. Each repair is a new provider call and call_index. v1 structured recordings are rejected; ordinary v1 stays compatible. The schema is hashed (SHA-256, sorted keys) for logs, DAG and errors; recordings retain the whole schema.

Session title consumer

conversation/turn_runtime/titles.py: TITLE_SCHEMA is {title: string, 1–80}, toolset="none", max_iterations=2, fallback="prompt", max_validation_retries=1. Best-effort: a structured error keeps the placeholder. The consumer does only Unicode trim and storage-length protection; logs hold fixed lifecycle labels only.

What was not taken
  • Provider strict alone, with raw text returned: refusals, truncation and compatible endpoints need local checks.
  • Partial or forgiving JSON repair.
  • Parsing every delta into objects.
  • A separate structured provider path.
  • Lossy schema rewriting, automatic Pydantic types, cross-language codegen, incremental JSON AST.

references/pi-ai shares options and strict tool schemas but has no response schema. Each adapter needs a payload contract test before a capability is enabled.

Files
FileHolds
models/providers/structured_output.pyNormalization, preflight, negotiation, parsing, errors
models/providers/types.pyFields and events
providers/catalog/{api_registry,register}.pyAdapter capabilities
providers/schema/Dialects, strict projection
runtime/agent/loop/Terminal validation, hidden tool, repair
runtime/agent/runtime/Parsed returns, callable models
runtime/conversation/event_parsing.pyStream events
providers/recording/{recording,replay}.pyFormat 2
interfaces/cli/{parser,application,chat,print_turn}.pyOne-shot CLI
interfaces/server/ws_actions/chat/, routes/chat.pyWebSocket and API
Last updated · 2026-11-25