Education › Forward Deployed › Stage 3: Building & integrating

Building LLM applications for customers

Retrieval-augmented generation over customer documents, prompts as code, structured output and evaluation from day one.

Intermediate ~45 min read Module 10 of 20

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.

After this module you can
  • 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.

  1. Ingest: extract text from PDFs, Word files, wiki pages and tickets; scanned documents need OCR; tables and headings carry meaning, so keep them.
  2. Chunk: split by document structure (sections, clauses, headings) rather than fixed character counts, and attach metadata: source, title, section, date, and access permissions.
  3. 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.
  4. Retrieve: hybrid search (keyword plus vector), filtered by the user's permissions, then optionally rerank the top candidates.
  5. 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.
Structure-aware chunking that keeps metadata (simplified)
python
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.

askgroupssearchcandidatesallowed passagescited answerUserIdentity (IdP)groupsAppquestion + groupsHybrid indexchunks + ACLsACL filterbefore the modelModelanswer + citations
Permission-aware RAG: the user's groups from SSO filter retrieval before anything reaches the model, and every answer cites the passages it used.
Permission filter applied before generation (illustrative store API)
python
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).

Validate extracted fields before they touch a customer system
python
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 queue

Prompts, 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 measureHowWhy
Retrieval recallIs the passage containing the answer in the top k?Separates retrieval from generation problems
Answer correctnessExpert review, or an LLM judge calibrated against expertsThe quality users feel
GroundednessIs every claim supported by a cited source?Catches hallucination
Refusal behaviourDoes it say 'not found' when the answer is absent?Prevents confident wrong answers
Field accuracyExact or normalised match per extracted fieldStructured-output workflows
Tip

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.

Hands-on practice

A permission-aware RAG assistant with evals

  1. Collect 30 to 50 public documents with clear structure (policies, manuals, regulations) and assign each to one of two 'groups'.
  2. Implement structure-aware chunking with metadata and ACLs, and index the chunks in a local vector store plus a keyword index.
  3. Write the answer() function with permission filtering and citations, using any model you have access to as call_llm.
  4. Prove the ACL filter works: a user in group A must never see content only group B may read, even when asked directly.
  5. Write 40 evaluation questions with expected answers and source documents; measure retrieval recall at k=8 and answer correctness.
  6. Change one thing (chunk size, hybrid versus vector-only, top_k) and rerun the evaluation; record the before and after.
Cheat sheet

Building LLM applications for customers — at a glance

Main things to focus on

  • RAG: ingest, chunk by structure, hybrid index, permission-filtered retrieval, cited generation.
  • Filter by the user's permissions before retrieval results reach the model.
  • Citations let users verify and let you tell retrieval failures from generation failures.
  • Structured output: schema, validation, fallback to human review.
  • Prompts and model choices are versioned configuration tied to eval results.
  • Evaluation set from discovery in week one; run it on every change.

RAG pipeline

ingest -> chunk -> embed + keyword indexIndexing
chunk metadata: source, heading, date, aclNeeded for filters and citations
hybrid search -> ACL filter -> rerank -> top kRetrieval
'answer only from sources; cite [n]; say if absent'Generation instruction

Structured output

class Fields(BaseModel): ...Schema in code
Fields.model_validate_json(raw)Validate model output
Fields.model_json_schema()Give the schema to the model
on failure: retry once, then human queueFallback

Evaluation

recall@kRight passage retrieved?
correctness (expert or calibrated judge)Right answer?
groundednessClaims supported by sources?
refusal when absentAdmits not knowing?
field-level accuracyExtraction quality

Deployment choices

hosted APICheck retention and residency terms
model in customer cloud accountData stays in their tenancy
self-hosted open weightsWhen data cannot leave

Common pitfalls

  • Retrieving across all documents and relying on the prompt to hide restricted content.
  • Fixed-size chunks that cut clauses and tables in half.
  • Vector-only search that misses exact codes and names.
  • Writing model output into customer systems without validation.
  • No evaluation set, so every change is judged by a few hand-picked examples.
Quiz

Check your understanding

5 questions · 4 to pass · answers are explained as you go. Your best score is saved on this device only.

Progress and quiz scores are saved in this browser only. Back up or restore on the hub.

Was this lesson useful? Tell me what to improve →