Skip to content
Visual explainer 12h to learn 5 steps

Agentic RAG capstone: build fixed RAG and the bounded agent

Implement fixed RAG and bounded agentic RAG behind an authenticated endpoint with verified citations, typed mock tools and a local fixture mode.

By Invicly Tech, , in Generative AI, Agentic AI and RAG. About 14 minutes to read.

Topic 33 of 34

In short

The 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.

Think of it like this: Fixture mode is a flight simulator: the same cockpit and controls as the real plane, but every reply from outside is scripted so a test can be repeated exactly.

Explained simply

Building the capstone means turning the design into a small working service. There are four parts: a job that loads documents into the database, a search function, the assistant logic in three modes and a web endpoint. You can build and test all of it on a laptop with Docker, without paying for a model.

The ingestion job reads each document, checks its front matter, splits it into sections and stores each section with its text, a vector and a full-text search column. A vector is a list of numbers that captures meaning. The job records which embedding model made each vector and marks older versions as no longer current.

Search runs two ways at once. Keyword search finds exact words such as policy codes, and vector search finds passages with similar meaning. The two ranked lists are merged into one. Before anything is ranked, the query keeps only rows the caller may see and only current versions.

Fixed RAG searches once and asks the model to answer from those results. The agent may route, search again with a better query or look up a ticket, but only within its budget. In both modes, code checks that every cited source was really retrieved for this caller. If not, the assistant abstains.

Fixture mode replaces the model and tools with fakes that give the same scripted replies every time. That makes tests repeatable and free, while the database, login check and validation code stay real.

Press Play on a diagram to walk through it one step at a time.

SequenceOne agent request in fixture mode
Client
API
Agent loop
Tools and database
  1. 1POST /ask with bearer token
    Client to API: POST /ask with bearer token
  2. 2Question, trusted scope, budgets
    API to Agent loop: Question, trusted scope, budgets
  3. 3search_docs(query), scope added by server
    Agent loop to Tools and database: search_docs(query), scope added by server
  4. 4Hits with section IDs
    Tools and database to Agent loop: Hits with section IDs
  5. 5get_section(section_id)
    Agent loop to Tools and database: get_section(section_id)
  6. 6Section text
    Tools and database to Agent loop: Section text
  7. 7Draft with citations
    Agent loop to API: Draft with citations
  8. 8Validated answer or abstention, request ID
    API to Client: Validated answer or abstention, request ID
LayersWhat is real and what is faked in fixture mode
  1. 1
    FastAPI app and auth

    Real: same code as any other run

  2. 2
    Assistant logic

    Real: model-only, fixed RAG and agent loop

  3. 3
    Model client

    Fake: scripted JSON replies per fixture case

  4. 4
    Embeddings

    Precomputed vectors or a small local model

  5. 5
    PostgreSQL with pgvector

    Real, started with Docker Compose

  6. 6
    Mock tools

    Typed, scripted results, latency and faults

MapNon-answer outcomes and their reasons
Run ends without an answer
  • abstained
    • no_permitted_evidence
    • citation_not_in_permitted_evidence
    • invalid_model_output
    • budget_exhausted
  • escalated
    • tool_timeout
    • deadline_exceeded
  • clarify
    • ambiguous_question

In depth

Ingestion: parse, chunk, embed, publish

Prerequisites: Python 3.12, Docker with the Compose plugin and the corpus folder. Start the database with docker compose up -d db using a pgvector image such as pgvector/pgvector:pg17, then run CREATE EXTENSION IF NOT EXISTS vector.

The sections table holds section_id, version, doc_id, scope, is_current, heading, body, an embedding vector(384), the embedding model name and a generated tsvector column. The job parses front matter and writes rejects to an ingest_errors table, splits on level-two headings, and computes embeddings, loading precomputed vectors from a fixtures file in fixture mode. It upserts on (section_id, version) so reruns are idempotent, then sets is_current to false for superseded versions in the same transaction.

Expected evidence: counts by scope and is_current match the corpus manifest. Rollback: the run is one transaction, so a failure leaves the previous index untouched.

  • Upsert key: (section_id, version)
  • Record embed_model with every vector
  • Supersede old versions in the same transaction
  • Failed parses go to ingest_errors, not the index

Hybrid retrieval with the filter inside the query

Run both searches in one SQL statement. The keyword branch ranks rows with ts_rank_cd against websearch_to_tsquery. The vector branch ranks rows by cosine distance using the pgvector operator <=>, where smaller means closer. Both branches apply WHERE scope = ANY(the caller's scopes) AND is_current, so denied and stale rows are never candidates.

Merge with reciprocal rank fusion: each row scores the sum of 1 / (60 + rank) over the lists it appears in, and the top 5 rows become evidence. The constant 60 is a common default, not a law.

With only a few hundred rows, an exact scan is fast and needs no vector index. If you add an HNSW index later, remember that filters apply after the approximate index scan, so a selective filter can return fewer rows than you asked for. Recent pgvector releases add iterative index scans to help; recheck recall whenever you change the index.

  • Filter by scope and is_current in both branches
  • Fuse by rank, not by raw scores
  • Exact scan is fine at capstone size
  • Recheck recall after adding an approximate index

Citation validation and abstention

The model returns JSON with status, answer and citations. Parse it with Pydantic; on invalid output retry once, then abstain with invalid_model_output. Next, check that every citation is in the evidence retrieved for this caller in this request, which also rules out superseded versions because they were never retrieved. An answered status needs at least one valid citation.

Add a cheap deterministic support check: numbers and dates in the answer must appear in the cited text. It catches many invented figures without a second model call.

Keep reasons from a fixed list so tests can assert on them. Missing evidence and denied evidence share no_permitted_evidence, so a general caller cannot learn that a finance document exists.

  • no_permitted_evidence: nothing usable was retrieved
  • citation_not_in_permitted_evidence: a cited ID failed the check
  • invalid_model_output: JSON failed twice
  • budget_exhausted and tool_timeout come from the agent loop

The bounded agent loop with typed mock tools

Each turn, the model proposes one typed action: search_docs, get_section, get_ticket_status, answer, clarify or abstain. Code, not the model, enforces the rules. It checks the action against the run's allowlist, validates arguments with the tool's Pydantic model, checks the budgets, runs the tool inside asyncio.timeout (Python 3.11 and later), and records the result with lineage: which call produced which section.

Identical repeated searches are skipped and noted. Reformulations count against their own limit. The mock ticket tool reads scripted statuses from a fixtures file and, for the two timeout cases, sleeps past its 2 second limit so the timeout path is exercised for real.

CycleOne agent turn with checks
  1. 1
    Propose action

    Model returns one typed action

  2. 2
    Validate

    Allowlist, argument model, budgets

  3. 3
    Run with timeout

    Tool gets the server's caller, not the model's

  4. 4
    Record evidence

    Section IDs with lineage, repeats skipped

  5. 5
    Continue or finish

    Finish validates citations and sets a status

  6. Back to step 1

Authenticated endpoint and fixture mode

POST /ask accepts AskRequest and depends on get_caller, which verifies a bearer token and returns a Caller with user ID and scopes. In fixture mode, tokens are signed with a development-only secret or looked up in a static test file; never reuse that secret anywhere real. A request ID comes from the X-Request-ID header or is generated, and is returned in the body and logs. The whole request runs inside an 8 second asyncio.timeout.

Set APP_MODE=fixture to make the lifespan handler build the fake model and scripted tools. Steps: docker compose up -d db, run the ingest module, start the API with fastapi dev or uvicorn. Expected evidence: a request without a token gets 401, a general token returns an answer citing POL sections, and a finance question from a general token abstains. Cleanup: docker compose down -v removes the database volume.

Learn it in 5 short steps

About 2h 25m each. Track them with a timer in your plan.

  1. 1
    Build ingestion and hybrid retrieval~2h 25m
  2. 2
    Add citation validation and abstention~2h 25m
  3. 3
    Implement the bounded agent with mock tools~2h 25m
  4. 4
    Serve an authenticated FastAPI endpoint~2h 25m
  5. 5
    Run everything in local fixture mode~2h 25m

Key points

  • Hybrid retrieval combines full-text search and vector similarity, with the scope and current-version filter inside the SQL.
  • Citations are checked in code: every cited section ID must be in the evidence retrieved for this caller in this request.
  • The agent loop counts tool calls, tokens and time, and every exit returns a typed status.
  • Authentication sets the scope. Neither the model nor the request body can change it.
  • Fixture mode swaps the model and outside tools for deterministic fakes so tests repeat exactly.

Key terms

Tap a card to flip it. 0/6 known

Examples

python
from dataclasses import dataclass

@dataclass
class Draft:
    answer: str
    citations: list[str]

def check_citations(draft: Draft, evidence: dict[str, str]) -> tuple[str, str | None]:
    """evidence maps section_id to text retrieved for this caller in this request."""
    if not draft.citations:
        return "abstained", "no_citations"
    if set(draft.citations) - evidence.keys():
        return "abstained", "citation_not_in_permitted_evidence"
    return "answered", None

Citations must come from this request's permitted evidence

Hybrid search SQL with the scope filter in both branches

Two ranked lists are built inside the database, each already limited to the caller's scopes and current versions, then fused by reciprocal rank. Parameters are passed by psycopg, with the pgvector Python package registered so the query vector is sent as a vector. Expected evidence: for a general caller, no returned section_id starts with FIN.

sql
WITH kw AS (
  SELECT section_id, row_number() OVER (ORDER BY ts_rank_cd(tsv, q) DESC) AS r
  FROM sections, websearch_to_tsquery('english', %(q)s) AS q
  WHERE tsv @@ q AND scope = ANY(%(scopes)s) AND is_current
  ORDER BY r LIMIT 20),
vec AS (
  SELECT section_id, row_number() OVER (ORDER BY embedding <=> %(qvec)s) AS r
  FROM sections
  WHERE scope = ANY(%(scopes)s) AND is_current
  ORDER BY r LIMIT 20)
SELECT section_id, sum(1.0 / (60 + r)) AS rrf
FROM (SELECT * FROM kw UNION ALL SELECT * FROM vec) AS fused
GROUP BY section_id ORDER BY rrf DESC LIMIT 5;

Running one tool call inside the budgets

This helper runs one proposed action. It refuses tools outside the allowlist, stops at the call budget, skips identical repeats, and turns a timeout into an escalation. Every exit is a typed status, so the loop can never end with an unchecked answer. Evidence goes into state with the number of the call that produced it, which is the lineage the trace will show.

python
async def run_tool(state, action, tools, caller):
    if action.name not in state.allowed_tools:
        return state.finish("abstained", "tool_not_allowed")
    if state.tool_calls >= state.max_tool_calls:
        return state.finish("abstained", "budget_exhausted")
    key = (action.name, action.args.model_dump_json())
    if key in state.seen: return state.note("skipped_repeat")
    state.seen.add(key)
    state.tool_calls += 1
    try:
        async with asyncio.timeout(tools[action.name].timeout_s):
            hits = await tools[action.name].run(action.args, caller=caller)
    except TimeoutError:
        return state.finish("escalated", "tool_timeout")
    state.add_evidence(hits, produced_by=state.tool_calls)

Quick reference

  • Start: docker compose up -d db, enable the vector extension, run ingestion, then start the API.
  • Put scope = ANY(scopes) AND is_current in every retrieval branch, keyword and vector alike.
  • RRF score: the sum of 1 / (60 + rank) across the keyword and vector lists.
  • pgvector cosine distance operator: <=>. Smaller means closer.
  • Answered needs at least one citation, and every citation must be in this request's permitted evidence.
  • Denied and missing evidence share one reason, no_permitted_evidence, so hidden documents stay hidden.
  • asyncio.timeout (Python 3.11+) wraps each tool call and the whole request deadline.
  • APP_MODE=fixture swaps in the fake model and scripted tools; database, auth and validation stay real.

Common mistakes

  • Filtering by scope in Python after retrieval, so top-k fills with denied rows and a single missed check leaks text. Filter in the SQL WHERE clause.
  • Trusting the citation IDs the model writes without checking them against the retrieved set.
  • A fixture mode that skips the database or authentication, so tests pass on code paths that real runs never use.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Why does the vector branch apply the scope filter rather than filtering the final 5 rows?

Question 2

2The model cites POL-003#1@v1, a superseded section that was not in this request's evidence. What happens?

Question 3

3What does reciprocal rank fusion combine?

Question 4

4In fixture mode, which part should remain real?

Question 5

5The agent proposes the same search_docs query twice. What should the loop do?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Start the database, enable pgvector and create the sections table with a generated full-text column.

  2. Exercise 2medium

    Write a pytest test proving a general caller never receives a finance section from hybrid_search, even for queries copied from finance text.

  3. Exercise 3hard

    Add POST /ask: authenticate with a bearer token, use or create a request ID, enforce an 8 second deadline and return escalated with deadline_exceeded on timeout.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do I need an embedding API for the build?
No. Fixture mode can load precomputed vectors from a file, or you can run a small open embedding model locally. Store the model name with each vector so a later switch forces a re-embed.
Should I use a framework such as Google ADK or LangChain?
Build the loop in plain Python first so every decision is visible and testable. Afterwards you can map each piece to a framework; the Google ADK path on Invicly is a natural next step.
Why not let the model pass the scope as a tool argument?
Anything the model writes can be steered by text in a question or a retrieved passage. The server injects the verified scope into every tool call instead.
Do I need an HNSW index for 20 documents?
No. An exact scan over a few hundred rows is fast and returns exact results. Add an index when the corpus grows and recheck recall, because approximate search with filters can return fewer rows.

Go deeper

ShareXLinkedInWhatsApp