API Reference

Full function signatures, parameters, and return types.

enforce clean check fix select prompt classify

enforce

The full contract loop. Runs your function, cleans the output, validates against the schema, retries with targeted repair on failure.

function enforce<T>(
  schema: ZodType<T>,
  run: (attempt: AttemptContext) => Promise<string | null>,
  options?: EnforceOptions<T>,
): Promise<Result<T>>

Parameters

ParamTypeDescription
schemaZodType<T>Zod schema defining the expected output shape
run(attempt) => Promise<string | null>Your LLM call. Receives attempt context, returns raw output
optionsEnforceOptions<T>Optional config (see below)

AttemptContext

Passed to your run function:

FieldTypeDescription
promptstringAuto-generated prompt instructions from the schema
fixesMessage[]Repair messages from previous failed attempt (empty on first try)
numbernumberCurrent attempt number (1-indexed)
previousErrorContractError?Error details from the previous attempt

EnforceOptions

OptionTypeDefaultDescription
maxAttemptsnumber3Maximum number of attempts
backoff"none" | "linear" | "exponential""none"Delay strategy between retries
backoffBaseMSnumber200Base delay in milliseconds
invariantsArray<(data: T) => true | string>[]Schema constraints Zod can't express
onAttempt(event: AttemptEvent) => voidHook called after each attempt
repairsPartial<Record<...>>Override or disable repair per category
promptSuffixstringAppended to the auto-generated schema prompt

Result

type Result<T> =
  | { ok: true; data: T; attempts: number; raw: string; durationMS: number }
  | { ok: false; error: ContractError }

clean

Normalizes raw LLM output into clean JSON.

function clean(raw: string | null | undefined): unknown

Handles:

check

Validates data against a Zod schema and optional invariants. Deterministic — no LLM involved.

function check<T>(
  data: unknown,
  schema: ZodType<T>,
  invariants?: Invariant<T>[],
): Result<T>

fix

Turns validation failures into targeted repair messages for the next attempt.

function fix(
  detail: AttemptDetail,
  repairs?: Partial<Record<FailureCategory, RepairFn | false>>,
): Message[] | false

select

Strips a state object down to only the fields the schema defines. Prevents sending PII, secrets, or unrelated data to the LLM.

function select<T>(
  state: Record<string, unknown>,
  schema: ZodType<T>,
): Record<string, unknown>

prompt

Generates prompt instructions from a Zod schema. Used internally by enforce.

function prompt(schema: ZodType): string

classify

Categorizes a failed LLM response into a FailureCategory.

type FailureCategory =
  | "EMPTY_RESPONSE"
  | "REFUSAL"
  | "NO_JSON"
  | "TRUNCATED"
  | "PARSE_ERROR"
  | "VALIDATION_ERROR"
  | "INVARIANT_ERROR"
  | "RUN_ERROR"

Used internally by enforce. Available for custom pipelines.