Alloy.OutputSchema (alloy v0.16.0)

Copy Markdown View Source

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_body output_config, text, response_format, and Gemini schema/thinking containers). :name (default "alloy_output") and :strict (default true) 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" => false on every object (pass %{schema: schema, strict: false} to opt out).
  • Provider compatibility: Gemini models prior to Gemini 3 and some OpenAICompat servers reject combining tools with 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, conflicting generation_config / extra_body["generationConfig"] keys (responseJsonSchema, legacy responseSchema, snake_case equivalents, or non-JSON responseMimeType) fail locally with non-retryable %Alloy.Provider.Error{kind: :invalid_request}. Overriding a provider's wire schema key via :extra_body changes 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_schema is loaded (bounded to 10 errors / 1,000 bytes; Draft 7 contentMediaType: "application/json" requires config :ex_json_schema, decode_json: &Jason.decode/1); without :ex_json_schema or for newer dialects (Draft 2019-09 / 2020-12), Alloy falls back to top-level JSON "type" and "required" checks only (logging a Logger.warning when :ex_json_schema is loaded and encounters an unsupported $schema dialect — pre-normalize once with normalize!/1 if reusing a Draft 2019-09 / 2020-12 schema across runs to avoid per-run log warnings).
  • Decoding & terminal failures: Runs before :after_completion and is skipped when :stop_after_tool completes a run. Final assistant text blocks are joined with "" for JSON decoding (whereas result.text joins blocks with " "). Invalid JSON, :max_tokens truncation (even when the prefix parses), refusals (taking precedence over :until_tool reminders), missing or whitespace-only text, and schema violations fail terminally with {:error, result} (status: :error, output: nil, and machine-readable result.metadata.run.output_error with %{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_json for contentMediaType: "application/json" or invalid local references) report kind: :invalid_schema with decoded: nil so host repair loops do not retry unfixable schema errors. Decode/validation failures and content-block refusals keep the assistant reply in result.messages / result.text, while stop-reason refusals discard the refused reply. If :after_completion halts with {:halt, reason} or {:halt, reason, state}, result.status is :halted and result.output is nil (the validated value was available on state.run_metadata.output). Alloy does not run an automatic repair turn.

Summary

Types

t()

Normalized :output_schema struct.

Functions

Decodes final assistant text as JSON and validates it against spec.

Normalizes :output_schema into %Alloy.OutputSchema{} or nil.

Types

output_error()

@type output_error() :: %{
  kind: output_error_kind(),
  message: String.t(),
  decoded: term() | nil
}

output_error_kind()

@type output_error_kind() ::
  :invalid_json
  | :schema_mismatch
  | :invalid_schema
  | :truncated
  | :refusal
  | :missing_text

t()

@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

decode_and_validate(text, spec)

@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}}.

normalize!(spec)

@spec normalize!(term()) :: t() | 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.