# A RAG build log: the search finds every answer, the assistant doesn't always use it

> I built an assistant that answers questions about Cmssy from its docs. The search finds the source for every question. The assistant got 85 of 87 direct answers right and 13 of 24 on questions asked the way a client talks. The whole build, stage by stage, with the code and the numbers.

- URL: https://www.maciejbednarczyk.com/en/blog/cmssy-docs-assistant-build-log
- Author: Maciej Bednarczyk
- Language: en
- Published: 2026-11-23

I built an assistant that answers questions about Cmssy using its documentation. This kind of system is called **RAG**: before the model answers, it looks up the passages of the docs that match the question, and answers from those passages only.

**The short version:** the search works, and that turned out not to be the hard part. It finds the answering passage for all 37 questions the docs can answer. The assistant built on top of it got 85 of 87 answers right on questions asked in the docs' own words, and 13 of 24 on questions asked the way a client talks. Most of those misses were not the search's fault. The assistant never searched. That measurement is the afterword at the end, and it is the part I would read first.

The rest is a build log. I updated it after every stage: what I did, why I did it that way, and what the numbers say.

## Where I am

**All 9 stages are done.** The assistant is in production. It answers questions about Cmssy inside the admin's AI assistant, from 61 pages of docs that are re-indexed every hour. Two stages ended differently than planned, and I left that in. After the write-up I measured the assistant itself instead of the search, and added the result as an afterword.

<table><caption>Stages of the build</caption><thead><tr><th>Stage</th><th>Status</th></tr></thead><tbody><tr><td>1. Test set</td><td>Done</td></tr><tr><td>2. Project skeleton</td><td>Done</td></tr><tr><td>3. Splitting the docs into chunks</td><td>Done</td></tr><tr><td>4. Search index</td><td>Done</td></tr><tr><td>5. First measurement</td><td>Done</td></tr><tr><td>6. Generating answers</td><td>Built, measured, then removed</td></tr><tr><td>7. Agent with Cmssy tools</td><td>Done differently: search became a tool of the existing assistant</td></tr><tr><td>8. Production</td><td>Done</td></tr><tr><td>9. Write-up</td><td>Done</td></tr></tbody></table>

## Stage 1: the exam comes before the code

The natural first move is to start coding. I did the opposite. Before I build anything, I want to know how I'll tell that it works.

So I started with an exam: 42 questions an agency might ask about Cmssy, each with the passage of the docs that answers it. After every change to the assistant, I run the same exam and get a score, instead of judging by eye. In AI projects this is called an **eval set**.

I didn't write the questions by hand. Claude went through the Cmssy docs and code and drafted them, each with its answering passage. Over 21 pages of docs, that took an AI minutes and would have taken me days. My part was deciding what the exam should test. A script then checks that every passage really is in the docs.

### What's in the exam

<table><caption>The 42 questions by kind</caption><thead><tr><th>Kind</th><th>Count</th><th>Why it's there</th></tr></thead><tbody><tr><td>Direct</td><td>29</td><td>Asked in the docs' own words. The baseline.</td></tr><tr><td>Colloquial</td><td>8</td><td>Asked the way a client talks. Only 7% of their words appear in the section of the docs that answers them, against 39% for direct ones. Search has a harder time here.</td></tr><tr><td>"I don't know"</td><td>5</td><td>The docs don't answer them. The assistant has to say so instead of making something up.</td></tr><tr><td>Two sources (among direct)</td><td>2</td><td>The answer needs two places in the docs at once.</td></tr></tbody></table>

The colloquial questions matter most. Below are two needs, each asked twice. Pick a question and see which of its words the answering passage contains.

-   **In the docs' words:** Czy usunięty przez pomyłkę workspace da się przywrócić? (1 of 4 words also in the answer)
-   **The way a client asks:** Klient skasował nam cały projekt. Da się to jeszcze jakoś odkręcić? (0 of 4 words also in the answer)
-   **The answer in the docs:** Usunięcie jest natychmiastowe i nieodwracalne - brak okresu karencji, brak soft delete, brak cofnięcia.

-   **In the docs' words:** Czy dodanie języka wymaga deployu? (4 of 4 words also in the answer)
-   **The way a client asks:** Klient wchodzi na rynek niemiecki. Musimy coś przerabiać w aplikacji, czy wystarczy, że ktoś przełoży teksty? (1 of 10 words also in the answer)
-   **The answer in the docs:** Dodanie języka to ustawienie workspace'u. Twoja aplikacja podchwyci je przy następnym żądaniu, co oznacza, że nowe locale nie wymaga deployu - tylko tłumaczeń.

A person sees one question. A search engine sees two different sets of words, and the colloquial one barely overlaps with the docs. If the assistant only handles the first kind, it fails real users.

### Two decisions that are easy to miss

-   **A frozen copy of the docs.** The docs changed on the very day the exam was made. If I tested against the live site, a docs edit would look like the assistant getting worse. So I test against a frozen copy: first 21 pages from 14 November 2026, later all 60 pages of the English docs from 18 November.
-   **A clear rule for a hit.** Search counts as a hit when a returned passage contains the answering sentence. A two-source question counts only when both places come back.

## Stages 2 and 3: a skeleton and a rule for cutting the docs

The skeleton is a small Python service: FastAPI, MongoDB Atlas for storage, Voyage for embeddings, strict type checking and tests from the first commit. Nothing interesting, and that is the point.

The first real decision is how to cut the docs into fragments, called **chunks**. Search returns chunks, not pages, so a bad cut loses the answer before any model sees it. My rules:

-   A chunk never crosses a section heading.
-   A chunk never cuts a line. Lines come from the structure of the page: a paragraph, a list item, a table row.
-   At most 1000 characters, with one line shared between neighbours.
-   Every chunk remembers its page and section, and that context is embedded together with the text. A short chunk like "Yes, up to 20 a month" still knows what it is about.

The whole packing rule is one function:

```python
def _pack(lines: list[str], max_chars: int, overlap_lines: int) -> list[list[str]]:
    """Group lines into windows of at most max_chars; a longer line becomes a window alone."""
    windows: list[list[str]] = []
    current: list[str] = []
    for line in lines:
        if current and len("\n".join([*current, line])) > max_chars:
            windows.append(current)
            current = current[-overlap_lines:] if overlap_lines else []
            if current and len("\n".join([*current, line])) > max_chars:
                current = []
        current.append(line)
    if current:
        windows.append(current)
    return windows


# on Chunk: what actually gets embedded
def embedding_text(self) -> str:
    """Text to embed: the chunk with its place in the docs, so short chunks keep context."""
    if self.section == self.page_title:
        return f"{self.page_title}\n{self.text}"
    return f"{self.page_title} > {self.section}\n{self.text}"
```

## Stages 4 and 5: the index and the first measurement

Before trusting embeddings I built the simplest thing that could work: **BM25**, classic keyword search, about 60 lines of Python. It is the baseline. If vectors don't beat it, they are not worth their bill.

Then embeddings. Every chunk becomes a vector (Voyage `voyage-4`), the question becomes a vector, and the nearest chunks win. I ran an exact search in memory first, then put the same vectors into MongoDB Atlas Vector Search and checked that Atlas returns the same results as the exact version. It does.

The grading rule fits in a few lines. A question counts only when every one of its sources is in the top `k` results:

```python
def source_hit_by(source: Source, chunk: Chunk) -> bool:
    if ELLIPSIS in source.fragment:
        return chunk.slug == source.slug and normalize(chunk.section) == normalize(source.section)
    return normalize(source.fragment) in normalize(chunk.text)


def hit_at_k(question: Question, ranked: Sequence[Chunk], k: int) -> bool:
    top = ranked[:k]
    return bool(question.sources) and all(
        any(source_hit_by(s, c) for c in top) for s in question.sources
    )
```

And this is the exam running. Each row is one way of searching. `hit@5` means the answering passage was in the first 5 results; `d` and `c` split the score into direct and colloquial questions.

![The eval runner scoring five search methods on the 37 answerable questions](https://assets.cmssy.io/6ae4795c65113d877fc8d877/ed875fe3-0771-47fd-baf7-37badd56083d-rag-eval-terminal-v2.gif)

![Questions that found their passage in the top 10, by search method](https://assets.cmssy.io/6ae4795c65113d877fc8d877/38230e18-0fa0-4115-89e0-763e348d3a4a-rag-eval-chart-en.png)

<table><caption>37 answerable questions, English docs snapshot of 18 November 2026</caption><thead><tr><th>Method</th><th>Rank 1</th><th>Top 5</th><th>Top 10</th><th>Colloquial in top 10 (of 8)</th></tr></thead><tbody><tr><td>BM25 (keywords)</td><td>5</td><td>13</td><td>15</td><td>1</td></tr><tr><td>BM25, 6-letter prefixes</td><td>4</td><td>15</td><td>17</td><td>1</td></tr><tr><td>Hybrid (rank fusion)</td><td>10</td><td>20</td><td>25</td><td>4</td></tr><tr><td>Vectors (voyage-4)</td><td>15</td><td>30</td><td>34</td><td>7</td></tr><tr><td>Vectors + rerank</td><td>21</td><td>36</td><td>37</td><td>8</td></tr><tr><td>Vectors + BM25 pool + rerank</td><td>21</td><td>36</td><td>37</td><td>8</td></tr></tbody></table>

### What the numbers say

-   **Keyword search finds 17 of 37, and 1 of the 8 colloquial questions.** A client who says "wiped out our whole project" shares no words with a page titled "Deleting a workspace".
-   **Vectors find 34 of 37, and 7 of the 8 colloquial ones.** This is the jump embeddings are paid for.
-   **Hybrid lost.** Merging the keyword and vector rankings (reciprocal rank fusion) is the textbook recommendation. On these docs it scored 25, worse than vectors alone: the weak keyword ranking dragged good vector hits down. Without the exam I would have shipped hybrid, because that is what everyone does.

### The second stage: rerank

Vector search is good at getting the answer into the top 10 and poor at putting it first: 15 of 37 at rank 1. A **reranker** fixes that. It is a slower model that reads the question together with each candidate and scores the pair. Too slow for 700 chunks, fine for 60.

```python
class RerankingRetriever:
    """Takes `candidates` chunks from the first-stage retriever and lets the reranker pick
    the best k. Recall comes from the first stage, precision from the reranker."""

    def search(self, query: str, k: int) -> list[Chunk]:
        pool = self._base.search(query, max(k, self._candidates))
        order = self._reranker.rerank(query, [c.embedding_text() for c in pool], min(k, len(pool)))
        return [pool[i] for i in order if 0 <= i < len(pool)][:k]
```

With rerank: 37 of 37 in the top 10, 36 in the top 5, 21 at rank 1.

One trap. A reranker can only promote what it is given. In an earlier version of the exam two questions kept failing because their passage sat at rank 60 and 52 in the vector results, outside the candidates, while keyword search had them at 3 and 6. Fusion did not help, so I stopped merging *rankings* and started merging *candidates*: the vector top 60 plus the keyword top 25, duplicates removed, and the reranker decides the order. Keyword search turned out useless as a ranker and useful as a safety net.

On today's exam the vector-only candidates score the same, so the keyword leg shows no gain in the table. I keep it because it runs in memory with no API call, and it was the only thing that found those two passages.

The pool size changed three times: 20 + 10 at the start, 30 + 15 when the corpus grew from 21 pages to 60, and 60 + 25 when the docs switched to English. Each change came from a failing exam question, not from a guess.

![The search pipeline: vector and keyword candidates go into one pool, a reranker picks the top 10, and Spotlight writes the answer](https://assets.cmssy.io/6ae4795c65113d877fc8d877/2759254e-7ba8-44ab-9b69-5eb6deedc53d-rag-pipeline-en.png)

## Stages 6 and 7: I built the answering part, then deleted it

The plan said: generate answers, then build an agent. So I built `/ask`: search, then Claude writes an answer and cites the fragments it used. I also built a second exam for the answers, graded by another model (correct, complete, grounded), with a self-test that feeds the judge deliberately wrong answers to check that it catches them.

It worked. Then I looked at where a user would actually ask. Cmssy already has an assistant in the admin, Spotlight, with its own model, conversation and tools. A second assistant next to it would be a worse copy. So the docs assistant shrank to one endpoint: a question goes in, up to ten fragments come out, no generated text. Two days after writing `/ask` I removed it, together with the judge and the model dependency.

The request:

```bash
curl -X POST "$DOCS_SEARCH_URL/search" \
  -H "Authorization: Bearer $DOCS_SEARCH_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"question": "Can a deleted workspace be restored?", "top_k": 5}'
```

```json
{
  "fragments": [
    {
      "slug": "/docs/editor/workspaces",
      "page_title": "Workspaces",
      "section": "Deleting a workspace",
      "url": "https://cmssy.com/docs/editor/workspaces",
      "text": "Deletion is immediate and permanent - there is no grace period, no soft delete, no undo. ..."
    }
  ]
}
```

On the Cmssy side, Spotlight gets it as a tool named `search_docs`. Abridged, without the error handling:

```typescript
tool({
  description:
    "Search the official cmssy documentation for how cmssy works: features, setup, the SDK, the API, webhooks, caching, roles. Returns fragments with the url of the docs page each comes from. Not for this workspace's own pages or records.",
  inputSchema: z.object({
    question: z
      .string()
      .trim()
      .min(3)
      .max(1000)
      .describe("The question about cmssy, in the user's words"),
    top_k: z.number().int().min(1).max(20).optional(),
  }),
  execute: async ({ question, top_k }) => {
    const response = await fetch(searchEndpoint(config.url), {
      method: "POST",
      headers: {
        authorization: `Bearer ${config.apiKey}`,
        "content-type": "application/json",
      },
      body: JSON.stringify({ question, top_k }),
      signal: AbortSignal.timeout(DOCS_SEARCH_TIMEOUT_MS),
    });
    if (!response.ok) return { error: statusError(response) };
    const body = await response.json();
    return {
      fragments: body.fragments
        .map(toFragment)
        .filter(Boolean)
        .slice(0, DOCS_FRAGMENTS_MAX),
    };
  },
});
```

Search never says "I don't know". For the five questions the docs don't answer it still returns fragments, just unrelated ones. Refusing is the job of the model that writes the answer, so the tool ships with a rule in Spotlight's instructions: every claim about how Cmssy works must come from a returned fragment, and when nothing relevant comes back, say that the docs don't cover it. I asked all five on production, and all five got "the docs don't say".

Here is the colloquial question from the exam, asked in the admin. Spotlight checks the trash of the workspace it is in, searches the docs, and links the docs pages it used:

![Spotlight answers "A client wiped out our whole project. Is there any way to get it back?" from the docs](https://assets.cmssy.io/6ae4795c65113d877fc8d877/bfec4897-0eab-4852-ad33-0c0d26482b02-rag-spotlight-search-docs-v2.gif)

## Stage 8: production

The service runs as a single FastAPI function. The interesting part is keeping the index fresh without breaking search while it updates.

-   **Generations.** A re-index writes a new set of chunks next to the live one and switches to it with one atomic update. Search never sees a half-written index, and nothing is redeployed.
-   **Hourly re-index.** A scheduled job rebuilds the corpus from the published docs pages. No change, no work. A small edit embeds only the chunks it touched; the rest come from a cache.
-   **The exam alarms, a gate blocks.** The frozen exam cannot see a page written yesterday, so a score below 37 of 37 opens an issue but does not stop the update. What does stop it is a structural check: no page lost its text, the chunk count is within 30% of the live index, and every changed page is found by its own title.
-   **An unknown block type fails the build.** If the docs get a new kind of content block, the corpus build stops instead of silently dropping its text.
-   **Busy is not broken.** When the embedding provider is saturated, the service answers 503 with `Retry-After`, and Spotlight tells the user the docs search is busy instead of retrying in a loop.

![The hourly re-index: build, candidate index, exam, gate, switch, commit and smoke test](https://assets.cmssy.io/6ae4795c65113d877fc8d877/05d5ad53-5d57-432f-a072-a2364428f322-rag-reindex-en.png)

The switch itself is one database update. The old generation is kept for one more sync, so a search that started a moment earlier still finds its chunks:

```python
def activate(db: Database[Document], info: SyncInfo) -> str | None:
    before = db[SYNCS].find_one_and_update(
        {"_id": info.snapshot},
        # One $set stage: "$generation" still reads the old value while it is replaced.
        # synced_at is the server's clock, so /health shows when the live index last changed.
        [{"$set": {"retired": "$generation", **asdict(info), "synced_at": "$$NOW"}}],
        upsert=True,
        return_document=ReturnDocument.BEFORE,
    )
    doomed = generation_to_delete(before, info.generation)
    if doomed:
        db[COLLECTION].delete_many({"snapshot": info.snapshot, "generation": doomed})
    return doomed
```

As I write this, the live index holds 61 docs pages in 760 chunks, last rebuilt a few hours ago by the scheduled job.

## Stage 9: what I would keep

-   **The exam first.** Every decision above was a number, and two of them went against what I expected: hybrid lost, and keyword search earned its place anyway, as a source of candidates.
-   **Score the hard questions separately.** The split into direct and colloquial showed exactly where keyword search fails: 1 of 8.
-   **Search as a tool, not a product.** The most useful version had less in it: no chat, no answering model, one endpoint behind an assistant that already existed.
-   **Delete what you built.** `/ask` taught me how to grade answers. It did not need to stay.

What the exam does not prove: 42 questions is a small set, a model drafted them from the same docs it is tested on, and 37 of 37 means the exam is now too easy to show the next improvement. It needs harder questions, ideally taken from what people actually ask.

## Afterword: measuring the assistant, not the search

The exam above grades the search. Nobody talks to the search. People talk to Spotlight, which decides whether to search at all, rewrites the question, reads ten fragments and writes an answer. So after the write-up I ran the same 42 questions through Spotlight itself, on production, in a test workspace, three times each: 126 conversations.

For every conversation I recorded which tools it called, which fragments came back and what it answered. Then a model graded each answer against the reference fragment from the exam. That is the judge I deleted together with `/ask`. It came back, this time outside the service, as a script that runs after the fact. Before trusting it I fed it a deliberately invented answer to check that it fails it.

<table><caption>Spotlight on production: 42 questions, three runs each</caption><thead><tr><th>Measure</th><th>Result</th></tr></thead><tbody><tr><td>Searched the docs</td><td>117 of 126</td></tr><tr><td>Linked a docs page</td><td>114 of 126</td></tr><tr><td>Correct answer, questions the docs answer</td><td>98 of 111</td></tr><tr><td>Correct, direct questions</td><td>85 of 87</td></tr><tr><td>Correct, colloquial questions</td><td>13 of 24</td></tr><tr><td>Said "the docs don't cover it", questions the docs don't answer</td><td>15 of 15</td></tr><tr><td>Stopped there, without offering a nearby feature</td><td>5 of 15</td></tr><tr><td>Every product claim backed by a retrieved section</td><td>113 of 117</td></tr><tr><td>Median time to a full answer</td><td>5 s</td></tr></tbody></table>

### What this showed that the exam could not

-   **The gap moved from search to routing.** Search finds the source for all 37 questions. The assistant still misses half of the colloquial ones, and mostly not because of search: in 9 conversations it never searched. Asked about a client who "wiped out our whole project", it checks the trash of the workspace it is in. Asked about a logo that will not change, it inspects the header block. Asked how big a video can be, it reads this workspace's plan and gives one number instead of the limits per plan.
-   **That is partly the exam's fault.** The questions were written from an agency's point of view, about Cmssy in general. Spotlight sits inside one workspace, so looking at that workspace first is often the right move. An exam for the assistant needs its own questions.
-   **Refusals hold, and they are padded.** All 15 said the docs do not cover the topic and none invented a guarantee. Ten then added a neighbouring feature: the status page for the SLA question, the GraphQL API for a WordPress migration.
-   **Rank 1 was the wrong thing to chase.** I set out to fix the docs behind the 16 questions whose source is not ranked first. In 10 of them the fragment on top states the same fact from another page, and the exam accepts only one source. Spotlight also rewrites the question before it searches, so the ranking the exam measures is not the ranking a user gets. I changed nothing in the docs.
-   **Four answers said more than their sources.** Small things, such as naming a "Team" screen no fragment mentions. This is the number I would watch.

### Where the results live

The three runs are loaded as experiments into Phoenix, an open-source tool for LLM evaluation, running on my own machine. It gives a table per question with every score next to the answer, and a way to compare runs. I did not connect it to production. The docs tool deliberately never logs the question a user asked, and tracing would undo that.

What this does not prove: I have not read all 126 verdicts myself, the grounding check compares an answer with whole docs sections instead of the exact fragments returned, so it is lenient, and three runs is enough to see a pattern, not a rate.