Pular para o conteúdo
Gerenciador de Prompts

Blog · Engenharia

A simple RAG that works: from PDFs to 4,000 hours of YouTube

26/10/2026 · 16 min de leitura

Cover: a simple RAG that works, from PDFs to 4,000 hours of YouTube

Leia este artigo em português →

One of this project’s goals was always a good RAG: one that actually works and stays simple enough to fit in one person’s head. RAG (retrieval-augmented generation) means fetching the right passages from a collection before asking the model for an answer, so that it answers from what is written rather than from memory.

At Gerenciador de Prompts, a Brazilian AI assistant, the same design serves two very different cases: the documents you upload to the chat (PDFs, contracts, public tenders, manuals), and a test we are particularly pleased with, a panel that talks to YouTube channels. There, five channels add up to 5,218 videos, about 4,255 hours of video and 39.5 million words. Every claim in an answer carries a number that opens the video at the passage it came from.

This article shows how it was built: the parts, the configuration numbers and the measurements behind each of them.

The recipe in seven principles

  1. OpenAI vectors, index at home. Embeddings come from text-embedding-3-large, but the vectors live on our own machine: in LanceDB on disk for documents, and in flat files loaded into memory for the channels. There is no managed vector database: apart from OpenAI itself, no third-party service sits on a question’s path.
  2. Search by meaning and by word. Vectors understand paraphrase but blur names, acronyms, article numbers and amounts. So every search runs two rankings, one by vector and one by BM25, fused by each passage’s position.
  3. The right passage beats a big passage. Chunking follows the material’s structure: paragraphs and lines in documents, sentence ends in captions, overlap between neighbours and, on YouTube, the second at which each passage starts.
  4. Every sentence cites its source. The model only states what the passages support, marks the passage number on each sentence, and says plainly when the collection does not cover the subject.
  5. The decisions that matter most have a measurement behind them. How many passages to fetch, how large the context ceiling is, which model answers, how much precision vector compression costs: all of it came from our own benchmarks, with answer keys anchored in the documents’ text.
  6. What doesn’t pay for itself goes. A metadata header on every chunk and a local reranker made search worse; dictionary-based vocabulary expansion and a commercial reranker gained little for what they would cost. All four were measured and left out.
  7. Context lasts one turn. Passages go into the current question, fenced as data, and do not pile up in the history. Without that rule a 20-turn conversation would resend thousands of tokens of old context with every message, and the provider bills for all of them.

The architecture in one figure

RAG diagram: documents and YouTube captions go through extraction, chunking and OpenAI embeddings into a local index; a question goes through vector search and BM25, rank fusion, passage selection and a cited answer.
Two sources, one recipe: what differs between documents and channels is how the text is prepared. Search and answer follow the same rules. Click or tap the image to enlarge.

Documents: an off-the-shelf engine with nine files replaced

For uploaded files we use AnythingLLM (open source, MIT licence) as the ingestion and search engine. Instead of adopting a whole framework or writing an engine from scratch, we keep a thin layer on top of it: nine replaced files, about 80 KB of JavaScript that fits in one code review. The build checks the checksums of the upstream files and fails if a new upstream version changes any of them. An image that looks patched but runs the original code would produce numbers no measurement describes.

A document’s path:

  • The original goes to S3 and the text is extracted, with OCR when the PDF is scanned.
  • The text is cut into 1,000-character chunks with 150 characters of overlap.
  • Each chunk becomes a 3,072-dimension vector, at US$ 0.13 per million tokens. Brazil’s entire Federal Constitution, 286 pages and about 170,000 tokens, costs a little over two US cents to index.
  • At question time, hybrid search fetches 100 candidates, filters them to the documents you ticked, and keeps up to 24 chunks within a 24,000-character ceiling.
  • The chunks go into a system message of their own, fenced and labelled as data, never pasted into the user’s message. A document can contain “ignore the previous instructions”, and the model is told that this is reference material.
  • If search returns no chunk at all, the answer is a polite refusal and the model is not called. A call that could only invent is not worth what it costs.

The changes the measurements asked for

ChangeHow it was measuredResult
Hybrid search (vector + BM25, fused by RRF) and no metadata header on every chunk20 tender notices from 20 e-procurement platforms never used for tuningRecall@24 from 63.2% to 72.5%; MRR from 0.275 to 0.371
From 8 to 24 chunks, with the context ceiling raised alongside (from 8,000 to 24,000 characters)50 questions about the Constitution, with 181 grading criteriaQuestions with every required article in context: from 86% to 92%
Fetch 100 candidates, then filter to the ticked documents200 questions, half over ten kinds of PDF and half over ten long manuals, three repetitionsCriteria met: from 85.8% to 89.0% (paired difference +2.9 points; 95% interval 0.5 to 5.6)
A light model for questions with documentsThe same 50 Constitution questions83.2% of the criteria, against 87.3% for the top model, which costs about 17 times more

Two details of these measurements apply to any RAG. First, raising the number of chunks without raising the context ceiling throws the gain away: fetching 24 and cutting at 8,000 characters scored 77.4% of the criteria, against 83.2% with the whole context, the only gap in that benchmark well above the noise. The cut discards exactly what the larger search went to fetch. Second, the header with the document’s name, which the original engine puts on every chunk, pulls all the vectors toward the same direction and spends paid context on repeated words. Turning it off, on its own, gained 6.6 points of Recall@24 on the tenders; on the Constitution the difference stayed within the noise (57 against 58 of 69 articles).

A third benchmark, with ten kinds of PDF (scientific paper, form, datasheet, report with charts, slides, financial statements, drug leaflet, statute, scanned document, book), showed where the problem is not: extraction found 162 of the 163 anchors in the answer key (99.4%), and the one it missed was in the scanned document. What hurts search is the neighbourhood. With one document in the collection, retrieval was 90%; with ten it fell to 81%, and the 100-candidate fix brought that case to 86%.

What was tested and left out

  • A local reranker. The cross-encoder that ships with the engine took 17 seconds to reorder 50 candidates on a 2-vCPU machine and, on the 6 questions where it was compared, got fewer right than plain search (4 against 5). It is a model trained on English reading Portuguese legal text. Without it, search took 0.41 s at the median, measured in production.
  • Dictionary-based vocabulary expansion, such as replacing “IPTU” (the municipal property tax) with its full legal name before searching. It gained one question in 50 and none on 40 hard ones, and the dictionary only fits constitutional law: expanding “IR” (income tax) in the search of someone who uploaded a rental contract makes the query worse. With a strong embedding the bottleneck was not vocabulary but how many articles the answer requires.
  • A commercial reranker. It improved the answers, but most of the gain came from a free fix, fetching more candidates before filtering. On top of that fix, the service’s own gain (+1.8 points) was not proven (95% interval −0.1 to 3.7). We kept the fix and skipped the new vendor, which would have meant one more contract, one more entry in our data-protection (LGPD) records and 0.45 s more per question.

YouTube channels: the same design, tuned for speech

The channels panel started as a test: if the RAG is good, it has to work on material much harder than a PDF. YouTube’s automatic captions are machine-transcribed speech with unreliable punctuation, mangled names, guests talking over each other and four-hour live streams that repeat the same greeting every week. The test’s five Brazilian channels range from science to business, self-improvement and faith:

The five channels, combinedTotal
Videos5,218
Hours of video~4,255
Words39.5 million
Passages indexed212,864
Embedding cost to index all of itUS$ 10.12

Here we do not use the documents engine. Each collection is fixed, large and the same for every user, and what matters most in it, the time of each utterance, does not survive a generic extractor. The simplest solution was an index of our own: eight flat files (manifest, passage records, texts, vectors, vocabulary and inverted lists) that the server loads into memory on the first question. That is about 130 MB for 52,000 passages, and removing the feature means deleting a directory.

1. From captions to timed text

The captions (.vtt) and each video’s metadata are downloaded with yt-dlp. Automatic captions “roll”: each line repeats the previous one and adds a few words. The reader keeps only what is new in each line, drops tags such as [música] and [aplausos], and turns the >> that marks a change of speaker into a dash. What it never drops is the time. The time is what turns “somewhere in a four-hour live stream” into a link to the sentence.

2. Ninety-second passages

Each passage holds about 90 seconds of speech. It closes at the first sentence end after 180 words, or by force at 250, because an excited speaker can go a long way without a full stop. Each passage repeats the last 40 words of the previous one, so an idea cut at a boundary is whole in one of the two; when two neighbours are picked together, they are joined back without the repeated seam.

split: sentence end after 180 words · max 250 · overlap 40 · min tail 60

3. What gets embedded: title + passage

The embedded text is the video’s title followed by the passage. The reason is practical: automatic captions mangle names, and the hand-written title spells the guest’s name correctly. On podcast channels, where the guest talks more than the host, that helps both search and the attribution of who said what.

4. Smaller vectors: 1,024 dimensions, one byte each

text-embedding-3-large is trained so that its first dimensions carry most of the meaning, which lets you request the vector already cut from 3,072 to 1,024 dimensions (the API’s dimensions parameter). Each dimension is then stored as one signed byte instead of a 4-byte float: the scale maps the 99.99th percentile of the values to 127, and the rare larger value is clamped. Each passage takes 1 KB, against 12 KB for the full float vector. The indexer measures the price of this compression on every build: the byte vectors recover 97.8% to 99.8% of the exact top 10, depending on the channel.

5. Two-pass search, no approximate index

With 50,000 passages, comparing the question’s vector with every passage in every dimension takes about 53 million multiplications: around 160 ms of one core, during which a Node server answers nobody else. Instead of an approximate index (HNSW, IVF), search runs two passes. It first ranks every passage by its first 256 dimensions, then scores all 1,024 only for the best 1,500. Measured on 30 questions against the 51,966-passage collection: 62 ms instead of 159 ms, the same first result in 30 of 30, all of the top 16 and 99.4% of the top 80.

Next to the vector search runs BM25, in 1 to 2 ms, over a lower-cased, accent-free vocabulary. No stemming, on purpose: the obvious plural rule turns “Deus” (God) into “deu” (gave), one of the most frequent words in these collections. The stop-word list includes the fillers of spoken Brazilian Portuguese, such as “né”, “tá”, “aí” and “cara”. The two rankings are fused by RRF (reciprocal rank fusion):

score(passage) = Σ weight ÷ (60 + position in the ranking)

original question:   vector 1.0 · BM25 0.5
each rewrite:        vector 0.7 · BM25 0.35

The fusion uses positions, not scores, because a cosine and a BM25 score are not comparable. Each ranking contributes its best 80 candidates.

6. Selection: variety, no repeats

  • At most 3 passages per video. Without that limit, one four-hour live stream would answer everything.
  • Nothing said twice. Live streams in a series open with the same greeting, and some videos are re-runs. A passage from another video with a cosine above 0.9 to one already chosen is skipped. The threshold was measured on the collection itself: the same greeting in two live streams sits between 0.91 and 0.99; different stretches of the same series, between 0.79 and 0.86.
  • Neighbours joined. Two consecutive passages from the same video become one.
  • A size ceiling. Up to 16 passages and 36,000 characters per question.

7. The prompt: third person, citations, reading through errors

The model receives the numbered passages, each with the video’s title, date and minute, and three rules weigh more than the others:

  • Only what the passages support, with the passage number right after each sentence, in the third person (“on the channel, he says that…”). An answer that improvises would be putting words in a real person’s mouth.
  • Read through transcription errors. The model infers from context the word that was said, uses the correct form, and leaves out what is unintelligible instead of guessing. World knowledge serves only to recognise a mangled name, never to add information.
  • Not every voice belongs to the channel’s owner. Guests, family and the audience speak too; on a podcast the guest speaks most. A line is attributed to the host only when it is clearly the host’s.

The passages are also declared reference material, not instructions: any order that appears inside a caption is to be ignored. In the interface each cited number is a link like youtube.com/watch?v=ID&t=754s, which opens the video at the second the passage starts. The passages reach the screen before the answer, so the source is already there while the text is being written.

8. Follow-up questions

“What about that?” retrieves nothing. On a follow-up, a short model call rewrites the question so it stands alone and proposes up to two variations in the words of someone talking about the subject, because the collection is speech, not written text. The first question of a conversation is searched exactly as typed. If the rewrite fails or takes longer than 12 seconds, the original question is searched anyway: a poorer search beats no answer.

When the captions lost their timing

For one channel, a conversion step deleted the original captions and only their text, without timing, was left. Rather than leave the channel out, the indexer estimates each passage’s time from the share of words spoken up to that point, 20 seconds early, so the link lands before the speech rather than after it. Measured on three channels that had both versions, the estimate is off by 11 to 16 seconds at the median and by less than a minute 9 times in 10. Those links show a “~” on the clock, and the page says the video opens near the point.

Latency and cost

The times were measured on the development machine; tokens and cost hold in any environment.

StepMeasured
From question to passages (almost all of it is the embedding call)~0.7 s
First word of the answer4 to 5 s
Whole answer5 to 9 s
Tokens per question~6,000 in, 200 to 550 out
Provider cost per question~US$ 0.0015
Indexing a whole channelUS$ 0.45 to 2.89, in 4 to 8 minutes

The indexer resumes: vectors are cached as they arrive, so a run interrupted at 90% pays only for the remaining 10%. And the panel has no meter of its own. Each question goes, inside the same process, through the chat’s own route, with the same limits, the same balance reservation before the call and the same settlement after it. A second meter would be a second set of numbers to keep equal to the first.

What we learned

  • Measure the cheapest axis first. Going from 8 to 24 chunks re-indexed nothing, changed no model and gained 6 points of article coverage. The old value came from a battery of 8 questions that saturated.
  • Compare a new component with the best free alternative, not only with what is in production. That is what separated the commercial reranker’s gain from the gain of simply fetching more candidates.
  • Measure retrieval separately from the answer. Large models answer many questions from memory, and a high score at the end of the pipeline can hide poor retrieval. That is why we count the anchors that reach the context, not just the right answers.
  • Repeat before concluding. The models we use do not accept a temperature of zero, and the same configuration varies by up to 3.9 points between runs. No difference smaller than that counts as a conclusion without three repetitions.
  • Keep the structure that gives the material its value. In a PDF it is the whole chunk and the number that identifies it. In a video it is the second at which something was said.
  • Simple storage until it hurts. Typed arrays in flat files serve 52,000 passages in 62 ms. A vector database comes in when the problem asks for one, not before.

Known limitations

  • Automatic captions make mistakes, and nothing tries to fix them. The model reads by context, but a badly mangled name is left out of the answer.
  • Speakers are not identified. Speaker changes are marked, but the guest’s name comes from the title, which is right for an interview with one guest and a guess at a table of three.
  • The channels panel does not have a benchmark with an answer key yet, as the documents do. Its parameters (16 passages, 36,000 characters, the fusion weights) were validated in use, question by question.
  • A new video re-indexes the whole channel today. At one or two dollars a run, a per-video cache has not been worth it yet.
  • In documents, a two-column table can lose the link between a value and its column, and a question about the collection itself (“which documents are from the Central Bank?”) has no answer, because the list of documents does not enter the context.

Try it with your own documents

Gerenciador de Prompts’ free plan includes documents: up to 5 files and 300,000 tokens of text, enough for the whole Constitution and one more. The app is in Brazilian Portuguese. Upload a PDF in the chat, tick the document and ask: every sentence of the answer carries the number of the passage it came from.

Open the chat and upload a document →