Skip to content

Schemas (@aeye/schema) ​

Tool arguments and prompt outputs are written with a, the schema builder from @aeye/schema. a is to aeye what z is to zod: you describe a value once, in your code's shape, and get its exact TypeScript type. Then, for whichever model a request goes to, the schema is rendered as the JSON Schema that model can read, the answer is decoded back into your code's shape in one pass, and mistakes are reported to the model in the shape it wrote.

@aeye/core depends on @aeye/schema and re-exports a:

typescript
import { a } from '@aeye/core';      // or: import { a } from '@aeye/schema';

The builder ​

typescript
const Budget = a.object({
  owner: a.string().describe('Who owns the budget.'),
  limits: a.record(a.number().min(0)).describe((v) => `Spending limit per category, as ${v.recordWord}.`),
  period: a.enum(['week', 'month']).default('month'),
  note: a.string().optional(),
});
type Budget = a.infer<typeof Budget>;
// { owner: string; limits: Record<string, number>; period: 'week' | 'month'; note?: string }
Builders
Primitivesa.string() a.number() a.int() a.boolean() a.null() a.literal('x') a.enum([...])
Any JSONa.unknown() (typed unknown), a.json() (typed JsonValue)
Containersa.object({...}) a.array(T) a.tuple([A, B]) a.record(V) a.record(a.enum([...]), V)
Combinatorsa.union([...]) a.discriminatedUnion('kind', [...]) a.intersection([...]) a.optional(T) a.nullable(T)
Named typesa.define({...}) a.declare<{...}>() a.ref('Name') .dynamic(fn, { key }) .result(...)
Mappinga.codec(wire, { decode, encode })
Importinga.fromJSONSchema(json) (MCP tools, OpenAPI bodies)

Modifiers (immutable, on every schema): .describe(text | (view) => text), .title(), .example(...values) (in the code shape, checked), .refine(fn, message?), .optional(), .nullable(), .default(value), .brand<'X'>(), .forPeople() (never shown to a model), .forModels(narrower). Type-specific: string().min/max/pattern/format, number().int/min/max/gt/lt/positive/nonnegative, array().min/max, object().strict() (unknown keys are errors), .extend(shape), .rest(V) (extra keys).

An optional field means the key is absent after decoding — never undefined, never the null a strict model may have written for it.

Build schemas once, at module scope

Renderings are memoized per schema instance and model profile; a schema rebuilt per call is rendered per call.

Named, recursive and dynamic types ​

typescript
// Recursion: a named type that refers to itself
const Tree = a
  .define({ Node: a.object({ value: a.number(), children: a.array(a.ref('Node')) }) })
  .result('Node');

// Dynamic: a part that depends on the context, bound per call and cached by `key`
const Search = a
  .declare<{ Field: string }>()
  .dynamic((ctx: { fields: string[]; version: number }) => ({ Field: a.enum(ctx.fields) }), {
    key: (ctx) => ctx.version,
  })
  .result(a.object({ field: a.ref('Field'), equals: a.string() }));

A tool's dynamic step takes the tool's context; a prompt's takes (ctx, input). Every mistake (an undefined ref, a dynamic step that misses one, a context that doesn't supply the step's arguments) is a compile error. A dynamic step without a key runs on every bind.

Rendered per model ​

profileFor(model) picks what a model reads from data on the model (ModelInfo.schema, strictFormat, capabilities). The same schema becomes:

typescript
// OpenAI strict sees  { owner, limits: [{ key, value }], period: 'week' | 'month' | null, note: string | null }
// Gemini sees         { owner, limits: { [k]: number }, period?: ..., note?: string }
// your code gets      Budget, either way

Providers do this for you: every request is planned as a whole for its model (see Strict Mode for the budgets and degradations). To plan and decode by hand:

typescript
import { a, profileFor } from '@aeye/core';

const plan = profileFor(model).request([
  { kind: 'tool', name: 'set_budget', schema: Budget },
  { kind: 'output', schema: Report },
]);

const tool = plan.get('set_budget');
tool.jsonSchema;                      // send as the tool's parameters (strict: tool.strict)
const res = tool.parseText(rawArgs);  // decode the model's answer
if (res.ok) res.value;                // Budget, in the code shape
else res.message;                     // what to tell the model
plan.degradations;                    // what was changed to fit the provider's limits

Errors for the model ​

When arguments or an output don't fit, the model is told in its own shape: its JSON echoed back, trimmed, with a marker under each mistake, "did you mean" for misspelt names, and the expected type, within a size cap (2,000 characters by default).

1 problem in the arguments of web_api_call:

{
  "url": "https://api.example.com/v1/items",
  "method": "PUTT",
            ^^^^^^ method: Expected one of: GET, POST, PUT, PATCH, DELETE — did you mean `PUT`?
}

errorFormat sets the detail: 'summary', 'list', 'markers' or 'full' (default), or { detail, maxErrors, maxChars, suggestions, expected, context, depth }. Set it on a tool or prompt definition, for a whole run with ctx.errorFormat, or per parse; the more specific wins. A schema's .refine message is shown to the model as a rule.

Values in instructions ​

A value written into a template as plain JSON is in the code shape, but a strict model may write the same record as pairs or an absent optional as null. Core registers two Handlebars helpers for tool instructions and prompt content:

handlebars
Call it like {{encode example}}.               {{!-- a tool's own args; the output in a prompt --}}
Search takes {{encode q tool="search"}}.       {{!-- another schema of the request --}}
Limits: {{encode limits path="limits" pretty=true}}
The shape: {{schema}}                          {{!-- as TypeScript --}}

Function forms get an encoder for the same thing: instructionsFn: (ctx, encode) => ..., a tool's input: (ctx, encode) => ..., a prompt's input: (input, ctx, encode) => ....

typescript
const search = ai.tool({
  name: 'search',
  description: 'Search the catalog',
  schema: a.object({ query: a.string(), filters: a.record(a.string()).optional() }),
  instructionsFn: (ctx, encode) => `Example: ${encode({ query: 'red shoes', filters: { size: '9' } })}`,
  call: async ({ query, filters }) => find(query, filters),
});

Deferred values ​

Text written before the request is planned (a tool description, a system message your app assembles, a gateway relaying the request to the provider that plans it) can't encode yet. It holds a deferred value instead, written through the plan once the request is planned:

typescript
import { deferEncode } from '@aeye/schema';

const system = `Example arguments: ${deferEncode({ tool: 'search', value: { query: 'x', filters: { size: '9' } } })}`;
// prepareRequest fills it in: pairs on OpenAI strict, an object on Gemini, …

fillDeferred(text, plan) writes them for a plan, plainDeferred(text) shows the fallback or the code shape (logs, estimates), and @aeye/core's deferRequest(request) renders a relayed request's templates with every value deferred. A value that doesn't read back through its schema is shown as its fallback.

Mapping and checking values ​

typescript
const When = a.codec(a.string().format('date-time'), {
  decode: (text) => new Date(text),          // what `call` gets
  encode: (date) => date.toISOString(),      // how a value is shown to the model
});

const Range = a.object({ from: a.number(), to: a.number() })
  .refine((r) => r.from <= r.to, '"from" must not be after "to".');

decode may return an Error (or a Rejection of issues at paths) to reject the value; the message goes back to the model.

Migrating from zod ​

zoda
import { z } from 'zod'import { a } from '@aeye/core'
z.object / string / number / boolean / array / enum / literal / union / tuple / nullthe same names on a
z.record(z.string(), V)a.record(V)
z.any() / z.unknown()a.unknown() (or a.json())
z.string().email() / .url()a.string().format('email' | 'uri')
.transform(fn)a.codec(wire, { decode, encode })
z.lazy(() => Node)a.define({ Node: ... a.ref('Node') ... }).result('Node')
z.infer<typeof X>a.infer<typeof X>
.passthrough() / .catchall(V).rest(a.unknown()) / .rest(V)
schema: (ctx) => z... (Tool)a bundle: a.declare<{...}>().dynamic((ctx) => ({...}), { key }).result(...)
schema: (input, ctx) => z... (Prompt).dynamic((ctx, input) => ...) — note the order
schema: () => falseapplicable: (ctx) => false
toJSONSchema / strictifyprofileFor(model).request([...]), or prepareRequest + sentTools / sentOutput in a provider

The full reference — every profile and its rules, request fitting, decoding and copies, error options, JSON Schema and gin import — is @aeye/schema's aeye-schema.md.

Released under the GPL-3.0 License.