Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 10 min · revision 3

Why Free Text Breaks Pipelines

See how free-text model replies break the code that consumes them, why prompt instructions and JSON mode only reduce the problem, and what a schema contract with an explicit 'cannot answer' path adds.

Contentsand lesson path

What you will learn

  • Design a JSON Schema or Pydantic model for an extraction or decision task, including enums, optional fields and an explicit 'cannot answer' path.

Prerequisites: LLM API Integration

01. Why it matters

A chat window has a human at the other end. If the model adds a friendly sentence, wraps its answer in a Markdown fence or calls a field vendorName instead of vendor_name, the reader shrugs and carries on. A pipeline has code at the other end: a parser, a database insert, a match statement that routes a ticket. Code does not shrug. It raises an exception, or, worse, it accepts the reply and stores something wrong.

This skill is about the boundary between a language model and the code that uses its output. In this lesson you will see the ways free text breaks that boundary, why asking nicely in the prompt only lowers the failure rate, and what a contract looks like: a schema the provider enforces, plus validation in your own code for everything the schema cannot express. The rest of the skill builds that contract for an invoice-extraction task, step by step.

02. Five replies, one parser

Suppose you ask a model for an invoice's vendor and total and parse the reply with json.loads. Real replies to such prompts drift in a few recurring ways:

  • Preamble or closing chatter: "Here is the data:" before the JSON, or "Let me know if you need more" after it.
  • Markdown fences: the JSON arrives wrapped in a triple-backtick block.
  • Invalid JSON: a trailing comma, single quotes, or an unescaped newline inside a string.
  • Key drift: vendor_name on one call, vendorName or supplier on the next.
  • Type drift: 450, "450", "450.00 USD" and "about $450" for the same field.

A common first fix is a helper that strips fences and then parses. The script below runs such a helper over five replies. It uses only the standard library, so you can run it with Python 3.12 or later.

Python · fragile.py
import json
import re

FENCE = re.compile(r"```(?:json)?\s*([\s\S]*?)\s*```")


def fragile_parse(text: str) -> dict:
    """Strip a Markdown fence if there is one, then parse. Do not ship this."""
    match = FENCE.search(text)
    return json.loads(match.group(1) if match else text.strip())


replies = {
    "clean": '{"vendor": "Northwind", "total": 450}',
    "fenced": '```json\n{"vendor": "Northwind", "total": 450}\n```',
    "preamble": 'Here is the data: {"vendor": "Northwind", "total": 450}',
    "trailing comma": '{"vendor": "Northwind", "total": 450,}',
    "drifted keys": '{"vendorName": "Northwind", "total": "about $450"}',
}
for name, text in replies.items():
    try:
        data = fragile_parse(text)
        print(f"{name:15} parsed: vendor={data.get('vendor')!r} "
              f"total={data.get('total')!r}")
    except json.JSONDecodeError as err:
        print(f"{name:15} JSONDecodeError: {err.msg}")
Terminal
python3 fragile.py
Expected output
clean           parsed: vendor='Northwind' total=450
fenced          parsed: vendor='Northwind' total=450
preamble        JSONDecodeError: Expecting value
trailing comma  JSONDecodeError: Expecting property name enclosed in double quotes
drifted keys    parsed: vendor=None total='about $450'

Two replies crash loudly, which is the good kind of failure: you see it and can retry or alert. The last reply is the dangerous one. It parses, so no exception is raised, but vendor is missing and total is a string that a later sum will reject or, in a loosely typed language, silently mangle. Each regex or try/except you add handles the failures you have already seen and misses the next one.

Scale makes this worse. Prompt-only formatting can look perfect in a hundred manual tests and still fail on a small share of production requests. At 200,000 documents a day, even half a percent is a thousand broken records every day. Do not trust a quoted failure rate, including one from a blog post: measure your own, per model and per prompt.

03. A schema is a contract, including "I cannot answer"

The alternative is to state the shape of the answer as data, not as prose in the prompt. A JSON Schema (or a Pydantic model, which produces one) says which keys exist, which are required, what type each value has and which values an enum allows. Your code and the provider then share one definition of a valid reply.

A good contract also says what the model should do when the honest answer is "there is no answer". If every invoice field is required and the document is a delivery note, a model that must fill the schema will invent an invoice: a plausible vendor, a made-up total. The schema needs a legitimate way out, for example a status field with values such as ok, not_an_invoice and unreadable, a reason, and invoice fields that are null unless the status is ok. Lesson 2 builds exactly that.

The same idea applies inside the invoice. A due date that is not printed should be null, not a guess. A currency the downstream system does not handle should become an explicit OTHER, not the nearest listed code.

04. Three levels of enforcement

Providers offer three levels of help, and they are easy to confuse:

  1. Instructions only. "Return JSON with these keys" in the prompt. The model usually complies; nothing checks that it did.
  2. JSON mode. The API makes the reply valid JSON but takes no schema, so keys and types are still up to the model. OpenAI's JSON mode also returns an error unless the word "JSON" appears in the conversation.
  3. Schema-constrained output. You send a JSON Schema and the provider restricts generation so the reply follows it. With OpenAI's Responses API this is text.format with type: "json_schema" and strict: true (Chat Completions uses response_format). With Claude it is output_config.format with type: "json_schema", or a tool definition with strict: true when the structure is a tool's input. Self-hosted servers such as vLLM offer the same through a structured-output option.

Level 3 is what the rest of this skill uses. Lesson 3 explains how it works, and also what it does not cover: a reply cut off at the token limit, a refusal, and values that are well-formed but wrong. That is why the contract always has a second half in your own code: check how the response ended, then validate the content.

05. Check your understanding

Practice check · 3 questions

Free text at the code boundary

Use the five replies and the contract idea from this lesson.

Q1. Your fence-stripping parser has raised no errors for a week, yet a report shows missing vendors. Which of the five reply styles above best explains it?
Q2. An enforced schema contains only invoice fields, all required. The document is a delivery note with no prices. What is the most likely result?
Q3. A prompt-only extractor returns unusable output for 0.5% of documents. At 200,000 documents a day, what should you plan for?
Practice only: not graded, not saved, not evidence.

06. Apply it

In the skill project you extract vendor, dates, line items, total and currency from 30 documents. Before writing any code:

  • list every field you need, and for each one decide what the model should return when the document does not show it;
  • list the kinds of document that are not invoices but may reach the pipeline, and name the status each should get;
  • write down which provider and which enforcement level you will use, and how your code will notice a cut-off reply or a refusal.

07. Review prompt

Without looking back: name five ways a free-text reply breaks a parser and say which of them raise an error and which pass silently. Explain the difference between JSON mode and schema-constrained output, and why a schema for extraction needs a 'cannot answer' path.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check