Structured Output
Get the answer back as JSON your program can use - then parse it, validate it, and retry only when retrying can help.
Watch the lesson
Lesson 1.3: Agentic AI from Scratch | Structured Output with JSON and Pydantic▶ Watch on YouTubeWhat you will be able to do
- Explain why plain text is not enough when a program has to use the answer
- Ask a model for JSON in an exact shape, and turn it into a Python dict with json.loads()
- Explain why temperature 0 suits structured output - and why it makes a plain retry useless
- Tell invalid JSON from valid JSON that carries the wrong data, and handle each differently
- Retry with feedback, so the model can correct its own formatting
- Let Ollama enforce the format with format="json" or a schema - without making it invent values
The idea, in plain English
So far the model has written text for a person. "Priya is 29 years old and lives in Pune" is easy for you to read - but a program that needs a name and an age cannot use a sentence. It needs data: {"name": "Priya", "age": 29}. Getting that from a model is called structured output.
The recipe: ask for an exact JSON shape at temperature 0, turn the reply into a Python dict with json.loads(), and check the fields before you use them.
Two different things can go wrong, and each has its own fix. The reply is not JSON at all - retry, and tell the model what was wrong. Or the reply is valid JSON with the wrong data in it - reject it, because asking again cannot help. Every output below is from a real run against a local model; yours may differ a little, which is exactly why the checks matter.
Worked example: Extract a name and an age from a sentence as JSON.
1 - Ask for an exact shape
The prompt shows the JSON shape you want, says "ONLY valid JSON, no explanation", and says to use null for anything the sentence does not give. Temperature 0, because you want the format right every time - not variety.
Extracting a person from a sentence. Step through what happens to the reply before your application is allowed to use it.
An everyday example: filling in a form
You are at a bank, filling in a form for your friend Priya. The form has two boxes: Name [ ] and Age [ ]. The clerk copies only what is inside the boxes into the computer. Three things can go wrong:
- Wrong place: you write "Her name is Priya and she is 29" across the top of the form, not in the boxes. The clerk cannot copy it, gives the form back and says "Please write inside the boxes." You fix it in a minute - you knew the answers, you only put them in the wrong place.
- Missing answer: you do not know Priya’s age, so the Age box stays empty. Giving the form back to you does not help - you still do not know it. The clerk must decide: refuse the form, or carry on without an age.
- Made-up answer: the form says Age must be a number and has no "not known" choice. So you write 0. The form looks complete - and it is wrong.
- A model’s reply has the same three problems. The table shows which is which.
The form with its boxesThe JSON shape you ask for in the prompt.The clerk copies the boxes into the computerjson.loads() turns the reply text into a dict.Wrong place: answers written outside the boxesThe model adds text like "Here is the JSON:" around it, so json.loads() fails. Send it back with the error - the model can fix it.Missing answer: the Age box is emptyValid JSON with "age": null. Asking again cannot help - check the data and reject it.Made-up answer: 0 because the form needs a numberA schema that forces an integer: the model invents "age": 0. Allow null instead.From JSON text to Python data
- JSON is a way of writing data as text - braces, quotes, brackets - that almost every language can read.
- response["message"]["content"] is always a string, even when it looks like JSON.
- json.loads() parses that string into Python values: an object becomes a dict, null becomes None.
- Once it is a dict, your program uses it like any other data - data["name"], data["age"]. That is the whole point.
import json
raw = '{"name": "Priya", "age": 29}' # a string - not a dict yet
data = json.loads(raw) # now a dict
print(data) # {'name': 'Priya', 'age': 29}
print(data["name"]) # Priya
print(data["age"]) # 29{ "name": "Priya" }dict["Pune", "Mumbai"]list"Priya"str29 / 4.5int / floattrue / falseTrue / FalsenullNoneTell the model exactly what to send back
A model is trained to chat with people, so it likes to add friendly sentences. Your program cannot read those. Here is what happened when we asked too briefly:
- 1. We asked: "Extract the name and age as JSON." That is all.
- 2. The model replied with a sentence first - "Here is the extracted information in JSON format:" - and then the JSON, wrapped in ``` marks (chat apps use those marks to show code).
- 3. A person can see the JSON in there. json.loads() cannot: it needs the text to START with {, but ours starts with "Here". So it fails on the very first character.
- 4. The fix is to say exactly what you want, as rules: reply with ONLY JSON, in this exact shape, no explanation, no ``` marks.
- 5. Add one more rule: "Use null for anything the sentence does not say." Without it, a model may guess a missing age - and a guessed age looks exactly like a real one.
Prompt:
Extract the name and age as JSON.
Sentence: Priya is 29 years old and lives in Pune.
Reply:
Here is the extracted information in JSON format:
```
{
"name": "Priya",
"age": 29
}
```
json.loads(reply) -> json.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
(the reply starts with "Here", not "{")Prompt:
Extract the person's name and age from this sentence.
Respond with ONLY valid JSON in this exact format: {"name": "...", "age": ...}
Use null for anything the sentence does not say.
No explanation, no markdown, just the JSON.
Sentence: Priya is 29 years old and lives in Pune.
Reply:
{"name": "Priya", "age": 29}
json.loads(reply) -> {'name': 'Priya', 'age': 29}Temperature 0 - and the catch
- At temperature 0 the model takes the most likely token every time, so the same prompt gives the same output.
- We ran the extraction five times: five identical replies. That is what you want for a format your code depends on.
- The catch: if the output is broken, the same prompt gives the same broken output. We retried the loose prompt three times - fail, fail, fail.
- A retry only helps if something changes between attempts. That is why the better version sends the error back to the model.
Watch out: Retrying the identical request at temperature 0 repeats the identical failure. Either change the request - add feedback - or do not retry.
First version: ask, parse, retry
The simplest version that works on a good day:
- A strict prompt with the exact shape, at temperature 0.
- json.loads() inside try/except json.JSONDecodeError.
- On a parse failure, try again - up to retries more times - then give up with the last output in the error.
import ollama
import json
def extract_json(sentence, retries=2):
prompt = f"""Extract the person's name and age from this sentence.
Respond with ONLY valid JSON in this exact format: {{"name": "...", "age": ...}}
No explanation, no markdown, just the JSON.
Sentence: {sentence}"""
for attempt in range(retries + 1):
response = ollama.chat(
model="llama3.1",
messages=[{"role": "user", "content": prompt}],
options={"temperature": 0}
)
raw = response["message"]["content"].strip()
try:
return json.loads(raw)
except json.JSONDecodeError:
if attempt == retries:
raise ValueError(f"Model never returned valid JSON. Last output: {raw}")
result = extract_json("Priya is 29 years old and lives in Pune.")
print(result) # {'name': 'Priya', 'age': 29}What the first version misses
Three real runs show its three gaps:
- Its retry sends the identical request - at temperature 0 that repeats the identical failure.
- "Priya lives in Pune." returns {"name": "Priya", "age": null}: valid JSON, no age. It goes straight to your app.
- "Priya is 29 and her brother Arjun is 34." returns one person: valid JSON, and Arjun silently dropped.
The loose prompt retried three times: fail, fail, fail
(temperature 0 gives the same output every time)
"Priya lives in Pune." -> {"name": "Priya", "age": null}
"Priya is 29 and her brother Arjun is 34." -> {"name": "Priya", "age": 29}
both valid JSON - one has no age, one dropped a personTwo problems, two fixes
- Problem 1 - not JSON. json.loads() raises json.JSONDecodeError. The model made a formatting slip, so it can fix it: add its reply and the error to the conversation, and ask for only the JSON.
- Problem 2 - valid JSON, wrong data. {"name": "Priya", "age": null} parses cleanly. So would no age at all, or an age of "twenty-nine". json.loads() catches none of these, so you check the fields yourself.
- And for problem 2 you do not retry. "Priya lives in Pune" has no age in it; asking again cannot invent one.
Prose or a markdown fence around the JSONNot JSON. Retry, telling the model what was wrong.A trailing comma or a missing quoteNot JSON. Retry with feedback.A required field is missingValid JSON, wrong data. Validate and reject.A field is null because the input did not sayValid JSON, honest answer. Reject it, or let the app handle None.A field has the wrong type - "twenty-nine"Valid JSON, wrong data. Validate and reject.Two people in the sentence, one in the JSONValid and silent. Only a better shape - a list of people - fixes it.Better: retry with feedback, validate without retrying
extract_person() handles the two problems separately:
- The prompt adds "Use null for anything the sentence does not say."
- Not JSON: append the model’s reply and "That was not valid JSON (...)" to messages, then loop. The next request is different, so the next reply can be too.
- Valid JSON: hand it to validate_person(), which checks for a dict, both fields, a non-empty name and a whole-number age - and raises ValueError otherwise. No retry.
- isinstance(True, int) is True in Python, so the age check rules out bool first.
import json
import ollama
MODEL = "llama3.1"
PROMPT = """Extract the person's name and age from this sentence.
Respond with ONLY valid JSON in this exact format: {{"name": "...", "age": ...}}
Use null for anything the sentence does not say.
No explanation, no markdown, just the JSON.
Sentence: {sentence}"""
def validate_person(data):
"""Raise ValueError unless data is a person with a name and a whole-number age."""
if not isinstance(data, dict):
raise ValueError(f"expected a JSON object, got {type(data).__name__}")
missing = [field for field in ("name", "age") if field not in data]
if missing:
raise ValueError(f"missing fields: {missing}")
if not isinstance(data["name"], str) or not data["name"].strip():
raise ValueError("name must be a non-empty string")
if isinstance(data["age"], bool) or not isinstance(data["age"], int):
raise ValueError(f"age must be a whole number, got {data['age']!r}")
return data
def extract_person(sentence, retries=2):
messages = [{"role": "user", "content": PROMPT.format(sentence=sentence)}]
for attempt in range(retries + 1):
response = ollama.chat(
model=MODEL,
messages=messages,
options={"temperature": 0},
)
raw = response["message"]["content"].strip()
# Problem 1 - not JSON at all. The model can fix this, so retry with feedback.
try:
data = json.loads(raw)
except json.JSONDecodeError as error:
if attempt == retries:
raise ValueError(f"No valid JSON after {retries + 1} attempts. Last output: {raw}") from error
messages.append({"role": "assistant", "content": raw})
messages.append({
"role": "user",
"content": f"That was not valid JSON ({error.msg}). Reply with only the JSON object.",
})
continue
# Problem 2 - valid JSON, wrong data. Retrying cannot invent a missing age,
# so reject it straight away and let the caller decide.
return validate_person(data)
print(extract_person("Priya is 29 years old and lives in Pune."))
try:
print(extract_person("Priya lives in Pune."))
except ValueError as error:
print("Rejected:", error){'name': 'Priya', 'age': 29}
Rejected: age must be a whole number, got None
With the loose prompt instead: the first reply failed to parse,
and the retry with feedback succeeded on the second call.Letting Ollama enforce the format
Ollama can do part of this for you:
- format="json" constrains the output to valid JSON. In our run it fixed the loose prompt with no retry at all.
- format=<a JSON schema> constrains the output to that exact shape.
- Careful: our first schema required age to be an integer. For "Priya lives in Pune" the model returned "age": 0 - invented, valid, silently wrong.
- Allowing null - "type": ["integer", "null"] - fixed it: the model returned null.
- Constraining the format does not make the data true. Validation stays.
import json
import ollama
MODEL = "llama3.1"
PERSON_SCHEMA = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": ["integer", "null"]}, # allow null, or the model invents an age
},
"required": ["name", "age"],
}
for sentence in ["Priya is 29 years old and lives in Pune.", "Priya lives in Pune."]:
response = ollama.chat(
model=MODEL,
messages=[{
"role": "user",
"content": f"Extract the person's name and age. Use null for anything not stated.\n\nSentence: {sentence}",
}],
format=PERSON_SCHEMA, # Ollama constrains the output to this shape
options={"temperature": 0},
)
print(json.loads(response["message"]["content"])){'name': 'Priya', 'age': 29}
{'name': 'Priya', 'age': None}
With "age": {"type": "integer"} - null not allowed:
{'name': 'Priya', 'age': 29}
{'name': 'Priya', 'age': 0} <- invented: valid, and wrongWhere structured output is used
- Any time a program acts on what the model says, instead of showing it to a person.
- Extracting fields from documents, classifying messages, filling in a form, routing a request.
- Every one follows the same steps as this lesson: exact shape -> parse -> validate.
- Building it by hand first is the point of Module 1. In Module 2, LangChain output parsers and Pydantic models wrap the same ideas in less code.
Resume parser{"name": "John", "skills": ["React", "Node.js"], "experience_years": 5}Support ticket triage{"category": "payment", "priority": "high", "requires_human": true}Course tagging{"topic": "React", "category": "Frontend", "difficulty": "Beginner"}Agent tool calls (Lesson 1.5 on)The model says which tool to run, in a format your code parses.Structured output toolkit
json.loads(text)Parse a JSON string into Python values.
data = json.loads(raw)
json.JSONDecodeErrorRaised when the text is not valid JSON. A subclass of ValueError.
except json.JSONDecodeError as error:
error.msgThe short reason - useful to send back as feedback.
"Expecting value"
temperature 0Same prompt, same output: a consistent format, and identical failures.
options={"temperature": 0}format="json"Ollama constrains the reply to valid JSON.
ollama.chat(..., format="json")
format=schemaOllama constrains the reply to a JSON schema. Allow null for optional facts.
"age": {"type": ["integer", "null"]}isinstanceCheck a field has the type you expect.
isinstance(data["age"], int)
Try it yourself
The code does not change. Swap the content string and the program does something else entirely.
“Arjun, 34, works as a data engineer in Bengaluru.”
“Priya lives in Pune.”
“Priya is twenty-nine and lives in Pune.”
“Priya is 29 and her brother Arjun is 34.”
What usually goes wrong
Any extra sentence or markdown fence makes the whole reply unparseable.
✗ Give me the answer as JSON and explain it.✓ Respond with ONLY valid JSON. No explanation, no markdown.The content is always a string. Indexing it with a key raises a TypeError.
✗ raw = response["message"]["content"]
raw["name"]✓ data = json.loads(response["message"]["content"])
data["name"]One stray word and it raises. Catch json.JSONDecodeError.
✗ data = json.loads(raw)✓ try:
data = json.loads(raw)
except json.JSONDecodeError as error:
...Same input, same output: the retry reproduces the failure. Add the error to the conversation so the next attempt is different.
✗ for attempt in range(3):
raw = ollama.chat(... same messages ...)✓ messages.append({"role": "assistant", "content": raw})
messages.append({"role": "user", "content": f"That was not valid JSON ({error.msg}). Reply with only the JSON object."})A missing key, a null, or "twenty-nine" all parse cleanly. Validate the fields you use.
✗ age = json.loads(raw)["age"] + 1✓ data = validate_person(json.loads(raw))Require an integer age and the model will invent one - 0 in our run - when the input has none. Allow null for anything the input might not say.
✗ "age": {"type": "integer"}✓ "age": {"type": ["integer", "null"]}Key points
- Applications need data, not prose - structured output means asking for an exact JSON shape.
- The reply is a string; json.loads() turns it into a dict, and null into None.
- Tell the model the exact shape, and what to use for missing information.
- Temperature 0 makes the format consistent - and makes identical retries fail identically.
- Invalid JSON: retry with feedback. Valid JSON with wrong data: validate and reject.
- Validation checks that required fields exist and have the right type.
- format="json" or a schema lets Ollama enforce the shape - but a strict schema can make the model invent values.
Quick check before you move on
Quiz
- 1.
Why do we set temperature=0 here?
- 2.
What does the retry loop protect against?
- 3.
What Python function turns a JSON string into a Python dictionary?
- 4.
The model returns {"name": "Priya", "age": null} for "Priya lives in Pune." Should you retry?
- 5.
A schema requires age to be an integer. What can go wrong when the input has no age?
Interview questions
How would you handle structured output from an LLM?
Ask for an explicitly defined JSON structure at temperature 0, parse it with json.loads(), retry parse failures with the error fed back to the model, and validate the required fields and types before the data reaches the application. Where the runtime supports it, constrain the output with JSON mode or a schema - and still validate.
What is the difference between invalid JSON and invalid data?
Invalid JSON fails to parse - a formatting slip the model can correct on a retry with feedback. Invalid data parses fine but is missing fields, null, or the wrong type - usually because the input lacks the information, so retrying does not help and validation must catch it.
Does a JSON schema or JSON mode make validation unnecessary?
No. It guarantees the shape, not the truth. A schema that requires a value can push the model to invent one when the input does not contain it.
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...