Generative AI, Agentic AI and RAG
Take one knowledge assistant from a model-only baseline to evaluated agentic RAG.
Build one fictional internal knowledge assistant three times: a model-only baseline, fixed retrieval-augmented generation (RAG) over PostgreSQL and pgvector, and a bounded agent with typed read-only tools. Then compare all three on the same questions. The path goes deeper than the introduction in AI Engineering with Python, focusing on retrieval quality, permission-aware search, verifiable citations, agent decisions and evaluation, in plain Python before any framework. Modules 1–2 are beginner, modules 3–7 are intermediate and modules 8–11 are advanced. You should know Python functions and type hints, Git, JSON, HTTP and basic SQL; Python from Zero, SQL & PostgreSQL and AI Engineering with Python cover those. Every lab runs locally with a deterministic model stub and small synthetic documents; a hosted or local model is optional.
01Models, tasks and a baseline
Beginner. Where generative models fit a workflow, how inference behaves, and a first typed model call against a deterministic stub.
- Where a generative AI step fits in a business workflowA generative model is one tool among several for automating a workflow step, not the default answer. Rules suit steps with fixed logic, a trained classifier suits steps that pick from a known list, and a generative model suits steps that must read or write free-form language. Because generative output can vary from run to run, you also decide where a person checks it before it reaches a customer or a system of record.11 min
- Tokens, context windows and sampling across input typesModels do not read characters or pixels directly. Text, images, audio and documents are turned into tokens, and the model predicts the next token one step at a time until it stops. The context window caps how many tokens fit in one request, and sampling settings such as temperature control how much the output varies between runs.11 min
- A typed first model call with a deterministic stubYour application should call models through one small typed interface, not scatter provider SDK calls through the code. Behind that interface you can plug in a deterministic fake for tests, a hosted model or a local model. Every call records which model answered, how many tokens it used and what you assume it cost, so later comparisons are fair.11 min
02Prompts and output guarantees
Beginner. Versioned prompts, schema-validated output and a measured baseline with success criteria set before retrieval or tools.
- A versioned prompt that triages support requestsA prompt is part of your program's code, so it deserves a clear task definition, a fixed output format, worked examples and a version number. For support triage, the prompt turns a synthetic request into a category, a short summary and a suggested next step. It also tells the model exactly what to return when the request lacks the information needed, instead of letting it guess.10 min
- Validate model output against a schema and escalateModel output is untrusted text until your code checks it. A Pydantic model describes the exact shape you accept, and validation either returns a typed object or raises a clear error. Anything that fails validation, any unknown category, refusal or ambiguous result goes to an escalation path where a person decides.10 min
- Measure accuracy, latency and cost before adding retrievalBefore adding retrieval or tools, measure how well the simple version works. Label a small test set, run it through a rule-based baseline and the model-only version, and score accuracy, schema validity, latency and cost per request. Write the success criteria down first, so later changes are judged against numbers rather than impressions.10 min
03Prepare, index and maintain your sources
Intermediate. A versioned synthetic corpus, chunking and embeddings in PostgreSQL with pgvector, and an index that stays fresh.
- Build a versioned support corpus for retrievalA RAG system can only be as good as the documents it searches, so the first job is a small, well-labelled corpus. Every document gets a stable ID, stable section IDs, a version number, a source URI, a visibility label and an effective date. Those fields later let you cite sources, filter by permission, pick the newest rule and delete cleanly.11 min
- Chunking strategies and versioned embeddings in pgvectorDocuments are split into chunks small enough to retrieve and quote, then each chunk is turned into an embedding: a list of numbers that places similar meanings close together. Token-window chunking cuts fixed-size pieces with overlap; heading-based chunking follows the document's own structure. Storing the model name and dimension with every embedding lets you change models without mixing incompatible vectors.12 min
- Keep a RAG index fresh with upserts and deletionsA RAG index goes stale the moment a source changes, so ingestion must be a repeatable job, not a one-off script. Idempotent upserts mean running the job twice leaves the same result. The job also records parse failures, marks old versions as superseded and makes deleted sources disappear from search while keeping provenance for audit.11 min
04Find the right evidence
Intermediate. Lexical, vector and hybrid search, reranking within a context budget, and permission filtering at retrieval time.
- Compare keyword, vector and hybrid retrieval in PostgreSQLKeyword search matches the exact words in a question, vector search matches meaning, and hybrid search combines both rankings. Each one wins on different questions: keywords find error codes and product names, vectors find paraphrases. Running all three over the same labelled question set shows you where each fails instead of guessing.12 min
- Rerank candidates and fit evidence into a context budgetFirst-stage search is fast but rough, so a reranker reads each question and candidate pair together and reorders a small set, often 20 to 50 chunks. You then drop near-duplicates, cut anything below a tested score threshold and pack the best evidence into a fixed token budget. A high score only means the reranker found the text similar; it does not prove the chunk answers the question.11 min
- Permission-aware retrieval for two user scopesIf a document the caller is not allowed to see reaches the model, it can leak into the answer, no matter what the prompt says. So permission filtering belongs inside the retrieval query, based on the caller's verified identity. You prove it with tests that run the same question under two scopes, and you include identity and data version in every cache key.11 min
05Ground, cite and abstain
Intermediate. Answers with validated citations, handling of conflicting and outdated sources, and retrieval evaluation by failure stage.
- Answers with validated source IDs or a reason to abstainA grounded answer is a typed record, not free text: a status, the answer text, the source IDs it relies on and, when there is no answer, a reason. Your code checks every cited ID against the evidence that was actually retrieved for this caller, so a model cannot cite a document it never saw or one the caller is not allowed to see. When the check fails or the evidence is thin, the assistant abstains or escalates instead of guessing.12 min
- Resolve outdated and contradictory sources in RAG answersReal corpora contain old versions, drafts, forum notes and policies that disagree. Before generation, your code ranks evidence by authority, effective date and version, and removes anything superseded or not yet in effect. When two current, authoritative snippets still disagree, the answer says so and flags the conflict instead of quietly picking one.11 min
- Score recall@k, ranking and citation support separatelyA RAG answer can fail at several stages, so one overall score hides the cause. Score retrieval with recall@k and rank metrics against labelled expected sources, score generation by whether each citation really supports its claim, and keep these scores separate. Then classify every failure by the stage that caused it: ingestion, search, permission filtering or generation.11 min
06Give agents bounded choices
Intermediate. When an agent beats a workflow, typed read-only tools, run state and memory, and a decision loop with hard limits.
- Fixed call, workflow, agent or delegation: choosing by evidenceAn agent is a system where the model decides which step to take next, usually by choosing tools in a loop. That flexibility costs extra model calls, latency and unpredictability, so it should be chosen on evidence. Compare four options in order of complexity: a fixed model call, a deterministic workflow your code controls, a single tool-using agent and delegation between agents, and pick the simplest one that meets your measured targets.11 min
- Typed read-only tools for a support agentTools are functions your code exposes to the model, each with a name, a description and an input schema. For a support agent, start with two read-only tools: knowledge search and ticket status. Validate every argument, take the caller's identity from the server-side session rather than from anything the model writes, and return only the fields the task needs.11 min
- Agent run state, conversation history and long-term memoryAn agent keeps four different kinds of state, and mixing them causes leaks and bugs. Per-run state lives for one request; conversation history lives for one session; persisted workflow state lets a long task pause and resume; long-term memory carries facts across sessions. Each needs a clear owner, an isolation key and a deletion rule.10 min
- A bounded agent loop with budgets, deadlines and cancellationAn agent loop must always stop, and it must stop with a useful result. Give each run an allowlist of tools, caps on tool calls and tokens, a wall-clock deadline and support for cancellation. Whatever happens, the run ends in either an answer or an escalation with a reason, never in silence or an endless loop.11 min
07Let an agent choose how to retrieve
Intermediate. Routing questions, aggregating evidence across retrieval steps, and serving the agent behind a typed FastAPI endpoint.
- Route questions to retrieve, clarify, reformulate or abstainFixed RAG runs the same retrieve-then-answer steps for every question. A routing step lets the assistant pick a better action first: ask the user to clarify, search the documents, look up a reference value, rewrite the query a limited number of times, or abstain. You only keep the router if it beats fixed RAG on the same test questions.12 min
- Combine evidence across multiple retrieval stepsWhen an agent searches more than once, it collects evidence from several steps. Aggregation means merging those results into one clean evidence set: each source keeps a record of which step and query found it, repeated searches are skipped, duplicates are merged, and anything the caller may not see is dropped before drafting. The answer may cite only what is left in that set.11 min
- Serve the knowledge agent behind a typed FastAPI endpointA service contract says exactly what the API accepts, what it returns and how it fails. For the knowledge assistant that means a typed FastAPI endpoint that authenticates the caller, attaches a request ID, returns an answer or status with source IDs, enforces a deadline, stops work when cancelled and never leaks internal errors.11 min
08Review tools, routing and failure modes
Advanced. Single versus multi-agent trade-offs, trust-boundary tests, and fallbacks when models, tools or budgets fail.
- One agent or a specialist handoff: a controlled comparisonA multi-agent design splits work between agents, for example a general agent that hands policy questions to a specialist. Each handoff adds a model call, more state to pass and new ways to fail. A controlled comparison runs one agent and the handoff design on the same cases with the same model, tools and budgets, and keeps the handoff only if it measurably helps.10 min
- Test agent trust boundaries with untrusted text and tool dataEverything the model reads can contain instructions: the user's question, retrieved passages and tool results. Prompt injection, the top risk in the OWASP Top 10 for LLM applications, is when such text tries to change what the system does. Trust-boundary tests plant harmless conflicting instructions in each input and prove that access checks and read-only tools still hold, because they are enforced in code, not by the prompt.11 min
- Fallbacks for failed models, tool timeouts and spent budgetsAgent runs fail in predictable ways: the model returns invalid output, the model provider is down, the client disconnects, a tool times out, or the budget runs out. For each failure you choose a planned response in advance: retry, fail over to another model, stop, fall back to fixed RAG, or escalate to a person. The run must always end with a clear status, never a hang or a guess.12 min
09Measure answer and tool quality
Advanced. A versioned golden dataset, trajectory scoring for tool use, and regression baselines across all three versions.
- A versioned golden dataset for a knowledge assistantA golden dataset is a fixed, versioned set of test requests with the outcome you expect for each one: which sources should be cited, whether the assistant should answer, ask, abstain or refuse. It covers answerable, unanswerable, ambiguous, outdated and unauthorised requests, so every later change to prompts, models, retrieval or tools is measured against the same yardstick. Because it is synthetic and stored in Git, anyone can rerun it and get comparable numbers.12 min
- Score agent trajectories, tool calls and token costA trajectory is the full record of one agent run: every model call, tool call, argument, result, timing and token count, plus the final answer. Scoring the trajectory, not just the final text, shows whether the agent used only allowed tools, wasted calls, cited real evidence and stayed inside its latency and cost budgets. Good scoring checks outcomes and constraints, so two different but valid paths both pass.11 min
- Compare model-only, fixed RAG and agentic RAG baselinesRegression baselines compare the model-only, fixed RAG and agentic RAG versions of the assistant over exactly the same cases, scorers and dataset version. Deterministic checks run first because they are cheap and repeatable; model grading is added only for fuzzy qualities and is calibrated against human labels. The results set rollout thresholds, so a new version ships only when it beats or matches the current one on agreed numbers.10 min
10Deploy, observe and maintain
Advanced. Tracing and cost tracking without sensitive content, safe index and model releases, and reproducible deployment with recovery drills.
- Trace retrieval, model and tool spans without leaking contentA trace follows one request through the assistant as a tree of spans: the API request, retrieval, each model call and each tool call, all sharing one trace ID. From those spans you derive the numbers that matter in production: p50 and p95 latency, abstention rate, failure modes and spend per request. The hard part is doing this without copying questions, passages or answers into logs, so traces record IDs, counts and timings instead of content.10 min
- Release prompt, model and index revisions with rollbackPrompts, models, embedding models and the index are one release unit: an embedding model change makes old vectors incomparable with new query vectors, and a prompt may depend on how chunks are shaped. A safe release builds the new index beside the old one with versioned metadata, sends candidate traffic through it, compares results against defined criteria and switches with a single pointer change. Rollback is the same pointer change in reverse.11 min
- Reproducible deployment and recovery drills for a RAG agentA reproducible deployment means anyone can start the same API, PostgreSQL with pgvector and fixture model from one Compose file and get the same results. Recovery means you have practised restoring the database from a backup and know what the assistant does when a source is invalid or a dependency is down. Both are rehearsed locally first, and a hosted option is documented without being required.11 min
11Ship an evaluated knowledge assistant
Advanced. Design, build and verify a knowledge assistant over 10–20 synthetic documents in two scopes, compared across all three versions.
- Agentic RAG capstone: design the assistant and its targetsThe design is the contract for the whole capstone. Before writing code you fix the corpus of 10 to 20 versioned synthetic documents in two permission scopes, the model-only baseline, the request and response schemas, the allowed read-only tools, the budgets and the evaluation targets. Fixing these first means all three versions are judged by the same rules, not rules adjusted after seeing results.13 min
- Agentic RAG capstone: build fixed RAG and the bounded agentThe build turns the design into running code: an ingestion job that loads the corpus into PostgreSQL with pgvector and full-text search, a fixed RAG pipeline and a bounded agent with typed mock tools. Both sit behind one authenticated FastAPI endpoint that checks every citation and can run fully offline in fixture mode.14 min
- Agentic RAG capstone: compare versions and document resultsVerification runs the same 20 fixture cases against the model-only baseline, fixed RAG and the bounded agent, then reports what each version got right, what it cost and where it failed. It must show missing-source and denied-document behaviour, prove zero cross-scope disclosures, and end with a written record of evidence, limitations, cost and a rollback plan.13 min