ExAgent.OutputSchema (ExAgent v3.0.0)

View Source

Structured output via object JSON Schemas or Ecto schemas and changesets.

Stability — Stable.

For a map with type: "object", JSV validates the schema and its data. Valid results have string keys throughout, with no coercion or inserted defaults.

Declare {:ecto, "~> 3.14 and >= 3.14.3"} in the application's dependencies to compile Ecto output support.

Given a module defining an embedded_schema and an optional changeset/2, this module:

  • json_schema/1 derives the JSON Schema the model is told to produce, by walking the schema's fields and types (scalars, enums, arrays, maps, embedded schemas, datetimes).
  • validate/2 builds a changeset from the model's data, applies the schema's validations, and returns either {:ok, struct} or {:error, errors} — feeding the errors back to the model for a retry.

The convention is the standard Ecto one: a changeset(struct, attrs) callback. Its declared required fields are authoritative, including an empty list. Optional fields accept omission or null through an anyOf branch, keeping reflected non-null constraints intact. Optional embeds_many is the Ecto exception: it accepts omission or an array, not null. Required fields are not nullable. These rules apply recursively to embedded schemas. Schemas without a changeset cast and require scalar fields and single embeds. An embedded list defaults to [] when omitted. Its elements use the child schema's changeset or, if absent, the same default rules.

Reflection inspects a changeset built with empty attributes; it cannot fully describe arbitrary custom or conditional validations. validate/2 always runs the actual changeset and remains the final authority. Custom validators can use their own metadata (for example, an atom). Reusing an Ecto metadata shape such as {:inclusion, values} with a list advertises that constraint. Provider support for this JSON Schema (including anyOf and strict-mode restrictions) must be checked against the actual backend.

Ecto.UUID fields and array elements advertise format: "uuid" as a hint for the model. ExAgent's local JSON Schema validator treats it as an annotation. Ecto handles casting and also accepts raw 16-byte binaries.

Reflected inclusion/exclusion values retain their JSON types. Ecto.Enum schemas advertise the declared integer or string storage values for scalar fields and array elements. Inclusion/exclusion constraints on scalar enum fields map enum members to that same vocabulary. If a choice such as a Decimal cannot be represented as JSON data in the schema, the whole inclusion or exclusion rule stays in the changeset. A list passed to validate_subset/3 on an array of strings, integers, floats, booleans or enum members constrains its items when every option has a corresponding JSON scalar. Ranges and custom values are checked by Ecto. Plain atom enums still use their string names, including boolean-named members. Repeated numeric limits retain the tightest bound for each JSON Schema keyword. Integer and float thresholds are reflected. A :not_equal_to value joins any choices excluded by validate_exclusion/3. A Decimal threshold is enforced by the changeset at the original precision. Array lengths use minItems/maxItems, while string lengths use minLength/maxLength, including exact (:is) bounds. Length bounds intersect across options and validation calls; contradictory bounds remain unsatisfiable, as in the changeset. JSON string lengths count Unicode codepoints. Ecto's default grapheme counting and optional byte counting can differ; use count: :codepoints when exact alignment is required. The real changeset remains authoritative for those count modes. For a :map field, Ecto checks the number of keys when it validates the response. The generated schema omits those bounds, so the model may need a retry.

Example

defmodule WeatherReport do
  use Ecto.Schema

  embedded_schema do
    field :city, :string
    field :temp_c, :float
    field :condition, Ecto.Enum, values: [:sunny, :rainy, :cloudy]
  end

  def changeset(schema, attrs) do
    schema
    |> Ecto.Changeset.cast(attrs, [:city, :temp_c, :condition])
    |> Ecto.Changeset.validate_required([:city, :temp_c])
    |> Ecto.Changeset.validate_number(:temp_c, greater_than: -100, less_than: 100)
  end
end

ExAgent.OutputSchema.json_schema(WeatherReport)
# => %{type: "object", properties: %{city: %{type: "string"}, ...}, required: [...]}

ExAgent.OutputSchema.validate(WeatherReport, %{"city" => "Madrid", "temp_c" => 22.0})
# => {:ok, %WeatherReport{city: "Madrid", temp_c: 22.0, ...}}

Summary

Functions

Return a normalized JSON Schema map or derive a JSON Schema from an Ecto module.

Validate an object against a JSON Schema or an Ecto schema module. Returns a string-keyed map or Ecto struct on success. Errors in embedded records include a :path from the root, with string field names and zero-based indices for lists.

Functions

json_schema(schema)

@spec json_schema(ExAgent.Output.schema()) :: map()

Return a normalized JSON Schema map or derive a JSON Schema from an Ecto module.

validate(schema, data)

@spec validate(ExAgent.Output.schema(), map()) :: {:ok, map()} | {:error, [map()]}

Validate an object against a JSON Schema or an Ecto schema module. Returns a string-keyed map or Ecto struct on success. Errors in embedded records include a :path from the root, with string field names and zero-based indices for lists.

Custom Ecto types should return :error or {:error, details} from cast/1 for invalid input. If casting raises even while gathering diagnostics, the result contains a generic changeset error.