Sub topic 7
Prompts and structured outputs for research tasks
This chapter assumes you can read Python, know what JSON is, and have written a basic prompt for a language model. It builds on the tool results from earlier chapters and shows how to ask the model for output that code can check.
Why structure matters
A free-text answer is hard to test. A reviewer must read it, and a script cannot tell whether a number came from a tool. A structured output is a reply in a fixed format, usually JSON, with named fields. Your code can validate it, and the report step can reuse it.
Parts of a research prompt
A reliable prompt for a research task has four parts:
- Role and task: one sentence, such as "Summarize last month's paid search performance for a marketing manager."
- Evidence: the tool results, pasted in as JSON and labeled as the only allowed source.
- Rules: what to do when data is missing, for example "If a value is null, write that it is unavailable. Never estimate."
- Output format: the exact fields, with a short example.
Put the evidence and rules before the format description. Say what the model must not do in plain terms, because vague rules such as "be accurate" change little.
Asking for a schema
Each claim in a report section should carry its number and its source. That lets the verification step compare claims against evidence later.
{
"section": "Paid search",
"claims": [
{"text": "Cost per click was 0.84.", "metric": "cpc", "value": 0.84, "source": "campaign_metrics"}
]
}Validating the reply
Never trust that the model followed the format. Parse the reply and check it in code before anything else uses it.
import json
CLAIM_FIELDS = {"text": str, "metric": str, "value": (int, float), "source": str}
def validate_section(raw):
"""Return (data, errors). data is None if the reply is not usable."""
try:
data = json.loads(raw)
except json.JSONDecodeError as exc:
return None, ["not valid JSON: " + str(exc)]
errors = []
if not isinstance(data, dict) or not isinstance(data.get("section"), str):
return None, ["missing string field: section"]
claims = data.get("claims")
if not isinstance(claims, list):
return None, ["missing list field: claims"]
for i, claim in enumerate(claims):
for field, kind in CLAIM_FIELDS.items():
if not isinstance(claim.get(field), kind):
errors.append("claim %d: bad or missing %s" % (i, field))
return data, errors
good = '{"section": "Paid search", "claims": [{"text": "CPC was 0.84.", "metric": "cpc", "value": 0.84, "source": "campaign_metrics"}]}'
bad = '{"section": "Paid search", "claims": [{"text": "CPC was low."}]}'
print(validate_section(good)[1])
print(validate_section(bad)[1])The first call prints []. The second prints three errors, one each for metric, value and source.
If validation fails, send the error list back to the model and ask for a corrected reply. Allow one or two retries, then stop and report the failure. This fits inside the step limit from the agent loop chapter.
Common errors
| Error | Effect | Fix |
|---|---|---|
| Asking for JSON but allowing extra prose | Parsing fails on the opening words | State "reply with JSON only" and strip code fences before parsing |
| No rule for missing data | The model fills gaps with plausible numbers | Require `null` plus a note, and test with a zero-click campaign |
| Pasting the whole data export | Slow, costly, and the key rows get lost | Pass only the tool results for the question |
| Validating shape only | A well-formed claim can still hold a wrong number | Check values against evidence in the verification step |
Keep prompts testable
Store prompts in version control and keep a few fixed test inputs, including one with missing data. After each prompt change, rerun them and compare the validation results. A change that fixes one report often breaks another.
Exercise
A model reply parses as valid JSON and passes validate_section, but one claim says "value": 21.0 for CPA while the tool returned 17.5. Which check catches this, and why did validation miss it?
Show answer
The number-checking step in verification catches it, for example by comparing claim values with the tool results. validate_section only checks that fields exist and have the right types, and 21.0 is a valid number.