Advanced

Constrained output

If your code has to consume the output, stop the model from writing prose. Ask for an exact format, usually JSON, and let a validator catch the slips.

What you will see

Missing fields: none

About 2 min of reading

Try It

Constrain model output to structured, valid JSON

1

Compare free text output against constrained JSON output.

print() print("Constrained output") def free_text_answer(): return "The price is roughly $5, maybe more or less depending on discounts." def constrained_answer(): return "{\"price\": 5.0, \"currency\": \"USD\", \"item\": \"widget\"}" free = free_text_answer() print("Free text -> must parse and clean: %s" % free[:20]) import json constrained = constrained_answer() print("Constrained -> trust and use: %s" % constrained) parsed = json.loads(constrained) print("Parsed price: %.2f" % parsed["price"])

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Constrained output Free text -> must parse and clean: The price is roughly Constrained -> trust and use: {"price": 5.0, "currency": "USD", "item": "widget"} Parsed price: 5.00
Always validate before trusting; a model can still add extra text or drop a field.
2

Check that every required field is present.

required = ["price", "currency", "item"] missing = [f for f in required if f not in parsed] print("Missing fields: %s" % (missing if missing else "none"))

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Missing fields: none
Constrain -> validate -> retry. Never trust blindly.

Put it in order

Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.

Data Flow

The model is constrained to a format, validated by code, and retried if it doesn't match.
1 Describe the required format or schema
↓
2 Request only that output
↓
3 Parse and validate the result
↓
4 Retry if validation fails
Why this works
Why format matters for code

When your program consumes model output, free text is painful. Constrain it:

Free text  ->  you must parse and clean it
Structured ->  you can trust and use it

Always validate before trusting. A model can still add extra text or drop a field.

Making output reliable

Combine techniques for reliable output:

  • Ask for JSON only, no prose.
  • Describe every field.
  • Validate with a parser.
  • Retry if it fails.

Constrain -> validate -> retry. Never trust blindly.

The retry is the safety net that makes it production-ready.

Examples

Demanding JSON

Respond with ONLY valid JSON.
No explanation. No markdown.
{ "title": "...", "tags": [] }

Requesting JSON lets your code parse the result directly.

Why it works: a fixed format means no cleaning up prose.

Using schema hints

Return a list of objects with:
  - name (string)
  - score (number)
  - ok (boolean)

Describing fields one by one reduces mistakes. If the model supports schemas, pass them directly.

A schema is a contract the model must follow.

Guarding the fields

Return JSON with all three fields:
  name (string), score (number), ok (boolean)
Leave no field out.

Listing every required field leaves no room for the model to guess.

Why it works: an explicit shape is easier to validate than a partial one.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Prompt chaining
Previous Lesson
Prompt chaining
Next Lesson
Optimizing prompts
Optimizing prompts →