ExAgent.OutputSchema (ExAgent v0.1.0)

Copy Markdown View Source

Structured output via Ecto schemas and changesets.

Given any module defining an embedded_schema (plus a 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, 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. If the module doesn't define one, a default "cast all fields" changeset is used.

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

Derive a JSON Schema from an Ecto schema module.

Validate data (a map, typically decoded from the model's JSON) against an Ecto schema, returning {:ok, struct} or {:error, [error_map]}.

Functions

json_schema(mod)

@spec json_schema(module()) :: map()

Derive a JSON Schema from an Ecto schema module.

validate(mod, data)

@spec validate(module(), map()) :: {:ok, struct()} | {:error, [map()]}

Validate data (a map, typically decoded from the model's JSON) against an Ecto schema, returning {:ok, struct} or {:error, [error_map]}.