Correctness / Contracts
Structured Output Contracts
Prompting can guide structure. Contracts enforce it.
Problem
Prompt-only parsing fails under drift. A small response change can break deserialization, violate required fields, or produce semantically invalid values.
Solution
Add a contract boundary between model output and application state. The boundary admits only structured, valid outputs.
Mechanism
- schema checks for structural validity
- invariants for domain-level correctness
- repair transforms for common failures
- bounded retries for controlled regeneration
Example
const result = await contract.run({
prompt,
schema: invoiceSchema,
invariants: [hasPositiveTotal, hasCurrencyCode],
maxRetries: 2,
repair: [stripMarkdownFence, trimTrailingText],
});
if (!result.ok) {
throw result.error;
}
return result.value;This makes acceptance explicit and failure classes observable.