Back to list

Compile knowledge, don't retrieve fragments

Jim Lin
AGITech

Lately I've been building a customer support knowledge base for a smart hardware product. It covers 200-plus documents: product specs, FAQs, a plant encyclopedia, user blog posts. The first version used Agentic RAG: give the AI entry points into several heterogeneous data sources, and let it decide for each question which source to hit and what to pull. After a few rounds of testing, recall came in below what I expected. A slightly complex user question can span several kinds of documents. The LLM has to understand product parameters, growing experience and troubleshooting all at once, but RAG only fishes back a handful of relevant fragments each time, and they don't add up to a complete answer. Recall is a problem. Reranking is a problem too.

At bottom, the model isn't too dumb. It's starting from zero every time, piecing its understanding together out of scattered fragments of knowledge. Recall done this way is often unstable. When recall goes badly, the answer is wildly off, and the model may simply make things up.

Then I came across Karpathy's LLM Wiki. I didn't pay much attention at first, but when I went back to it a few days later, something clicked. This seemed like the way it should have been done all along. The ocean of human knowledge was built the same way: "compiled" generation after generation, by growing and pruning a tree of knowledge, not by mindlessly stacking up unconnected fragments.

Incrementally compiling a wiki

In early April, Karpathy posted a Gist on GitHub with a plain title: LLM Wiki. Controversy aside, his core insight is very clear:

The problem with RAG isn't inaccurate retrieval, it's that knowledge doesn't accumulate. Every query rediscovers things from scratch, and nothing gets "built".

His alternative: have the LLM incrementally build and maintain a persistent wiki. Instead of piecing things together at query time, the knowledge is integrated when new source material is ingested: update the entity pages, revise the topic summaries, flag contradictions. The wiki is an artifact that keeps compounding. The LLM is both the editor-author of the books and the librarian. It has to make sure the encyclopedia it compiles is complete, has a table of contents, can be indexed, and can be discovered progressively.

The architecture has three layers:

  1. Raw Sources: the original material. Immutable, the source of truth.
  2. Wiki: a set of Markdown files the LLM generates and maintains. The entry point for retrieval.
  3. Schema: a rules document that tells the LLM how to organize the wiki.

The human picks the material, asks the questions, makes the calls. The LLM organizes, cross-references and keeps the books. In other words, new knowledge should be "compiled" into the encyclopedia once (cross-checking where it belongs and building the index along the way), instead of piecing together an answer and running it on the spot every time a question comes up.

From idea to practice

Inspired by this, I rebuilt that knowledge base project to see if it would work better. The architecture is almost exactly what Karpathy describes, with a few adaptations:

  • Layer 0 is raw data. JSON pulled from the backend API, one file per entry, fetched automatically by a script, no manual edits allowed. This is the single source of truth.

  • Layer 1 is source files. A script converts the JSON into Markdown, keeping the structured metadata (frontmatter) for indexing later. FAQs, the plant encyclopedia and blog posts each get their own directory. Product spec pages have no API, so they're maintained by hand.

  • Layer 2 is the wiki. This layer is generated entirely by the LLM. After reading every source file in Layer 1, it synthesizes topic pages, device pages, guide pages and comparison pages. A "beginner's guide", for example, pulls together 5 plant encyclopedia entries, 4 FAQs and 3 blog posts.

There's one important design principle here: the agent is the librarian, not the author. Every sentence in the wiki should trace back to raw material in Layer 1. The LLM doesn't create new knowledge. It just puts scattered knowledge on the right shelf.

The effect was immediate. Before, when a user asked "what do I do with my plants while I'm on vacation", RAG might fish up one FAQ about automatic watering and a not-very-relevant blog post. Now the wiki has a dedicated vacation-care guide that already brings together automatic watering, tank capacity, how long each device can run unattended, and a checklist for before you leave. The LLM reads that one page and gives a complete answer.

index.md and manual tuning

The retrieval entry point for the whole system is a single index.md file. One summary line per document, with a link. The LLM reads the index first, locates the relevant pages, then reads deeper. At a scale of 200-plus documents, this is more controllable than vector search.

But the auto-generated summaries weren't good enough. Index entries written by the LLM tend to be too generic and miss the keywords users actually search for. This is where learning from failed cases really helps.

It's not advanced technology. It's the most basic kind of annotation (handed to the AI). The effect was significant: a few dozen covered cases lifted retrieval accuracy by a big margin.

The core logic of the AI-driven index optimization script:

1. Run the retrieval tests → read test-results.json
2. Find the failed cases where fileRecall < 100%
3. For each missed file:
   a. Read the file's actual content
   b. Read its current summary in index.md
   c. Collect every failed question involving this file
   d. Call the LLM: file content + failed questions → generate an enhanced summary
4. Update the corresponding line in index.md directly
5. Rerun the tests to verify
6. Output an optimization report (what changed, what it did)

When the wiki grows, search becomes the bottleneck

Karpathy himself admits that index.md is only enough while the wiki is small. Once you pass a few hundred pages, you need a real search engine. He recommends a tool: QMD.

I spent some time in QMD's source code. It's an open-source project by Tobias, Shopify's CEO, and it passed twenty thousand stars in 4 months. A few of its key algorithms are worth walking through.

Probe first, then call the model

QMD's hybrid search pipeline has 8 steps, and step 2 hides a clever optimization: Strong-Signal Short-Circuit.

Before calling any LLM, it runs a cheap BM25 full-text search. If the top result scores above 0.85 and leads the second-place result by more than 0.15, it skips LLM expansion entirely and saves the model loading and inference latency.

The intuition is simple. When a user searches for something precise like "JWT auth middleware", BM25 has already hit it perfectly, and there's no point spending an LLM on "semantic understanding". When they search "how do I log in", BM25 scores are low and fuzzy, and that's when the LLM is worth calling.

This pattern carries over to any multi-stage AI system: before calling a heavyweight model, use a lightweight signal to decide whether you need to. It's the first principle of cost control.

Original query plus expanded variants

QMD's Query Expansion is the soul of the whole system. It uses a custom fine-tuned 1.7B model to expand the user's natural-language query into several structured search instructions, then runs them in parallel alongside the original query. The original query gets 2x weight, so the user's intent isn't diluted by the expansions. Each expansion has a type, and each type maps to a different search backend:

lex (keyword variants): for BM25. Expands "auth config" into "authentication configuration settings jwt".

vec (semantic rewrites): for vector search. Rewrites "auth config" as "how to configure user authentication settings in the application", closer to how the documents actually phrase it.

hyde (hypothetical document generation): the cleverest path. The LLM first writes a "fake answer", say "Authentication is configured via the config.yml file. Set the auth_provider field to...", and then uses that fake answer for the vector search. Because the fake answer reads more like a real document, cosine similarity is higher, and it finds documents that are semantically related even when their wording is nothing like the user's query.

HyDE (Hypothetical Document Embedding) is an existing technique from academia (Gao et al. 2022), but QMD turns it, lex and vec into a parallel multi-path pipeline and fuses the results with Reciprocal Rank Fusion. That design keeps recall stable across all kinds of query styles.

A few words of intuition on these algorithms, for readers who don't know the retrieval world.

BM25 is basically an upgraded TF-IDF. The core logic: the more often a word appears in a document (term frequency, TF), and the less often it appears across all documents (inverse document frequency, IDF), the more "characteristic" that word is of that document. It also adds term frequency saturation (10 occurrences and 100 aren't that different) and document length normalization (long documents don't get a free ride). The simplified formula:

score⁡(q,d)=∑t∈qIDF⁡(t)⋅TF⁡(t,d)(k1+1)TF⁡(t,d)+k1(1−b+b⋅∣d∣avgdl⁡)\operatorname{score}(q, d) = \sum_{t \in q} \operatorname{IDF}(t) \cdot \frac{\operatorname{TF}(t, d)(k_1 + 1)}{\operatorname{TF}(t, d) + k_1 \left(1 - b + b \cdot \frac{|d|}{\operatorname{avgdl}}\right)}

Here k₁ controls how fast term frequency saturates, and b controls how hard document length is penalized. BM25's strength is speed (pure index lookups, no model inference). Its weakness is that it only matches on surface words: a user searching "how do I log in" won't find a document that says "authentication flow".

HyDE takes a completely different approach. The problem with traditional vector search is that a user query (a short phrase) and a document (a long passage) are stylistically far apart in vector space, which drags cosine similarity down. HyDE has the LLM first write a "fake answer". The content may be wrong, but the style is close to a real document. Searching with the fake answer's vector finds the documents that the query's literal wording "can't reach but are actually relevant".

A fusion strategy that protects exact matches

Fusion is the step in a RAG system most likely to go wrong. Different search engines don't score on the same scale (BM25 scores might run 0-25, vector search 0-1), so you can't just add them. QMD puts up three layers of protection here.

The first layer is RRF (Reciprocal Rank Fusion). Its solution is elegant: ignore the scores, look only at the rank. The formula:

RRFScore(d)=∑weightk+rank\mathrm{RRFScore}(d) = \sum \frac{\mathrm{weight}}{k + \mathrm{rank}}

Here k=60 is a smoothing constant, rank is the document's position in a given search result list, and weight is that query's weight (2x for the original query, 1x for expansions). Scores are summed across all the lists, and a document that ranks high in several of them naturally wins. For example: one document ranks 1st in BM25 and 5th in vector search, fused score = 1/(60+1) + 1/(60+5) = 0.032. Another ranks 10th in BM25 and 2nd in vector search, fused score = 1/(60+10) + 1/(60+2) = 0.030. The first one wins, because it ranks high in both.

The second layer is a Top-Rank Bonus. If a document ranks first in any search list, it gets an extra 0.05; second or third gets 0.02. This keeps "exact matches from being diluted by semantic noise".

The third layer is Position-Aware Blending. A reranker (cross-encoder) is more accurate, but it can overturn high-confidence retrieval results. QMD dynamically adjusts the mix of RRF and reranker by rank position, in three tiers:

  • Ranks 1-3: 75% trust in RRF, 25% in the reranker, protecting exact hits
  • Ranks 4-10: 60% trust in RRF, 40% in the reranker, a gradual transition
  • Ranks 11+: 40% trust in RRF, 60% in the reranker, letting the reranker make more of the call
final_score=α⋅RRFScore+(1−α)⋅rerank_score\mathrm{final\_score} = \alpha \cdot \mathrm{RRFScore} + (1 - \alpha) \cdot \mathrm{rerank\_score}

Here α changes with the RRF rank (0.75 → 0.60 → 0.40).

The insight behind this design: in the "high-confidence zone" the retrieval engine is more reliable than the reranker, and in the "low-confidence zone" the reranker has better judgment than the retrieval engine. Three tiers beat one global weight by a wide margin.

Where the two ideas meet

Looking back, Karpathy's LLM Wiki and QMD tackle two sides of the same problem.

Karpathy tackles how knowledge is organized. Compile scattered information into a structured wiki, and the LLM carries less cognitive load on every query. That's an offline optimization.

QMD tackles how knowledge is retrieved. Once there are enough compiled pages, how do you find exactly the one you need? That's an online optimization.

They complement each other. The wiki makes retrieval easier, because the knowledge is already pre-synthesized and the search engine doesn't have to stitch an answer together across 5 documents. QMD makes retrieval more precise: once the wiki reaches hundreds or thousands of pages, hybrid search is orders of magnitude better than grepping an index file.

Interestingly, QMD's Context System (tagging paths with hierarchical descriptions) and what Karpathy calls the Schema (telling the LLM how to understand the wiki's structure) are essentially the same thing: a small amount of metadata that gives an AI system navigation signals.

The community pushback

The idea isn't uncontroversial. The comments on Karpathy's Gist have some fierce objections, mostly on three points: the wiki is generated by an LLM, so there's a hallucination risk; once it grows, you still need RAG underneath; and "wiki" is the wrong word, because a real wiki is collaborative across many users.

These criticisms have a point, but I don't think they touch the core value. The LLM Wiki was never meant to replace RAG. It sits upstream of RAG. The wiki is the compiled artifact, and RAG (or hybrid search like QMD) is the runtime. They don't conflict.

As for hallucination, the principle that the agent is a librarian and not an author, plus every piece of wiki content being traceable to raw material, already keeps the risk within acceptable bounds. Perfect? No. But far more reliable than having the LLM piece things together from zero on every query.

My take

After building this knowledge base, I've come away with a few fairly firm conclusions.

  1. "Compile vs. retrieve" isn't either/or. They complement each other. At small scale, wiki plus index.md is enough. As it grows, add a search layer like QMD on top. You don't have to do it all at once.

  2. The ROI of manual tuning is extremely high. A small amount of human effort buys a disproportionate jump in quality. It's the most underrated optimization in AI systems. Watch the failed cases, look at the gap between the result and what you expected (most likely a retrieval problem), then have the AI reflect and check whether the index is representative. That's one of the steps that closes the loop toward a complete encyclopedia.

  3. Several of QMD's engineering patterns generalize well. Strong-Signal Short-Circuit (let a lightweight signal decide first), three-way Query Expansion (split one intent into several search forms), Position-Aware Blending (mix by confidence tier). These aren't just search techniques. They're general ideas for building any multi-stage AI pipeline.

  4. For founders, the LLM Wiki pattern Karpathy describes is already very practical at small to medium scale (up to a few hundred documents). No complex infrastructure, no vector database. A directory structure and an index file and it runs. By the time you really need to scale, the tools are already there.

Knowledge management used to run on human willpower, which is why most knowledge bases end up as information graveyards. What LLMs change isn't the knowledge itself, it's the cost of maintaining it. When the cost of maintenance approaches zero, knowledge finally has a chance to compound.

References