Back to notes
ValidationTutorial6 min

Validate OpenAI model output before writing to the database

A safe implementation pattern for keeping AI output useful without letting invalid data pollute production records.

Open source doc
Real example

Example: quarantine invalid extracted tender data

An extraction returns a deadline, buyer, score, and recommendation, but the deadline is not a valid ISO date and the recommendation references a missing certificate.

Parse the model output with a schema. If validation fails, create a review task containing the raw response id, validation errors, and the source tender. Do not write to the final assessment table.

Bad output becomes visible work instead of corrupt production data. The operator can repair the record and the team can improve the prompt or source parser.

ts
Fail closed before write
const parsed = TenderFitSchema.safeParse(modelOutput);

if (!parsed.success) {
  await db.reviewTask.create({
    data: {
      type: "ai_validation_failed",
      sourceId: tender.id,
      errors: parsed.error.flatten(),
    },
  });
  return { status: "needs_human_review" };
}

await db.tenderAssessment.create({ data: parsed.data });
Tutorial path

How to implement it

Step 01
Define a schema that mirrors the fields your UI and database can actually support.
Step 02
Parse model output into that schema and fail closed when required fields are missing.
Step 03
Write valid results into a draft or review table before finalizing production state.
Step 04
Show validation errors to an operator when the model cannot complete the record safely.
Step 05
Track rejection reasons so the prompt, source data, or schema can improve.
Checklist

Ready when these are true

Schema validation before write
Draft state for AI output
Operator review for rejects
No silent coercion of critical fields
Metrics for validation failures
Field notes

What matters in practice

01
Structured output is the start of reliability, not the end of it.
02
Application validation should run before database writes, emails, notifications, or status changes.
03
Rejected output still has value when it becomes a review task.
Avoid these mistakes

Common failure modes

01
Do not coerce critical dates, amounts, or statuses silently.
02
Do not write partial records into the final table without an explicit draft state.
03
Do not treat structured output as a replacement for application validation.
Practical tip
A validation failure is product signal. Track it as a queue item, not just an exception.
Apply this to a build
Contact
Bring the workflow, deadline, and constraints.
Send the desired outcome, current bottleneck, users, and timeline. I will respond with a practical path for the build.