Skip to content
Visual explainer 14h to learn 6 steps

Build a RAG assistant with tools (e.g. docs Q&A or support bot)

A deployed app with citations, at least one tool, an eval suite in CI and a README showing scores.

By Invicly Tech, , in AI Engineering with Python. About 14 minutes to read.

Topic 33 of 33

In short

The capstone is a deployed RAG assistant with citations, at least one tool, an eval suite in CI and documented scores. Build a thin version end to end first, then improve it in measured loops.

Explained simply

This is where you build the real thing: an assistant that answers questions from your documents, shows where each answer came from, can use at least one tool, and proves its quality with scores. It is the project you can show in an interview or a portfolio.

The most important rule is to build a thin slice first. That means the simplest version that works from start to finish: load a few documents, search them, ask the model, and print an answer with sources. It will not be great, but it gives you a baseline score.

Then you improve it in small, measured steps. Change one thing, run the eval set, and keep the change only if the scores get better. Better search, a reranker or a smarter prompt each earn their place with numbers, not with a good feeling.

Finally, you make the quality visible. The eval suite runs automatically on every change in CI (continuous integration, the server that tests your code), the app is deployed with a link people can try, and the README shows the scores of every version.

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

LayersThe assistant's architecture
  1. 1
    API

    FastAPI with auth, validation and streaming

  2. 2
    Orchestration

    Query rewrite, retrieval, tool calls, prompt

  3. 3
    Retrieval

    Hybrid search over chunked documents

  4. 4
    Storage

    Postgres with pgvector and metadata

  5. 5
    Quality

    Evals in CI, tracing and feedback

CycleEval, then improve
  1. 1
    Run evals

    Score the current version

  2. 2
    Inspect failures

    Retrieval miss or generation error?

  3. 3
    Change one thing

    Chunking, prompt, reranker or model

  4. 4
    Re-run and compare

    Keep it only if scores improve

  5. Back to step 1
MapDiagnosing a failed eval case
Case failed
  • Right doc not retrieved
    • Fix chunking or cleaning
    • Add keyword search (hybrid)
    • Try a larger k plus a reranker
  • Retrieved but answer wrong
    • Tighten the prompt rules
    • Put the best chunk first
    • Try a stronger model
  • Bad or missing citation
    • Number chunks clearly
    • Validate cited IDs in code
  • Should have refused
    • Add a score threshold
    • Add more refusal examples
  • Tool problem
    • Wrong tool or bad arguments
    • Improve tool description

In depth

The thin slice: end to end in a day

Resist building the perfect ingestion pipeline first. Start with 10 to 20 documents, split them by headings, embed them, store them, and write one function answer(question) that retrieves the top 5 chunks and asks the model for a cited answer. Call it from a small script that runs the whole eval set and writes a results file.

Now you have a baseline: maybe 60% correct and 70% cited. Every number after this is a comparison, and you can see where the failures are. Often the first surprise is that retrieval, not the model, causes most errors.

Only then wrap the function in a FastAPI endpoint, add the tool, and add the remaining documents. Because the eval script already exists, each step is checked right away instead of at the end.

FlowOrder of work for the capstone
  1. 1
    Thin slice

    Few docs, top-5 search, cited answer

  2. 2
    Baseline eval

    Score all 30 cases, save results

  3. 3
    Improve retrieval

    Chunking, hybrid search, reranker

  4. 4
    Add the tool

    One action users really need

  5. 5
    API and deploy

    FastAPI, Docker, secrets, logs

  6. 6
    CI and README

    Evals gate merges, scores published

Ingesting and indexing the documents

Ingestion turns raw files into searchable chunks. Parse each format into clean text (HTML, Markdown, PDF), and drop navigation menus and footers, which pollute search. Split by headings first, then by length, aiming for a few hundred tokens per chunk with a little overlap. Keep the heading in the chunk text so a chunk still makes sense on its own.

Store metadata with every chunk: document ID, title, URL, section heading and updated_at. Citations need it, and filters such as "only current policies" need it too. Also store a hash of each document's content. When you re-run ingestion, skip documents whose hash did not change, and delete all old chunks of a document before inserting its new ones. That keeps the job idempotent: running it twice gives the same index.

Embed queries with the same model you used for the chunks; vectors from different models are not comparable. In pgvector, an HNSW index keeps vector search fast as the table grows, and a generated tsvector column with a GIN index adds keyword search.

  • Same embedding model for chunks and queries, always
  • Delete old chunks of a changed doc before inserting new ones
  • Keep doc ID, URL, heading and updated_at on every chunk

Retrieval with citations you can verify

Pure vector search misses exact terms such as error codes, product names and version numbers. Hybrid search runs a vector query and a keyword query, then merges the two ranked lists. A simple, robust merge is reciprocal rank fusion (RRF): each chunk scores the sum of 1 / (k + rank) over the lists it appears in, with k = 60 as the usual constant. Optionally, a reranker model then reorders the top 20 or so and you keep the best 5.

In the prompt, number the chunks [1] to [5] and show each one's title and source. Instruct the model to cite numbers after each claim and to say it does not know when the chunks do not contain the answer. After generation, check in code that every cited number was actually sent. If none were cited, or the best retrieval score is below a threshold you tuned on the eval set, return a refusal instead of a guess.

Return the sources (title and URL) next to the answer so the user can click and check.

SequenceOne question through the assistant
User
API
Postgres
Model
  1. 1POST /chat with a question
    User to API: POST /chat with a question
  2. 2Vector and keyword search
    API to Postgres: Vector and keyword search
  3. 3Top chunks with IDs and URLs
    Postgres to API: Top chunks with IDs and URLs
  4. 4Rules plus numbered chunks [1] to [5]
    API to Model: Rules plus numbered chunks [1] to [5]
  5. 5Answer with [n] citations
    Model to API: Answer with [n] citations
  6. 6Checked answer plus source links
    API to User: Checked answer plus source links

Adding a tool the right way

Pick a tool that answers questions the documents cannot. For a support bot that might be get_order_status(order_id) or search_changelog(version). For a docs assistant it might be fetching the latest release notes. Start with read-only tools; a tool that changes data needs confirmation from the user and much stricter checks.

You describe the tool to the model with a name, a description and a JSON schema for its arguments. When the model decides to use it, it returns a tool call with JSON arguments instead of a final answer. Your code validates the arguments (Pydantic works well), runs the tool with a timeout, and sends the result back in the next message. The model then writes the answer, or asks for another tool call.

Put a hard limit on this loop, for example 3 tool rounds per question, so a confused model cannot loop forever and burn tokens. Log every call with its arguments and result. Add eval cases that check the right tool was called with the right arguments.

  • Validate tool arguments before running anything
  • Timeouts and a maximum number of tool rounds
  • Eval cases for tool choice and arguments, not just final text

Evals in CI and a README that proves it

Turn the eval script into a test that fails when scores drop below your success criteria, and run it in GitHub Actions on every pull request. Store the API key as a repository secret, never in the code. Note that secrets are not passed to workflows triggered by pull requests from forks, so outside contributors' runs will skip or fail the eval step.

Model outputs vary between runs. Use a low temperature where your provider supports it, set thresholds a little below your current score so one flaky case does not block every merge, and re-run a failing case before you trust it. If the full suite is slow or costly, run a fast subset on every pull request and the full set on main or nightly.

The README is your evidence: the problem statement, an architecture diagram, how to run it locally, a results table with one row per version (correct, cited, p95 latency, cost per question), a demo link and known limitations. Honest limitations make the project more credible, not less.

Learn it in 6 short steps

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

  1. 1
    Ingest and index the documents~2h 20m
  2. 2
    Build retrieval with citations~2h 20m
  3. 3
    Add at least one tool~2h 20m
  4. 4
    Run the eval suite in CI~2h 20m
  5. 5
    Deploy the app~2h 20m
  6. 6
    Document scores in the README~2h 20m

Key points

  • Get a basic pipeline answering questions end to end before optimising.
  • Change one variable at a time so you know what helped.
  • Make CI fail when scores drop below your success criteria.
  • Show eval scores, cost and latency in the README as evidence.

Key terms

Tap a card to flip it. 0/4 known

Examples

markdown
## Results (eval set v2, 30 cases)

| Version              | Correct | Cited | p95 latency | Cost/q  |
|----------------------|---------|-------|-------------|---------|
| Baseline vector RAG  | 63%     | 70%   | 4.1 s       | $0.006  |
| + hybrid search      | 77%     | 83%   | 4.3 s       | $0.006  |
| + reranker           | 87%     | 93%   | 5.2 s       | $0.008  |

README results showing each measured improvement.

The chunk table in Postgres with pgvector

Step 1: enable the extension. Step 2: create a table with the metadata citations need, a content hash for re-ingestion, and a vector column whose size matches your embedding model (384 for all-MiniLM-L6-v2). Step 3: add a generated tsvector column so Postgres keeps keyword search data in sync automatically. Step 4: add an HNSW index for cosine distance and a GIN index for keyword search. Queries then use embedding <=> query_vector for vector search and tsv @@ plainto_tsquery('english', question) for keywords.

sql
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE chunks (
  id           bigserial PRIMARY KEY,
  doc_id       text NOT NULL,
  url          text NOT NULL,
  heading      text,
  content      text NOT NULL,
  doc_hash     text NOT NULL,
  updated_at   timestamptz NOT NULL,
  embedding    vector(384) NOT NULL,
  tsv          tsvector GENERATED ALWAYS AS (to_tsvector('english', content)) STORED
);
CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops);
CREATE INDEX ON chunks USING gin (tsv);

Running the eval suite in GitHub Actions

Step 1: save this file as .github/workflows/evals.yml. Step 2: add LLM_API_KEY under the repository's Settings, Secrets and variables, Actions. Step 3: open a pull request; the job installs dependencies and runs the eval test, which asserts your thresholds (for example accuracy of at least 0.85). If retrieval needs a database, add a Postgres service container built from the pgvector/pgvector image and run ingestion on a small fixture set first. Step 4: in the branch protection rules, mark this job as required so a quality drop blocks the merge.

yaml
name: evals
on: [pull_request]
jobs:
  evals:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install -r requirements.txt
      - run: pytest -q tests/test_evals.py
        env:
          LLM_API_KEY: ${{ secrets.LLM_API_KEY }}

Quick reference

  • Build a thin slice end to end first, then record the baseline scores
  • Change one thing per eval run and log what changed
  • pgvector HNSW index: CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops)
  • RRF score = sum over lists of 1 / (60 + rank)
  • Check in code that every cited [n] was actually sent to the model
  • Cap the tool loop, for example 3 rounds per question
  • API keys go in repository secrets: ${{ secrets.LLM_API_KEY }} in the workflow
  • README: problem, architecture, how to run, results per version, limits, demo

Common mistakes

  • Adding agents and tools before basic retrieval works well.
  • Changing several things at once and not knowing which helped.

Quick quiz

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

Question 1

1Your app often answers "I don't know" even though the answer is in the docs. The logs show the right document is never in the top 5. What should you fix first?

Question 2

2Users search for error codes like E1042 and vector search misses them. Which change helps most directly?

Question 3

3Why put a maximum on the number of tool-call rounds per question?

Question 4

4A pull request from a fork fails the eval step with an authentication error. Why?

Question 5

5After re-running ingestion, search results show old and new versions of the same policy. What is missing?

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

    Write a function that turns a list of eval results (dicts with correct, cited and latency_ms) into one README table row: accuracy, cited rate and p95 latency.

  2. Exercise 2medium

    Write rrf(rankings, k=60, top=5) that merges several ranked lists of chunk IDs with reciprocal rank fusion and returns the best IDs.

  3. Exercise 3hard

    Write a pytest test that fails CI if accuracy is below 0.85, any must_refuse case was answered, or p95 latency is above 6 seconds. Assume run_evals() returns a list of result dicts.

Check yourself

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

Feel confident about this topic?

Frequently asked questions

Do I need an agent framework like LangChain for the capstone?
No. A RAG assistant with one tool is a few hundred lines of plain Python with your provider's SDK, FastAPI and Postgres. Writing it yourself makes it easier to debug and to explain in an interview.
How do I stop the assistant from making things up?
Answer only from retrieved chunks, require citations, check in code that cited IDs were actually sent, and refuse when retrieval finds nothing relevant. Then measure it with refusal and citation checks in your eval set.
Is it expensive to run evals on every pull request?
Usually not: 30 cases at around a cent each is well under a dollar per run. If the suite grows large, run a small subset on pull requests and the full suite nightly or on main.
What makes a capstone stand out to employers?
Evidence. A live demo, a results table that shows how each change moved the scores, honest limitations, and CI that blocks regressions show you can ship AI features responsibly.
ShareXLinkedInWhatsApp