Build Your Own AI That Can Search Your Documents (RAG)
How RAG works, how to set it up on a VPS, and where to look when it doesn't work well. It covers tuning chunking and search, how to show the basis of an answer, and how to protect the material you collect.

Ren

Procura
Ren

Procura
The flow
- 1. Split your documents into pieces of a suitable length
- 2. Convert each piece into a "sequence of numbers representing its meaning" and store it (embedding)
- 3. When a question comes in, convert the question into numbers in the same way
- 4. Find the pieces whose numbers are close, meaning close in meaning
- 5. Hand the pieces you found together with the question to the AI and have it answer based on them
Running it on a VPS

Procura
- Where to store embeddings: there are dedicated databases for searching by closeness of meaning (vector databases), but for a small scale, a PostgreSQL extension is enough
- While you have little material, you can start without any special tricks
- Combining with full-text search improves accuracy for searching proper nouns
Where to look when it doesn't work
When answers are off, the cause is almost always on the search side, not the model. If it picks up unrelated parts, no model can answer correctly. First, have it display what it was given as the basis. Looking at what was passed tells you whether your chunks are too small or too large.
Tuning chunking and search
- Decide the chunk length by trying it on your actual documents. Too small and context is lost, too large and unrelated information gets mixed in
- Splitting with a little overlap between chunks lets you catch context that was cut at the boundary
- Attaching headings and sources to chunks lets you show the basis of an answer
- Pass several candidates. With only one, you can't answer if it misses
Showing the basis of an answer

Procura

Procura
Care with the data you handle
If you handle internal documents, check that what search can pick up doesn't go beyond people's permissions. If you put all the text into one container, documents that someone shouldn't be able to see can show up as the basis of an answer. Even if it works correctly as a mechanism, in operation it's an accident.

Wilson

Procura
- Put authentication on the search feature. Don't make it public
- Divide, per user, the range of documents they're allowed to see
- If you pass content to an external API, check in the terms how what you passed is handled
- When you update documents, delete the old chunks (if you forget, old answers keep coming back)

Ren
This article is translated from the Japanese original. If the two differ, the Japanese version is the one we keep up to date.