Most FDE projects today involve putting a language model to work on a customer's own knowledge and processes. The demo version takes an afternoon; the version a regulated enterprise will trust with real users takes discipline. This lesson covers the patterns that make the difference: retrieval-augmented generation over messy customer documents, respecting document permissions, grounding answers with citations, structured output that downstream systems can rely on, prompts managed as code, choosing where the model runs, and an evaluation set built from discovery so every change is measured rather than guessed.
- Design a retrieval-augmented generation pipeline for real customer documents
- Enforce document permissions and cite sources in every answer
- Produce validated structured output for downstream systems
- Manage prompts and model choices as versioned, tested configuration
- Build and run an evaluation set from day one of a project
RAG over real customer documents
Retrieval-augmented generation (RAG) answers questions by first retrieving relevant passages from the customer's documents and then asking the model to answer using only those passages. It keeps answers grounded in the customer's own content and current without retraining. Every stage needs care with enterprise data.
- Ingest: extract text from PDFs, Word files, wiki pages and tickets; scanned documents need OCR; tables and headings carry meaning, so keep them.
- Chunk: split by document structure (sections, clauses, headings) rather than fixed character counts, and attach metadata: source, title, section, date, and access permissions.
- Index: store embeddings in a vector index and the text in a keyword index; many enterprise questions use exact codes, names and numbers that keyword search finds better.
- Retrieve: hybrid search (keyword plus vector), filtered by the user's permissions, then optionally rerank the top candidates.
- Generate: prompt the model with the retrieved passages, instruct it to answer only from them and cite each claim, and to say when the answer is not in the sources.
import re
def chunk_policy(doc_id: str, text: str, acl: list[str], max_chars: int = 2000):
sections = re.split(r"\n(?=Section \d+[.:])", text) # split at 'Section 4.' headings
for i, sec in enumerate(sections):
heading = sec.strip().splitlines()[0][:120] if sec.strip() else ""
for start in range(0, len(sec), max_chars):
yield {
"id": f"{doc_id}:{i}:{start}",
"text": sec[start:start + max_chars],
"doc_id": doc_id,
"heading": heading,
"acl": acl, # groups allowed to see this document
}Permissions and citations
In an enterprise, not everyone may read every document. A RAG system that retrieves across all documents and lets the model summarise them will leak HR files, board papers or other customers' contracts to anyone who asks the right question. Carry each document's access control list into the index and filter retrieval by the requesting user's groups, from the identity provider, before anything reaches the model. Never rely on the prompt to keep secrets.
def answer(question: str, user_groups: set[str]) -> dict:
hits = index.search(question, top_k=40) # hybrid search
allowed = [h for h in hits if user_groups & set(h["acl"])][:8] # enforce ACLs first
if not allowed:
return {"answer": "I could not find this in documents you can access.", "sources": []}
context = "\n\n".join(f"[{i + 1}] {h['heading']}\n{h['text']}" for i, h in enumerate(allowed))
prompt = ("Answer using only the numbered sources. Cite like [2]. "
"If the sources do not contain the answer, say so.\n\n"
f"Sources:\n{context}\n\nQuestion: {question}")
return {"answer": call_llm(prompt), "sources": [h["doc_id"] for h in allowed]}Citations do more than build trust: they let users verify an answer in seconds, and they let you debug whether a wrong answer came from bad retrieval (the right passage was not found) or bad generation (it was found but misused). Show the cited passages in the interface, linked to the source.
Structured output for downstream systems
Many FDE workflows do not end in a chat answer but in data: fields extracted from a claim form, a classification routed to a queue, a draft record for a CRM. Ask the model for structured output against a schema, validate every response, and decide what happens when validation fails (retry once with the error, then send to a human queue).
from pydantic import BaseModel, Field, ValidationError
class ClaimFields(BaseModel):
policy_number: str = Field(pattern=r"^POL-\d{8}$")
incident_date: str = Field(pattern=r"^\d{4}-\d{2}-\d{2}$")
claim_type: str = Field(pattern=r"^(motor|home|travel)$")
amount_claimed: float = Field(ge=0)
def extract(text: str) -> ClaimFields | None:
raw = call_llm(f"Extract the claim fields as JSON matching this schema: "
f"{ClaimFields.model_json_schema()}\n\n{text}")
try:
return ClaimFields.model_validate_json(raw)
except ValidationError:
return None # route to human review queuePrompts, models and where they run
- Prompts are code: keep them in version control as templates, review changes, and tie each deployed version to its evaluation results.
- Model choice is configuration, not hard-coded: a capable model for hard reasoning, a smaller, cheaper one for routing or extraction, selected per task through a gateway.
- Where the model runs is a customer decision: a hosted API (check data retention and residency terms), a model in the customer's cloud account, or a self-hosted open-weight model on their infrastructure when data cannot leave.
- Cost and latency scale with tokens: retrieve fewer, better passages; cache repeated prompts; set max output tokens.
- Prompt injection: retrieved documents and user input can contain instructions; never let model output trigger actions without validation, which the agents lesson covers.
Evaluation from day one
Without an evaluation set, every prompt tweak is a guess and every demo is anecdote. Build one in week one from discovery: real questions or documents from users, with expected answers or fields agreed with domain experts. Start with 50 to 200 items and grow it with every failure found in testing.
| What to measure | How | Why |
|---|---|---|
| Retrieval recall | Is the passage containing the answer in the top k? | Separates retrieval from generation problems |
| Answer correctness | Expert review, or an LLM judge calibrated against experts | The quality users feel |
| Groundedness | Is every claim supported by a cited source? | Catches hallucination |
| Refusal behaviour | Does it say 'not found' when the answer is absent? | Prevents confident wrong answers |
| Field accuracy | Exact or normalised match per extracted field | Structured-output workflows |
Run the evaluation on every change to prompts, retrieval settings or models, and put the numbers in your weekly status. 'Correct answers rose from 81% to 92% on 150 expert-reviewed questions' is the sentence that wins the go decision.