Normalized representation of a portable :output_schema option.
Built by Alloy.Agent.Config.from_opts/1 and Alloy.Agent.State.prepare/2
from either a plain JSON Schema map or a wrapper map
%{name: ..., schema: ..., strict: ...}. Stored on state.config.output_schema
so middleware can inspect it and built-in providers can translate it into
their wire formats without re-normalizing per request.
Semantics
- Provider translation & wrapper options: Sent on every completion turn
and forwarded to fallback providers (omitted on compaction summaries, which
also drop raw
extra_bodyoutput_config,text,response_format, and Gemini schema/thinking containers).:name(default"alloy_output") and:strict(defaulttrue) apply to OpenAI, xAI, and OpenAICompat and are ignored on Anthropic, Gemini, and Codex. OpenAI/xAI strict mode requires every property in"required"and"additionalProperties" => falseon every object (pass%{schema: schema, strict: false}to opt out). - Provider compatibility: Gemini models prior to Gemini 3 and some
OpenAICompat servers reject combining
toolswith JSON Schema output; use Gemini 3+ (gemini-3.8-flash),:until_tool/:stop_after_tool, or a host-driven follow-up no-tools turn. On Gemini, conflictinggeneration_config/extra_body["generationConfig"]keys (responseJsonSchema, legacyresponseSchema, snake_case equivalents, or non-JSONresponseMimeType) fail locally with non-retryable%Alloy.Provider.Error{kind: :invalid_request}. Overriding a provider's wire schema key via:extra_bodychanges the wire payload only; Alloy still validates against the top-level:output_schema. - Validation tiers: Remote (non-
#)$refs are always rejected at startup. Full Draft 4/6/7 validation runs when optional:ex_json_schemais loaded (bounded to 10 errors / 1,000 bytes; Draft 7contentMediaType: "application/json"requiresconfig :ex_json_schema, decode_json: &Jason.decode/1); without:ex_json_schemaor for newer dialects (Draft 2019-09 / 2020-12), Alloy falls back to top-level JSON"type"and"required"checks only (logging aLogger.warningwhen:ex_json_schemais loaded and encounters an unsupported$schemadialect — pre-normalize once withnormalize!/1if reusing a Draft 2019-09 / 2020-12 schema across runs to avoid per-run log warnings). - Decoding & terminal failures: Runs before
:after_completionand is skipped when:stop_after_toolcompletes a run. Final assistant text blocks are joined with""for JSON decoding (whereasresult.textjoins blocks with" "). Invalid JSON,:max_tokenstruncation (even when the prefix parses), refusals (taking precedence over:until_toolreminders), missing or whitespace-only text, and schema violations fail terminally with{:error, result}(status: :error,output: nil, and machine-readableresult.metadata.run.output_errorwith%{kind: :invalid_json | :schema_mismatch | :invalid_schema | :truncated | :refusal | :missing_text, message: String.t(), decoded: term() | nil}). Runtime schema/configuration errors (such as missing:ex_json_schema:decode_jsonforcontentMediaType: "application/json"or invalid local references) reportkind: :invalid_schemawithdecoded: nilso host repair loops do not retry unfixable schema errors. Decode/validation failures and content-block refusals keep the assistant reply inresult.messages/result.text, while stop-reason refusals discard the refused reply. If:after_completionhalts with{:halt, reason}or{:halt, reason, state},result.statusis:haltedandresult.outputisnil(the validated value was available onstate.run_metadata.output). Alloy does not run an automatic repair turn.
Summary
Functions
Decodes final assistant text as JSON and validates it against spec.
Normalizes :output_schema into %Alloy.OutputSchema{} or nil.
Types
@type output_error() :: %{ kind: output_error_kind(), message: String.t(), decoded: term() | nil }
@type output_error_kind() ::
:invalid_json
| :schema_mismatch
| :invalid_schema
| :truncated
| :refusal
| :missing_text
@type t() :: %Alloy.OutputSchema{ name: String.t(), resolved: {:cached, {String.t(), map(), boolean()}, {:ok, term()} | :fallback} | nil, schema: map(), strict: boolean() }
Normalized :output_schema struct.
:resolved is an internal validation cache bound to {name, schema, strict}
and excluded from Inspect.
Functions
@spec decode_and_validate(String.t() | nil, t() | map()) :: {:ok, term()} | {:error, output_error()}
Decodes final assistant text as JSON and validates it against spec.
Uses full Draft 4/6/7 validation via optional :ex_json_schema when loaded
and the schema dialect is supported; falls back to top-level JSON "type"
and "required" checks otherwise. Returns {:ok, decoded} or
{:error, %{kind: kind, message: message, decoded: decoded | nil}}.
Normalizes :output_schema into %Alloy.OutputSchema{} or nil.
Accepts nil, a %Alloy.OutputSchema{} struct (returned as-is if already
normalized, or validated if hand-built), a plain JSON Schema map (defaulting
name: "alloy_output" and strict: true), or a wrapper map
%{schema: map, name: ..., strict: ...}. Raises ArgumentError on invalid
shapes, non-JSON-encodable schemas, remote $refs, or invalid schemas when
:ex_json_schema is loaded.