Shaf Lab

RAG

Retrieving relevant documents and feeding them to a model so answers stay grounded.

Retrieval-augmented generation, or RAG, means fetching relevant documents and feeding them to a model so the answer stays grounded in material you have, rather than only in the model's training. You chunk a corpus, index it, retrieve the best passages for a question, and then ask the model to answer with those passages in view. It is the standard pattern for a small knowledge base, a product manual, or a set of internal docs.

The name spells out the three steps: retrieve passages relevant to the question, augment the prompt by placing them in context, and generate an answer from that evidence rather than from memory. In the classic form your code does the first two steps and the model does only the last. In agentic retrieval, the model decides for itself when and what to search through tool calls, which handles multi-step questions better but is harder to predict and evaluate.

Quality comes from the corpus and the retrieval, more than from a larger model. Clean documents, sensible chunks, and a hybrid of keyword and vector search will beat a sloppy index every time. Always pass enough of the retrieved text to cite or to inspect, and tell the model what to do when the passages do not contain the answer.

Keep the index fresh, and measure with real questions. A demo query that quotes a heading is not an evaluation set. When the answer is wrong, look at what was retrieved before you rewrite the prompt.

RAG is not a substitute for a database query or for a precise API. Use it when the answer lives in prose, and use a structured query when the answer lives in rows.

Chunking

Cutting documents into passages that are small enough to be specific but large enough to stand alone.

Chunking cuts documents into passages for indexing and retrieval. A chunk should be small enough to be about one thing, so its embedding is specific, and large enough to make sense on its own when a model reads it without the rest of the document. Typical sizes are a few hundred tokens, but the right size depends on the content and the embedding model.

Splitting along natural structure, such as headings, paragraphs, functions, or list items, usually retrieves better than blind fixed-size windows that cut sentences in half. A small overlap between neighboring chunks helps when ideas cross boundaries. Store metadata with each chunk, such as document title, section heading, URL, and date, so results can be filtered, cited, and refreshed, and consider prefixing each chunk with its heading so it carries its context with it.