Sub topic 7
Structured Output: Claims with Source IDs
This chapter assumes you can call a model through an API, read JSON, and write basic Python. It also assumes you have already numbered your sources as in the earlier chapters on context assembly and citation formats.
Why use structured citations
Inline markers like [2] are easy to ask for, but they are hard to check. A marker sits somewhere in free text, and you cannot tell which sentence it supports. Structured output fixes this by asking the model for a JSON object. Each claim in the object lists the source ids it relies on and a short quote from those sources.
This gives your code three things to check:
- The source ids exist.
- The quote appears in the cited source.
- Each claim has at least one source.
The shape of the output
Here is a structured answer. The answer field is the full text for the user. The claims list breaks that text into statements you can verify one by one.
{
"answer": "The service retries failed requests up to three times.",
"claims": [
{
"text": "The service retries failed requests up to three times.",
"source_ids": [2],
"quote": "failed requests are retried up to three times"
}
]
}The quote must be copied word for word from the source. This is what lets code check the claim later. A paraphrase would not match the source text.
Asking for this format
Add the schema to your prompt, or use your API's JSON or schema-constrained mode if it has one. State the rules plainly:
- Every factual statement is one entry in
claims. source_idsuses only the numbers shown in the sources.quoteis copied exactly from one cited source.- If the sources do not answer the question, return an empty
claimslist and the abstention text from the previous chapter.
Checking the response in code
Parse the JSON first. Models sometimes return invalid JSON, so handle that case. Then check each claim. The helper below reuses the quote check from the verification approach in this tutorial.
import json
def normalize(text):
return " ".join(text.lower().split())
def quote_is_supported(quote, source_text):
"""True if the quote appears verbatim in the source, ignoring case and whitespace."""
return normalize(quote) in normalize(source_text)
def check_structured_answer(raw, sources):
"""sources: list of dicts with 'text'. Returns a list of problem descriptions."""
try:
data = json.loads(raw)
except json.JSONDecodeError:
return ["Response is not valid JSON."]
problems = []
for i, claim in enumerate(data.get("claims", []), start=1):
ids = claim.get("source_ids", [])
if not ids:
problems.append(f"Claim {i} has no source ids.")
continue
for n in ids:
if not isinstance(n, int) or not 1 <= n <= len(sources):
problems.append(f"Claim {i} cites unknown source {n}.")
valid = [n for n in ids if isinstance(n, int) and 1 <= n <= len(sources)]
quote = claim.get("quote", "")
if valid and not any(
quote_is_supported(quote, sources[n - 1]["text"]) for n in valid
):
problems.append(f"Claim {i}: quote not found in cited sources.")
return problemsAn empty list means the structure passed. It does not mean the sources support the claim. A model can quote a real sentence and still draw a wrong conclusion from it. Later chapters cover that check.
The flow
Trade-offs
| Approach | Strength | Cost |
|---|---|---|
| Inline markers | Simple, reads naturally | Hard to tie a marker to one claim |
| Structured claims | Each claim is checkable | Longer output, more parsing code |
Exercise
A claim lists source_ids [4] but only three sources were supplied. Which check catches this, and what should your code do with the answer?
Show answer
The source id range check (1 <= n <= number of sources) catches it. The code should treat the answer as invalid and reject it or retry the request, instead of showing the citation to the user.