004

AI output needs a contract

Turn a generated answer into a reviewable draft with a small schema, runtime validation, and an explicit commit step.

AI

01Separate a proposal from an action

Imagine a writing assistant that suggests a title and category for an article. Its job is to propose a draft. The application still decides which fields are accepted, where the draft is stored, and whether anything is published. Keeping those responsibilities separate makes failures easier to inspect.

Start with a small output contract: a title, an excerpt, and a category from a fixed list. Do not ask the model to generate arbitrary HTML when the interface only needs three text values. Smaller contracts are easier to validate, preview, and revise.

02Define the shape before the prompt

draft.schema.json
{
  "type": "object",
  "properties": {
    "title": { "type": "string", "minLength": 1, "maxLength": 100 },
    "excerpt": { "type": "string", "minLength": 1, "maxLength": 240 },
    "category": {
      "type": "string",
      "enum": ["creative-dev", "interface", "front-end", "ai"]
    }
  },
  "required": ["title", "excerpt", "category"],
  "additionalProperties": false
}

In JSON Schema, declaring properties does not make them required. The required list does that. Disallowing additional properties closes another gap: an unexpected publish flag should not become an application instruction. If your model provider supports schema-constrained responses, check which schema features that provider accepts.

A correctly shaped answer can still be misleading. A schema can check that a title is a string; it cannot establish that the title accurately describes the source article. Content review remains a separate step.

03Validate at the application boundary

Treat parsed model output as unknown data. A TypeScript type assertion does not inspect it at runtime. Here is a dependency-free validator for this small contract; a shared schema validator is preferable once several services need to agree on the same rules.

validate-draft.ts
const categories = ['creative-dev', 'interface', 'front-end', 'ai'] as const
type Draft = {
  title: string
  excerpt: string
  category: typeof categories[number]
}

export function validateDraft(value: unknown): Draft {
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
    throw new Error('Expected a draft object')
  }
  const record = value as Record<string, unknown>
  const allowed = ['title', 'excerpt', 'category']
  if (Object.keys(record).some((key) => !allowed.includes(key))) {
    throw new Error('Unexpected draft field')
  }
  const text = (key: string, limit: number) => {
    const raw = record[key]
    if (typeof raw !== 'string') throw new Error('Expected text: ' + key)
    const result = raw.trim()
    if (!result || Array.from(result).length > limit) {
      throw new Error('Invalid length: ' + key)
    }
    return result
  }
  const category = categories.find((item) => item === record.category)
  if (!category) throw new Error('Unknown category')
  return { title: text('title', 100), excerpt: text('excerpt', 240), category }
}

This validator deliberately trims surrounding whitespace as an application policy. Handle JSON parsing errors before calling it. Render accepted strings through normal escaped text bindings, and validate again on the server before saving. Client-side checks help the interface; they do not establish a trusted boundary.

04Make failure reviewable

Keep an invalid response out of the editable draft. Show a short explanation and let the user retry or write the fields themselves. If you retry automatically, bound the number of attempts and distinguish validation errors from network failures, timeouts, and provider refusals. Endless retries make a broken workflow feel like a slow one.

Show the proposal beside its source text, with an explicit save or publish action. Treat source documents as data, even if they contain instructions addressed to an assistant. The server should enforce permissions independently of anything the model says.

Test missing fields, extra fields, blank titles, unknown categories, and plausible but inaccurate summaries. Track those failures separately. Better formatting and better factual accuracy are different improvements, and the interface should make both visible.

Reference: JSON Schema — object validation.

0%