Generative AI, Agentic AI and 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.
What you will be able to do
- Choose between rules, a single model call, fixed RAG and an agent for a given workflow
- Build a versioned ingestion and retrieval pipeline in PostgreSQL with pgvector
- Return answers with validated citations, or abstain with a clear reason
- Design a bounded agent with typed, read-only, permission-checked tools and budgets
- Evaluate model-only, fixed RAG and agentic RAG on the same fixture set
- Serve the assistant through a reproducible, authenticated FastAPI service
Roadmap
Bar length shows each module's share of study time.
- 17h 30m3 topics
Models, tasks and a baseline
Beginner. Where generative models fit a workflow, how inference behaves, and a first typed model call against a deterministic stub.
Show topicsNot startedDecide for a given workflow step whether rules, a classifier or a generative model fits best and where human review is needed.
- Map the workflow and its inputs
- Compare rules, classifiers and generation
- Spot steps where variation is harmful
- Place human review points
Explain how text, image, audio and document inputs become tokens and how sampling, context size and latency shape the output.
- Map input types to generation tasks
- Count tokens and fit a context window
- Tune temperature and other sampling settings
- Measure latency and run-to-run variation
Call a model through one typed interface that swaps between a fake, a hosted and a local model and records identity, usage and cost.
- Define a typed model interface
- Build a deterministic fake model
- Compare hosted and local options
- Log model ID, usage and cost assumptions
- 28h 30m3 topics
Prompts and output guarantees
Beginner. Versioned prompts, schema-validated output and a measured baseline with success criteria set before retrieval or tools.
Show topicsNot startedWrite a versioned prompt with few-shot examples that returns a category, summary and next step and handles missing information.
- Define the task and output fields
- Add few-shot examples
- Handle missing information explicitly
- Version prompts alongside code
Validate model output with Pydantic and route unknown categories, refusals and malformed values to an escalation path.
- Model the output with Pydantic
- Reject unknown categories
- Detect refusals and malformed values
- Route ambiguous results to a person
Score a labelled set for accuracy, schema validity, latency and cost and set success criteria before adding retrieval or tools.
- Label a small test set
- Score accuracy and schema validity
- Record latency and cost per request
- Write success criteria up front
Module resources:OpenAI: prompt engineering ↗ - 310h3 topics
Prepare, index and maintain your sources
Intermediate. A versioned synthetic corpus, chunking and embeddings in PostgreSQL with pgvector, and an index that stays fresh.
Show topicsNot startedCreate a small synthetic corpus with stable document and section IDs, versions, source URIs, visibility and effective dates.
- Write or license source documents
- Assign stable document and section IDs
- Store version, source URI and effective date
- Record visibility for each document
Compare token-window and heading-based chunking and store versioned embeddings in pgvector that survive a model change.
- Chunk by token window and by heading
- Store embeddings with model and version
- Choose vector dimensions and an index
- Re-embed when the model or dimension changes
Run repeatable ingest, re-index and delete jobs that handle failed parsing and stale versions and remove deleted sources from retrieval.
- Make upserts idempotent
- Record failed parses and retry
- Supersede stale versions
- Remove deleted sources from results
- Keep provenance for every chunk
- 410h 30m3 topics
Find the right evidence
Intermediate. Lexical, vector and hybrid search, reranking within a context budget, and permission filtering at retrieval time.
Show topicsNot startedRun keyword, vector and hybrid retrieval over one question set and explain where each wins or fails.
- Query with PostgreSQL full text search
- Query with pgvector similarity
- Fuse results into a hybrid ranking
- Apply metadata filters
- Name common failure patterns
Rerank a candidate set and select deduplicated evidence within a token budget, with thresholds you can justify.
- Rerank a small candidate set
- Suppress near-duplicate chunks
- Set score thresholds
- Fit evidence to a token budget
- Weigh reranking latency
Filter retrieval by the caller's permissions, prove a denied document never appears, and scope caches to identity and data.
- Filter by caller scope in the query
- Test a denied document with two scopes
- Consider row-level security
- Include identity and data version in cache keys
Module resources:PostgreSQL: full text search ↗ - 59h3 topics
Ground, cite and abstain
Intermediate. Answers with validated citations, handling of conflicting and outdated sources, and retrieval evaluation by failure stage.
Show topicsNot startedReturn an answer with source IDs that are checked against the caller's visible evidence, or an abstain or escalate reason.
- Define the answer and citation schema
- Check each citation against retrieved evidence
- Reject citations the caller cannot see
- Return abstain or escalate reasons
Apply provenance and freshness rules to conflicting snippets and flag evidence that is missing or unresolved.
- Rank evidence by effective date and version
- Detect contradictory snippets
- Prefer authoritative sources
- Flag unresolved conflicts in the answer
Measure recall@k, rank quality and citation support independently and classify each failure by pipeline stage.
- Label expected sources per question
- Compute recall@k and rank metrics
- Check citation support
- Classify failures by stage
- 612h 30m4 topics
Give 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.
Show topicsNot startedChoose between a fixed model call, a deterministic workflow, a single tool-using agent and delegation using observable criteria.
- Describe each option's control flow
- List observable reasons to pick each
- Estimate cost and latency of each
- Default to the simplest option that works
Define typed knowledge-search and ticket-status tools that validate input, authorise each call with trusted identity and return minimal data.
- Define tool schemas with Pydantic
- Validate every tool input
- Authorise with trusted identity, not model text
- Return only the fields needed
Separate per-run state, conversation history, persisted workflow state and long-term memory with clear ownership, isolation and deletion.
- Define per-run state
- Store conversation history per session
- Persist workflow state
- Scope and delete long-term memory
Implement an agent loop with allowed tools, call and token budgets, a deadline and cancellation that always ends in an answer or escalation.
- Allowlist tools per run
- Cap tool calls and tokens
- Enforce a deadline
- Handle cancellation
- Return an answer or escalation
Module resources:Google Cloud: choose agentic AI architecture components ↗ - 710h3 topics
Let an agent choose how to retrieve
Intermediate. Routing questions, aggregating evidence across retrieval steps, and serving the agent behind a typed FastAPI endpoint.
Show topicsNot startedRoute each question to clarification, retrieval, reference lookup, bounded reformulation or abstention and compare outcomes with fixed RAG.
- Define the route options
- Ask for clarification when needed
- Limit query reformulation steps
- Abstain when evidence is absent
- Compare against fixed RAG
Aggregate sources across retrieval steps with full lineage, no repeated searches and drafts based only on permitted evidence.
- Track lineage for each source
- Skip repeated searches
- Merge and deduplicate evidence
- Draft only from permitted sources
Expose the assistant through an authenticated FastAPI endpoint with request IDs, source IDs, deadlines, cancellation and safe errors.
- Define request and response models
- Authenticate the caller
- Attach request IDs
- Enforce deadlines and cancellation
- Return user-safe errors
Module resources:Invicly: FastAPI with Python for AI Backends ↗ - 89h 30m3 topics
Review tools, routing and failure modes
Advanced. Single versus multi-agent trade-offs, trust-boundary tests, and fallbacks when models, tools or budgets fail.
Show topicsNot startedCompare one agent with one specialist handoff on the same cases and measure the latency and failures the handoff adds.
- Define handoff state
- Set stop conditions for each agent
- Run both designs on the same cases
- Measure added latency and failures
Write tests showing access restrictions and read-only tools hold when user text, retrieved passages and tool data contain conflicting instructions.
- Treat all model inputs as untrusted
- Plant benign conflicting instructions
- Test denied-request cases
- Confirm tools stay read-only
Handle invalid output, unavailable models, client disconnects, tool timeouts and budget exhaustion with a chosen fallback or escalation.
- Retry or reject invalid output
- Fail over when a model is unavailable
- Stop work on client disconnect
- Time out slow tools
- Choose fixed RAG fallback or escalation
Module resources:OWASP Top 10 for LLM applications ↗ - 911h3 topics
Measure answer and tool quality
Advanced. A versioned golden dataset, trajectory scoring for tool use, and regression baselines across all three versions.
Show topicsNot startedBuild a versioned fixture set of answerable, unanswerable, ambiguous, outdated and unauthorised requests with expected sources and outcomes.
- Cover each request category
- Record expected sources and outcomes
- Version the fixture set
- Keep fixtures synthetic
Score answer quality, citation support, allowed tool use, unnecessary calls, latency and cost while accepting equivalent valid trajectories.
- Record each run's trajectory
- Check allowed and unnecessary tool calls
- Score answer and citation support
- Accept multiple valid paths
- Report latency and token cost
Run model-only, fixed RAG and agentic RAG over identical cases and set rollout thresholds from deterministic checks and calibrated grading.
- Run all three versions on the same cases
- Apply deterministic checks first
- Calibrate model grading against people
- Set rollout thresholds
- 1010h 30m3 topics
Deploy, observe and maintain
Advanced. Tracing and cost tracking without sensitive content, safe index and model releases, and reproducible deployment with recovery drills.
Show topicsNot startedCorrelate retrieval, model and tool spans and track p50/p95 latency, abstention, failures and spend without logging sensitive content.
- Create spans for each step
- Track p50 and p95 latency
- Count abstentions and failure modes
- Track spend per request
- Redact sensitive content
Roll out compatible prompt, model and index revisions with versioned metadata, candidate traffic checks and defined rollback criteria.
- Version source and embedding metadata
- Build the new index beside the old one
- Send candidate traffic and compare
- Define rollback criteria
Run the API, database and fixture model reproducibly with Docker Compose and rehearse backup, restore and dependency-failure recovery.
- Run the stack with Docker Compose
- Document a hosted option
- Back up and restore PostgreSQL
- Drill invalid sources and unavailable dependencies
Module resources:Docker Compose ↗ - 1123h3 topics
Ship 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.
Show topicsNot startedWrite a design that fixes the corpus, caller scopes, model-only baseline, schemas, allowed tools, budgets and evaluation targets.
- Define 10–20 versioned documents in two scopes
- Diagram ingestion and querying separately
- Specify schemas, tools and budgets
- Write a 20-case fixture plan and targets
Implement fixed RAG and bounded agentic RAG behind an authenticated endpoint with verified citations, typed mock tools and a local fixture mode.
- Build ingestion and hybrid retrieval
- Add citation validation and abstention
- Implement the bounded agent with mock tools
- Serve an authenticated FastAPI endpoint
- Run everything in local fixture mode
Compare all three versions on the fixture suite with zero cross-scope disclosures and document evidence, limitations, cost and rollback.
- Run the 20-case suite on all three versions
- Show missing-source and denied-document behaviour
- Report recall, support, tools, latency and cost
- Publish a redacted trace and rollback checklist