Validate Model-Generated Data Before Saving It

Validate Model-Generated Data Before Saving It

Published on

0

views

This article explains why schema validation alone is not enough to ensure AI data quality. It demonstrates how to implement a practical second validation layer using business rules and Pydantic validators in Python. By checking domain logic, checking for placeholder text, and logging rejections before database persistence, you can keep bad data out of your system.

You asked the model for structured JSON. It came back looking clean. The schema validator passed. Now the temptation is to write the object straight into the database and move on.

That is the moment most quiet data-quality bugs are born.

This article shows the practical checks that should happen between “schema-valid” and “saved forever.” We stay with a single deterministic call and ordinary application code. No agents, no repair loops, no extra infrastructure.

The Short Answer

Schema validation proves shape. It does not prove the values are complete, consistent, safe, or worth storing. Before you persist model-generated data, run a second layer of application checks: required business rules, length and range limits, cross-field consistency, and a clear reject path that records why the object was refused. Only then write to the database.

Low-angle shot of a backend engineer reviewing Pydantic schema validation and business rules code on a laptop.

What Product Problem This Solves

A structured response that passes JSON Schema can still contain:

  • an empty or near-empty title

  • key points that are duplicates or off-topic

  • a confidence score that is pure hallucination

  • sentiment labels that contradict the summary text

  • strings that are long enough to pass the schema but useless for your UI

If you save those objects, every downstream query, report, and user-facing view inherits the problem. Validation before save is the last cheap chance to keep bad data out of the system of record.

Minimal Working Implementation

We will extend the structured-summary endpoint from the previous article. After the Pydantic schema check succeeds, we run a small set of domain rules. Only objects that pass both layers are written to PostgreSQL.

Python

from pydantic import BaseModel, Field, ValidationError, field_validator
from typing import Literal, Optional
from fastapi import HTTPException
import logging

logger = logging.getLogger(__name__)

class StructuredSummary(BaseModel):
    title: str = Field(..., min_length=1, max_length=120)
    summary: str = Field(..., min_length=10, max_length=800)
    key_points: list[str] = Field(..., min_length=1, max_length=6)
    sentiment: Literal["positive", "neutral", "negative"]
    confidence: float = Field(..., ge=0.0, le=1.0)

    # Extra shape-level guards that schema alone does not enforce well
    @field_validator("key_points")
    @classmethod
    def no_empty_points(cls, v: list[str]) -> list[str]:
        cleaned = [p.strip() for p in v if p and p.strip()]
        if len(cleaned) < 1:
            raise ValueError("key_points must contain at least one non-empty item")
        return cleaned

    @field_validator("title", "summary")
    @classmethod
    def no_placeholder_text(cls, v: str) -> str:
        lowered = v.lower().strip()
        forbidden = ["n/a", "none", "unknown", "not available", "tbd"]
        if lowered in forbidden:
            raise ValueError(f"placeholder text not allowed: {v}")
        return v


def business_rules(data: StructuredSummary) -> list[str]:
    """Return a list of human-readable reasons the object should be rejected.
    Empty list means the object is acceptable to save.
    """
    problems = []

    # 1. Title should not just repeat the first few words of the summary
    if data.title.lower() in data.summary.lower()[:80].lower():
        problems.append("title appears to be a simple truncation of the summary")

    # 2. Key points should not be near-duplicates of each other
    normalized = [p.lower().strip() for p in data.key_points]
    if len(set(normalized)) < len(normalized):
        problems.append("key_points contain near-duplicate entries")

    # 3. Very high confidence with very short summary is suspicious
    if data.confidence >= 0.9 and len(data.summary) < 40:
        problems.append("high confidence paired with very short summary")

    # 4. Sentiment vs. obvious negation in the summary (simple heuristic)
    summary_lower = data.summary.lower()
    negative_signals = ["error", "failed", "problem", "issue", "bug", "broken"]
    if data.sentiment == "positive" and any(w in summary_lower for w in negative_signals):
        problems.append("positive sentiment conflicts with negative language in summary")

    return problems


@app.post("/v1/structured-summary")
async def structured_summary(
    body: StructuredRequest,
    db: AsyncSession = Depends(get_db),
    openai_client: OpenAI = Depends(get_client),
):
    # ... model call and raw_content extraction from previous article ...

    # Layer 1 – schema / shape validation
    try:
        parsed = StructuredSummary.model_validate_json(raw_content)
    except ValidationError as e:
        logger.warning("Schema validation failed: %s", e)
        # Persist a failed task record if you are tracking tasks
        raise HTTPException(status_code=502, detail="Schema validation failed")

    # Layer 2 – business rules
    problems = business_rules(parsed)
    if problems:
        logger.warning(
            "Business rule rejection: %s | raw_title=%s",
            "; ".join(problems),
            parsed.title[:80],
        )
        # Optionally store the rejected object for later analysis
        raise HTTPException(
            status_code=422,
            detail={
                "message": "Model output failed business validation",
                "reasons": problems,
            },
        )

    # Only now do we consider the data safe to save
    task = AITask(
        status="succeeded",
        style="structured",
        input_text=body.text,
        model=response.model,
        finish_reason=finish_reason,
        prompt_tokens=response.usage.prompt_tokens,
        completion_tokens=response.usage.completion_tokens,
        total_tokens=response.usage.total_tokens,
        request_id=response.id,
    )
    db.add(task)
    await db.flush()  # get the task.id

    result = AITaskResult(
        task_id=task.id,
        summary=parsed.model_dump_json(),  # or store fields in typed columns
    )
    db.add(result)
    await db.commit()

    return {
        "id": task.id,
        "data": parsed,
        "finish_reason": finish_reason,
        "usage": {
            "prompt_tokens": task.prompt_tokens,
            "completion_tokens": task.completion_tokens,
            "total_tokens": task.total_tokens,
        },
    }

This is the smallest version that still answers the product question: “Can I trust this object enough to write it to the database?”

Why Two Layers Exist

JSON Schema (and the Pydantic model that mirrors it) is excellent at shape. It is deliberately silent on most domain meaning. Business rules capture the meaning that matters to your product:

  • Is the title actually useful?

  • Are the key points distinct?

  • Does the confidence number pass a basic smell test?

  • Does the sentiment label roughly match the language in the summary?

I once watched a pipeline save hundreds of objects whose titles were literally “Summary” and whose key points were three identical sentences. The schema passed every time. The data was still garbage. A five-line business-rule function would have rejected them before they ever reached the table.

What to Do with Rejected Objects

Rejection is not the same as silence. Log the reasons. Optionally store the raw content and the rejection reasons in a separate “rejected” table or debug store. That collection becomes the best source of new test cases and prompt improvements.

Do not automatically retry the model inside the same request unless you have measured that a retry actually improves the acceptance rate. Blind retries raise cost and latency for a problem that may need a clearer prompt or a tighter schema instead.

Wide-angle shot of an engineer monitoring structured rejection logs and warning messages in a dim operations room.

Keeping the Rules Honest

Business rules should be deterministic, fast, and easy to explain. Avoid calling another model to “validate” the first model’s output in the critical path of a simple feature. That pattern quickly becomes an agent in disguise and brings its own failure modes.

If a rule later proves too strict or too loose, change the rule. The important part is that the decision to save is explicit and recorded.

What Was Tested and What Remains Uncertain

I tested the two-layer path with objects that passed schema but failed each business rule in turn, with clean objects that passed both layers, and with deliberately malformed JSON. Rejections returned 422 with clear reasons; valid objects were persisted.

I have not measured the long-term distribution of rejection reasons under real traffic, nor have I tested every possible Unicode edge case inside titles and key points. Exact schema-constraint behavior and token accounting must still be verified against current official documentation. Confidence scores remain uncalibrated until you compare them with human judgments on your own data.

When a Simpler Approach Is Enough

If the structured object is only ever shown to a human and never stored or used for branching, a single schema check may be sufficient. The moment the data will be queried, counted, or fed into another system, the second validation layer becomes the smaller useful version.

Before adding an agent or a multi-step repair loop, see whether clearer prompting plus ordinary application checks already keep the bad data out. The extra complexity has to earn its place.

Practical Conclusion

Schema-valid is necessary. It is not sufficient. Between the model response and the database there should be a short, explicit set of business rules that decide whether the object is worth saving. Rejected objects should be logged with reasons; accepted objects should be written only after those checks pass.

Start with the smallest version that can answer the product question. In this case the question is “Can I keep obviously bad structured data out of my database?” The two-layer check above is that version.

The model can produce the JSON; your application still has to decide whether it deserves to be stored.

Build real applications. Verify every step.

Last updated:

Share:

Leave a comment

Related Articles

Structured Outputs with GPT-6.1 Sol

Structured Outputs with GPT-6.1 Sol

This article demonstrates how to request and validate structured JSON outputs from the GPT-6.1 Sol model using FastAPI and Pydantic. It highlights minimal implementation details, schema enforcement, application-side validation, and essential logging practices, helping you turn unstructured model responses into reliable, typed application data without unnecessary agent complexity.

1
Build a Safe Tool-Calling Workflow with FastAPI

Build a Safe Tool-Calling Workflow with FastAPI

This article demonstrates how to build a safe, production-ready tool-calling workflow inside a FastAPI service. It covers essential security practices including explicit tool registries, permission flags, Pydantic argument validation, and strict four-gate execution checks, ensuring the model only proposes actions while your application retains full control over execution and logging.

0
What to Do When a Tool Call Has Invalid Arguments

What to Do When a Tool Call Has Invalid Arguments

This article explains how a FastAPI service should handle invalid tool-call arguments from language models. It covers rejecting bad arguments instead of auto-correcting, implementing Pydantic validation checks, structuring error responses, and logging exact failure details. This ensures predictable application behavior and maintains strict control over execution boundaries during AI tool interactions.

0