Full function signatures, parameters, and return types.
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>>
| Param | Type | Description |
|---|---|---|
| schema | ZodType<T> | Zod schema defining the expected output shape |
| run | (attempt) => Promise<string | null> | Your LLM call. Receives attempt context, returns raw output |
| options | EnforceOptions<T> | Optional config (see below) |
Passed to your run function:
| Field | Type | Description |
|---|---|---|
| prompt | string | Auto-generated prompt instructions from the schema |
| fixes | Message[] | Repair messages from previous failed attempt (empty on first try) |
| number | number | Current attempt number (1-indexed) |
| previousError | ContractError? | Error details from the previous attempt |
| Option | Type | Default | Description |
|---|---|---|---|
| maxAttempts | number | 3 | Maximum number of attempts |
| backoff | "none" | "linear" | "exponential" | "none" | Delay strategy between retries |
| backoffBaseMS | number | 200 | Base delay in milliseconds |
| invariants | Array<(data: T) => true | string> | [] | Schema constraints Zod can't express |
| onAttempt | (event: AttemptEvent) => void | — | Hook called after each attempt |
| repairs | Partial<Record<...>> | — | Override or disable repair per category |
| promptSuffix | string | — | Appended to the auto-generated schema prompt |
type Result<T> =
| { ok: true; data: T; attempts: number; raw: string; durationMS: number }
| { ok: false; error: ContractError }
Normalizes raw LLM output into clean JSON.
function clean(raw: string | null | undefined): unknown
Handles:
```json, ```JSON, bare ```)"85" → 85, "true" → true)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>
Turns validation failures into targeted repair messages for the next attempt.
function fix(
detail: AttemptDetail,
repairs?: Partial<Record<FailureCategory, RepairFn | false>>,
): Message[] | false
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>
Generates prompt instructions from a Zod schema. Used internally by enforce.
function prompt(schema: ZodType): string
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.