Sub topic 4
Asking for a format in the prompt
This chapter assumes you know basic Python (classes and exceptions), can read JSON, and have called an LLM API at least once. It also assumes you have seen the TicketTriage model from the earlier chapter on schema models. Prompting is the simplest way to get structured output. It needs no special API features, so it works with any model. It also gives the weakest guarantees, which is why the validation step later in this chapter matters.
What a format prompt needs
A prompt that asks for a format should do four things:
- Say what the output is: "Reply with a single JSON object."
- Name every key and the allowed values for each one.
- Forbid extra text: "and nothing else."
- Include the input to process, clearly separated from the instructions.
A weak prompt such as "Triage this ticket as JSON" leaves too much open. The model may invent key names, wrap the answer in prose, or choose a priority scale you did not intend.
A stronger prompt spells the contract out:
PROMPT_TEMPLATE = """Triage the support ticket below.
Reply with a single JSON object and nothing else. Use exactly these keys:
- "category": one of "billing", "bug", "feature_request", "other"
- "priority": integer from 1 (most urgent) to 3 (least urgent)
- "summary": one sentence, at most 200 characters
Ticket:
{ticket}
"""
prompt = PROMPT_TEMPLATE.format(ticket="I was charged twice this month.")
print(prompt)Adding one example of a correct reply often helps more than extra rules. Put it after the key list and label it as an example, so the model does not copy its values.
Why prompting alone is unreliable
The model produces text one token at a time. Nothing in the API forces that text to be valid JSON or to match your keys. Common problems are:
- A code fence around the JSON, such as a
jsonfence. - A sentence before or after the object, like "Here is the result:".
- A wrong key name, such as
severityinstead ofpriority. - A value outside the allowed set, such as
"category": "Billing issue". - A number written as a string, such as
"priority": "1".
The first two are formatting problems, and you can often fix them in code. The last three are schema problems, and you need validation to catch them.
Cleaning the reply
Code fences are the most common formatting problem, so strip them before parsing:
def strip_code_fence(raw: str) -> str:
"""Remove a surrounding Markdown code fence, which models sometimes add."""
text = raw.strip()
if text.startswith("```"):
text = text.split("\n", 1)[1] if "\n" in text else ""
text = text.rstrip()
if text.endswith("```"):
text = text[:-3]
return text.strip()The function drops the opening fence line, including any language label such as json. It then removes the closing fence. Text that has no fence passes through unchanged, so you can call it on every reply.
Do not go further and try to extract JSON from the middle of prose with regular expressions. That approach breaks on nested braces and on braces inside strings. If the reply contains prose, treat it as a failure and retry.
Parse, then validate
Cleaning makes the reply parseable. It does not make it correct. Always parse into your schema model so that bad keys and values raise an error instead of passing silently:
from typing import Literal
from pydantic import BaseModel, Field, ValidationError
class TicketTriage(BaseModel):
category: Literal["billing", "bug", "feature_request", "other"]
priority: int = Field(ge=1, le=3)
summary: str = Field(max_length=200)
def parse_reply(raw: str) -> TicketTriage:
return TicketTriage.model_validate_json(strip_code_fence(raw))
good = '```json\n{"category": "billing", "priority": 1, "summary": "Double charge."}\n```'
bad = '{"category": "Billing issue", "priority": 7, "summary": "Double charge."}'
print(parse_reply(good))
try:
parse_reply(bad)
except ValidationError as err:
print(err)The first call succeeds even though the reply was fenced. The second raises a ValidationError that lists both problems: the category is not in the allowed set, and the priority is above 3. These error messages are useful, because the retry chapter feeds them back to the model.
The flow
Tips that improve reliability
- Keep the allowed values in one place and generate the prompt text from it, so the prompt and the schema cannot drift apart.
- Lower the temperature for extraction tasks. Randomness helps creative writing and hurts format compliance.
- Tell the model what to do when information is missing, for example "use \"other\" if no category fits". Otherwise it guesses.
- Keep the instructions short. Long prompts with many rules give the model more chances to miss one.
Exercise
A model replies with {"category": "bug", "priority": "2", "summary": "App crashes on login."}. The JSON parses without error. Why might validation still reject it, and what does that tell you about checking only that the reply is valid JSON?
Show answer
Pydantic in its default mode may accept the string "2" and convert it to an integer, but strict mode, or a schema that requires an integer, rejects it. The more important point is that valid JSON only means the syntax is correct. It says nothing about key names, types, or allowed values, so you must validate against the schema before using the data.
Exercise
Why is extracting a JSON object from the middle of a reply with a regular expression a poor way to handle a reply that contains prose around the JSON?
Show answer
A regular expression cannot reliably match nested braces or braces inside string values, so it can cut the object in the wrong place or return a fragment. A reply with extra prose is a sign the model ignored the format, so it is safer to treat it as a failure and retry.