Search Tutorials
--Ads--Structured RAG Outputs
Return validated JSON answers with sources and confidence using Pydantic.
A chat window can show free text, but many RAG applications need answers that code can use: a field to display, a flag that says whether the answer was found, a list of sources to link, a confidence level that decides whether to escalate to a human. Structured outputs make the model return JSON that matches a schema you define, every time.
Define the answer schema
from typing import Literal
from pydantic import BaseModel, Field
import anthropic
client = anthropic.Anthropic()
class Evidence(BaseModel):
source_id: int
quote: str = Field(description="Exact sentence copied from the source")
class RagAnswer(BaseModel):
answer_found: bool
answer: str = Field(description="Short answer for the user; empty if not found")
evidence: list[Evidence]
confidence: Literal["high", "medium", "low"]
follow_up_needed: bool = Field(description="True if a human should review or act")
Ask for it
With the Python SDK, messages.parse() takes a Pydantic model, sends its JSON schema to the API, and returns a validated object. The API constrains the output to the schema, so you never get malformed JSON or missing fields.
def structured_answer(question: str, hits: list[dict]) -> RagAnswer:
sources = "\n".join(f'<source id="{i}">\n{h["text"]}\n</source>'
for i, h in enumerate(hits, start=1))
response = client.messages.parse(
model="claude-opus-5-5",
max_tokens=2000,
output_config={"effort": "low"},
system="You answer employee questions from company policy sources. Quote evidence "
"exactly. Set answer_found to false if the sources do not answer the question.",
messages=[{"role": "user", "content": f"<sources>\n{sources}\n</sources>\n\nQuestion: {question}"}],
output_format=RagAnswer,
)
return response.parsed_output
result = structured_answer("Is there a limit on hotel costs in metro cities?", hits)
print(result.model_dump_json(indent=2))
{
"answer_found": true,
"answer": "Yes. Hotel costs are covered up to 6,000 rupees per night in metro cities.",
"evidence": [
{"source_id": 1, "quote": "Hotel costs are covered up to 6,000 rupees per night in metro cities and 4,000 rupees elsewhere."}
],
"confidence": "high",
"follow_up_needed": false
}
Verify the evidence
The schema guarantees the shape of the output, not the truth of its content. Because the evidence quotes are supposed to be copied exactly, you can check them cheaply:
def normalise(s: str) -> str:
return " ".join(s.lower().split())
def verify_evidence(result: RagAnswer, hits: list[dict]) -> list[str]:
problems = []
for e in result.evidence:
if not 1 <= e.source_id <= len(hits):
problems.append(f"unknown source id {e.source_id}")
elif normalise(e.quote) not in normalise(hits[e.source_id - 1]["text"]):
problems.append(f"quote not found in source {e.source_id}: {e.quote[:60]}")
if result.answer_found and not result.evidence:
problems.append("answer given without evidence")
return problems
If verification fails, you can retry, lower the displayed confidence, or route the question to a human.
Using the structure in your application
def respond(question: str, hits: list[dict]) -> dict:
result = structured_answer(question, hits)
problems = verify_evidence(result, hits)
if not result.answer_found:
return {"type": "not_found", "message": "I couldn't find this in the policies. "
"Please contact HR at [email protected]."}
if problems or result.confidence == "low" or result.follow_up_needed:
return {"type": "needs_review", "draft": result.answer, "issues": problems}
return {"type": "answer", "text": result.answer,
"sources": [hits[e.source_id - 1]["title"] for e in result.evidence]}
Things to know
- Model-reported confidence is a rough signal, not a calibrated probability. Combine it with checks you control, such as evidence verification and rerank scores.
- Keep schemas small and flat. Fewer, clearly described fields give better results than deeply nested ones.
- Structured output and built-in citations cannot be used in the same request. Use evidence quotes in the schema, as above, when you need both.
- Streaming still works with structured output, but partial JSON is only useful once complete; for live text display, stream a plain-text answer instead.
Key takeaways
- Structured outputs return JSON that always matches your schema; use
messages.parse()with Pydantic. - Include fields your application acts on: found or not, answer, evidence, confidence, escalation.
- Verify evidence quotes against the sources in code.
- Use the structure to route answers: show, ask for review, or report "not found".