The post has been translated automatically. Original language: Russian Russian
When working with clients, we often come across the question: "Explain in a human way what RAG is and how to assemble it so that it works in business?". We decided to give a simple explanation to make it clear to everyone.
If there are any white spots along the way, then let us know in the comments. Let's update the material, expand the controversial points and add practices from real implementations.
Retrieval-Augmented Generation is a way to make a large language model respond not "out of its head", but based on actual facts. The bottom line is simple, we add information found from the outside (from the knowledge base, files, web sources) to the user's question and already give this whole set to LLM. As a result, the model relies on context and provides an accurate, verifiable answer.
For example, if we ask: "What is the average height of an emperor penguin?" first, you need a source of truth — an encyclopedia, expert websites, etc. — and only then this fragment is added to the question. The model doesn't guess, she reads.
It's a bad idea to constantly retrain the model on the FAQ, which changes every week. Expensive and unreliable. It is much better to find relevant articles on the issue and attach their pieces to the query. The model generates an answer based on the relevant sections of the knowledge base.

This is exactly what the name describes: retrieval (finding facts) → augmentation (adding to the query) → generation (forming a response based on what was found).
- We cut documents into chunks — small fragments of 100-1000 words each.
- We encode chunks into vectors (embeddings) — we get a numerical representation of the meaning.
- We put it in vector storage to quickly search for the fragments closest to the meaning.
- We find the top N suitable chunks for a specific question (usually by cosine proximity).
- We are collecting a hint for LLM: system instructions + user's question + found pieces.
- We get an answer where the model is based not on memory, but on the facts provided.
It looks elementary on paper. In practice, the first version almost always works "wrong". Then the tuning begins.
But, the devil is in the details. Let's look at the size and overlap of the chunks.:
Combined search, because a single vector search is not a silver bullet. For terms and formulations, BM25/TF-IDF will help. A common scheme is hybrid retrieval: we combine the results "by meaning" and "by words" with the weights found on your data.
Query expansion Rephrase the question in 3-5 ways (automatically) and search for all the options. This way you increase the chance to get the right content, even if the original wording was "not as in the documentation."
Compression and repackaging If there is too much found and everything does not fit into the context, make a squeeze for each group of similar fragments and give the model an "archive of knowledge", not a sheet of text.
The RAG mode for the model is a System prompt (and at the mature stage, an easy refresher), explain the format: the question is here, the facts are here, answer only based on the facts; if there are not enough of them, say so. This reduces "hallucinations" and disciplines responses.
- Prepare the corpus: PDF/HTML/Markdown → blank text.
- Cut into chunks with overlap (for example, 300-600 words, overlap 50-100 words).
- Build embeddings and put them in vector storage.
- Implement a hybrid retriever: vectors + BM25/TF-IDF, set weights.
- Assemble the prompt: instructions → question → top-k chunks.
- Add logging: which question, which chunks, which answer. Without tracing, RAG does not improve.
To understand that the model has become better at responding, you need a set of real questions. As a rule, they are written by business people who will actually use the assistant. Preferably multiple answers to the same question, written by people. If the launch is urgent, you can first generate the benchmarks with an assistant model on small documents, and then manually correct them. Mix several (ROUGE/BERT-like) into one aggregated one. The main thing is to choose weights for your subject area.
Save the pairs "question → reference chunks" and measure the MRR. In 8 cases out of 10, the quality of the final response breaks down precisely at the search stage, and not at the generation stage.
We are waiting for your questions and comments!
Работая с клиентами мы часто сталкиваемся с вопросом: «Объясни по-человечески, что такое RAG и как его собрать, чтобы работало в бизнесе?». Мы решили дать простое объяснение, чтобы было понятно каждому.
Если по пути останутся белые пятна, то дайте знать в комментариях. Обновим материал, развернем спорные места и добавим практики из реальных внедрений.
Retrieval-Augmented Generation — это способ заставить большую языковую модель отвечать не «из головы», а на основе актуальных фактов. Суть проста, мы к вопросу пользователя добавляем найденные извне сведения (из базы знаний, файлов, веб-источников) и уже весь этот комплект отдаём LLM. В результате модель опирается на контекст и даёт точный, проверяемый ответ.
Если например мы спросим: «какой средний рост у императорского пингвина?» то, сначала нужен источник правды — энциклопедия, экспертные сайты и.т.п. — а уже затем этот фрагмент подкладывается к вопросу. Модель не угадывает — она читает.
Плохая идея — постоянно дообучать модель на FAQ, который меняется каждую неделю. Дорого и ненадёжно. Гораздо лучше, по вопросу находить релевантные статьи и прикладывать их кусочки к запросу. Модель формирует ответ, опираясь на актуальные разделы базы знаний.

Именно это и описывает название: retrieval (поиск фактов) → augmentation (добавление к запросу) → generation (формирование ответа с учётом найденного).
- Режем документы на чанки — небольшие фрагменты по 100–1000 слов.
- Кодируем чанки в векторы (эмбеддинги) — получаем числовое представление смысла.
- Складываем в векторное хранилище — чтобы быстро искать ближайшие по смыслу фрагменты.
- Находим топ-N подходящих чанков к конкретному вопросу (обычно по косинусной близости).
- Собираем подсказку для LLM: системная инструкция + вопрос пользователя + найденные куски.
- Получаем ответ, где модель опирается не на память, а на предоставленные факты.
На бумаге выглядит элементарно. На практике — почти всегда первая версия работает «не так». Дальше начинается тот самый тюнинг.
Но, дьявол кроется в деталях. Давайте посмотрим на размер и перекрытие чанков:
Комбинированный поиск, ведь один векторный поиск — не серебряная пуля. Для терминов и формулировок помогут BM25/TF-IDF. Частая схема — hybrid retrieval: объединяем результаты «по смыслу» и «по словам» с весами, найденными на ваших данных.
Расширение запроса (query expansion) Перефразируйте вопрос 3–5 способами (автоматически) и ищите по всем вариантам. Так повышаете шанс достать нужный контент, даже если оригинальная формулировка была «не как в документации».
Сжатие (summarization) и переупаковка Если найденного слишком много и в контекст всё не лезет — делайте выжимку по каждой группе похожих фрагментов и отдавайте модельке уже «архив знаний», а не простыню текста.
Режим RAG для модели Системной подсказкой (а на зрелом этапе — лёгким дообучением) объясните формат: вопрос тут, факты тут, отвечай только на основании фактов; если их мало — скажи об этом. Это снижает «галлюцинации» и дисциплинирует ответы.
- Подготовьте корпус: PDF/HTML/Markdown → чистый текст.
- Разрежьте на чанки с перекрытием (например, 300–600 слов, overlap 50–100 слов).
- Постройте эмбеддинги и положите во векторное хранилище.
- Реализуйте гибридный ретривер: вектора + BM25/TF-IDF, задайте веса.
- Соберите промпт: инструкция → вопрос → топ-k чанков.
- Добавьте логирование: какой вопрос, какие чанки, какой ответ. Без трассировки RAG не улучшается.
Чтобы понять, что модель стала лучше отвечать, нужен набор реальных вопросов. Как правило их пишет бизнес — те, кто действительно будет пользоваться ассистентом. Желательно несколько ответов на один вопрос, написанные людьми. Если запуск срочный, можно сначала сгенерировать эталоны моделью-ассистентом на небольших документах, а потом вручную подправить. Смешайте несколько (ROUGE/BERT-подобные) в одну агрегированную. Главное — подобрать веса по вашей предметной области.
Сохраните пары «вопрос → эталонные чанки» и меряйте MRR. В 8 случаях из 10 качество финального ответа ломается именно на этапе поиска, а не генерации.
Ждем ваши вопросы и замечания!