Making model replies parse on the first try, or the second

Many AI features are not really chat at all. A nutrition app needs a meal with exact quantities and calories, an invoice tool needs totals and dates, a support system needs a category and a priority. Builders keep discovering that the hard part is not getting a good answer but getting one in a format code can read, every single time.
This guide is for developers who call a chat completions API and need structured data back. It covers how to write prompts that produce clean JSON, how to validate replies with a schema, how to repair the ones that fail, and when to move constraint logic out of the model entirely. Every pattern works with any OpenAI-compatible endpoint.
Examples run against the keyless free-ai endpoint, which is convenient for iterating on prompts. Provider-specific features such as strict schema modes differ between services; check the documentation of the provider you use. This site is not affiliated with OpenAI.
Frequently asked questions
What is structured output?
It is a model reply that follows a fixed machine-readable format, usually JSON with defined keys and types, instead of free prose. Your code parses it directly and uses the values without any text processing.
How does JSON mode differ from schema enforcement?
A JSON mode, where a provider offers one, makes the reply valid JSON but does not guarantee specific keys or types. Schema enforcement constrains the output to match a given schema. Support for both varies by provider and model, so check the documentation.
Does free-ai support a strict schema mode?
Treat it as a plain chat model and rely on prompting plus validation. The patterns in this guide, a clear schema in the prompt, low temperature, parsing and a repair retry, give high success rates without any provider-specific feature.
Which is better: asking for JSON or using function calling?
Function or tool calling is a structured channel designed for this purpose on providers that support it well. Plain JSON in the message works everywhere. If you need portability across many endpoints, the plain approach with validation is the safer default.
Why do models wrap JSON in code fences?
Chat-tuned models are trained to format code nicely for human readers. Tell them to reply with JSON only, and strip fences in your parser anyway. A single line of cleanup removes the most common parsing failure.
Should the model do arithmetic like calorie totals?
Preferably not. Language models are unreliable at exact arithmetic. Let the model choose items and quantities, and compute totals in code from a trusted data table. That is also how you get answers that are actually accurate.
How many retries are reasonable?
One or two. If a reply fails validation twice with the error fed back, the prompt or schema probably needs work. Endless retries hide design problems and waste tokens.
Can I stream structured output?
Yes, but you can only parse once the stream completes or you use an incremental JSON parser. For most backend tasks, a non-streamed request is simpler and the latency difference is small.
Step by step
- Define the schema in code — Write a Pydantic or Zod model with types, ranges and allowed values.
- Describe it in the system prompt — List keys, types and rules, include one short valid example and require JSON only.
- Call at low temperature — Send the request with temperature near zero and enough max_tokens for the full object.
- Clean and validate — Strip code fences, parse, validate against the schema and check business rules.
- Repair on failure — Return the reply and the exact error to the model and ask for corrected JSON, at most twice.
- Compute exact values in code — Use trusted tables for totals, prices and nutrients instead of numbers generated by the model.
Why free text breaks applications
A reply like Sure! Here is a healthy lunch: grilled chicken, about 150 grams... is perfect for a person and useless for code. Extracting the numbers with regular expressions works until the model phrases it slightly differently. Then the parser fails, or worse, silently picks up the wrong number.
Structured output turns the model into a component with a contract. The contract says which keys appear, what types they have and which values are allowed. Your code checks the contract and either uses the result or asks again.
The contract lives in code
Define the schema once, in your codebase, and generate both the prompt description and the validator from it. That keeps them from drifting apart.
Boring is good
For data tasks, you want the model to be predictable rather than creative. Plain, constrained outputs are a feature.
Prose has its place
Not every reply needs a schema. Explanations shown directly to users can stay as prose. A useful hybrid is a JSON object with a few structured fields plus one free-text field for the human-readable part, so your code gets reliable data and your users still get natural language in the same response.
Writing the prompt
Put the format rules in the system message and the actual request in the user message. State the exact keys, their types, allowed values and what to do when information is missing. Show one short example of a valid reply. End with a clear instruction to output JSON only.
Keep temperature low, between zero and about 0.3, and set max_tokens high enough for the full object. A reply cut off mid-object is a common and avoidable failure.
Name allowed values
If a field is a category, list every allowed value. Models invent plausible categories when left to guess, and your code will not recognize them.
Keep field names plain
Short, descriptive English field names such as total, currency and due_date work better than abbreviations or internal codes. The model understands what a plain name means and fills it more accurately. If your database uses cryptic column names, map them in code after validation rather than exposing them in the prompt.
SYSTEM = """You plan simple meals. Reply with JSON only, no prose, no code fences.
Schema:
{
"meal": string,
"items": [{"food": string, "grams": integer}],
"notes": string
}
Rules: 2 to 5 items. grams between 10 and 500. Use common foods only.
Example:
{"meal": "lunch", "items": [{"food": "cooked rice", "grams": 150}, {"food": "chicken breast", "grams": 120}], "notes": ""}"""
Validating with a schema
Parse the reply and validate it against your schema before using any value. Pydantic in Python and Zod in TypeScript are popular choices; both give precise error messages that you can feed back to the model on a retry.
Validation should also enforce business rules the schema expresses, such as ranges and list lengths. A reply with a negative quantity is valid JSON and still wrong.
Strip before parsing
The clean function removes code fences, the most frequent cause of parse errors. Also trim any text before the first brace if your model occasionally adds a preamble.
from pydantic import BaseModel, Field, ValidationError
class Item(BaseModel):
food: str
grams: int = Field(ge=10, le=500)
class Meal(BaseModel):
meal: str
items: list[Item] = Field(min_length=2, max_length=5)
notes: str = ""
def clean(raw: str) -> str:
raw = raw.strip()
if raw.startswith("```"):
raw = raw.split("\n", 1)[1] if "\n" in raw else raw
raw = raw.rsplit("```", 1)[0]
return raw.strip()The repair loop
When validation fails, send the model its own reply together with the validation error and ask for a corrected version. This works remarkably well because the error message tells the model exactly what to fix. Limit it to one or two attempts.
The loop below combines prompt, parse, validation and repair. It is small enough to copy into any project and works against any OpenAI-compatible base URL.
Log failures
Record every reply that needed repair, along with the error. Patterns in these logs show you which prompt rules to tighten.
Fail closed
If all attempts fail, return an error to the caller rather than a half-parsed result. Wrong data is worse than no data.
from openai import OpenAI
client = OpenAI(base_url="https://api.apifreekeyopenai.com/v1", api_key="not-needed")
# SYSTEM, Meal and clean come from the previous snippets
def plan_meal(request: str, attempts: int = 3) -> Meal:
messages = [{"role": "system", "content": SYSTEM},
{"role": "user", "content": request}]
for _ in range(attempts):
r = client.chat.completions.create(
model="free-ai", messages=messages, temperature=0.2, max_tokens=500)
raw = r.choices[0].message.content or ""
try:
return Meal.model_validate_json(clean(raw))
except ValidationError as e:
messages += [
{"role": "assistant", "content": raw},
{"role": "user", "content": f"That reply was invalid: {e.errors()[:3]}. Return corrected JSON only."},
]
raise ValueError("no valid reply after retries")
print(plan_meal("A vegetarian dinner around 600 kcal."))
Keep exact numbers out of the model
Builders of nutrition and finance tools learn this quickly: models are good at choosing and describing, poor at exact arithmetic and lookups. A model asked to list calories per item will produce numbers that look right and are often off.
The fix is to split responsibilities. Let the model pick foods and quantities from an allowed list, then compute calories and macros in code from a trusted nutrition table. The output is both structured and accurate, and the model's job becomes much easier.
Closed vocabularies
Pass the list of allowed foods, products or categories in the prompt, and validate that every returned name is in the list. Unknown names trigger a retry.
Validate units explicitly
Quantities without units are a classic source of silent errors: grams versus ounces, cents versus dollars, minutes versus seconds. Put the unit in the field name, such as grams or amount_cents, and state it again in the prompt. A single line in the schema prevents an error that could otherwise slip into production unnoticed for weeks.
- Model: choose items from a closed list, pick quantities, write notes.
- Code: look up nutrient values, compute totals, check targets.
- Code: reject or adjust plans that miss constraints, then ask again if needed.
Constraints the model cannot see
Some rules are too complex to express in a prompt: dietary restrictions combined with budget limits, or invoice totals that must reconcile with line items. Check them in code after validation and treat violations like schema errors, with a targeted message back to the model.
This is cheaper than it sounds. Most replies pass on the first try, and a short repair message costs far less than a long prompt trying to anticipate every edge case.
Specific feedback
Say exactly what is wrong: total is 820 kcal, target is 600 plus or minus 50. Vague feedback like try again yields random changes.

Business uses where structure pays off
Lists of business use cases for chat APIs often stop at customer support bots. The quieter, more reliable wins are structured: tagging and routing support tickets, extracting fields from emails and documents, normalizing product data, and generating short descriptions within strict length limits.
All of these share the pattern in this guide: a closed schema, low temperature, validation and a small repair loop. For a document-specific version of the same pipeline, see adding document analysis to a web app.
Classification
Ask for one label from a fixed list plus a confidence note. It is the easiest structured task and a good first project.
Extraction
Pull names, dates, amounts and references into fields. Validate formats such as dates in code, not by trusting the model.
Testing structured prompts at scale
Before shipping, run your prompt against a few hundred varied inputs and measure the first-try success rate, the success rate after repair and the average tokens per request. These three numbers tell you whether the prompt is ready.
A free endpoint is a convenient place to iterate on the prompt and the validation code, within its limits of about one request per second per IP and 10,000 requests per day. For the final quality numbers, test on the model you will actually deploy, because different models fail in different ways. Our guide on free APIs for testing explains how to split the two.
Commercial strict modes
Where your production provider offers enforced schemas, use them. They reduce failures further. Keep validation anyway: it protects you if the setting changes or you switch providers.

Send a prompt to the keyless free-ai endpoint from the home page and see a reply in seconds, no sign-up needed.
Read also
- Can agent tools run on a ChatGPT subscription instead of an API key?
- How to translate subtitle files with an OpenAI-compatible LLM API
- Why do API answers differ from what the ChatGPT app tells you?
- Chat completions vs text completions: which endpoint should you use?
- Why does an OpenAI-compatible endpoint throw internal server errors?