RAG · Lesson 44 of 120
Structured Answers
Answer plus sources.
An app often needs more than text. It needs the answer, the list of sources, and whether the answer was found at all. Structured output gives us all three, as a Python object.

- Answer
- Sources
- Found or not
An answer object
Answer is a Pydantic model with three fields. With structured output makes the model fill those fields. We ask one question we can answer, and one we can't. Run it. The first is found, with its source. The second is marked not found.
structured.pypython
from pydantic import BaseModel
from rag_kit import load_docs, make_chunks, Index
from llm import llm, PROMPT
class Answer(BaseModel):
answer: str
sources: list[str]
found: bool
index = Index(make_chunks(load_docs()))
structured = llm.with_structured_output(Answer)
for q in ["How much does UK delivery cost?", "Do you sell skateboards?"]:
context = "\n\n".join(f"[{c['source']}] {c['text']}" for s, c in index.search(q))
r = structured.invoke(PROMPT.format(context=context, question=q))
print(r.found, r.sources, "|", r.answer[:45])Output
True ['shipping.md'] | Standard delivery in the UK costs £4.99, and False [] | I don't know
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter
def load_docs(folder="data/rag/northwind"):
return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]
def make_chunks(docs, size=300, overlap=50):
splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
return [{"source": d["source"], "text": t.replace("\n", " ")}
for d in docs for t in splitter.split_text(d["text"])]
embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")
def embed(texts):
return embedder.encode(texts, normalize_embeddings=True)
class Index:
def __init__(self, chunks):
self.chunks = chunks
self.vectors = embed([c["text"] for c in chunks])
def search(self, query, k=3):
scores = self.vectors @ embed([query])[0]
top = np.argsort(-scores)[:k]
return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]Also uses llm.py
from langchain.chat_models import init_chat_model
llm = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
PROMPT = """Answer the question using only the context below.
If the answer is not in the context, say "I don't know".
Context:
{context}
Question: {question}"""
def answer(question, chunks):
context = "\n\n".join(f"[{c['source']}] {c['text']}" for c in chunks)
return llm.invoke(PROMPT.format(context=context, question=question)).text.strip()Using the fields
Show the answer to the customer. Turn the sources into links. And when found is false, offer a way to contact a person. Your app decides what to do, instead of parsing text.
| key | value |
|---|---|
| answer | show it |
| sources | make links |
| found = false | hand to a person |
| No parsing | just fields |
Summary
Structured output returns the answer, its sources, and a found flag, ready for your app. Next, streaming.
Key takeaways- Pydantic model
- with_structured_output
- found flag
Next up: Streaming the Answer — word by word