Why LLMs Need Help
Large language models (LLMs) are excellent writers but poor librarians.
Ask one about your company's refund policy, and it might confidently answer with a policy it made up.
Three limitations cause this:
- Frozen knowledge: A model only knows what was included in its training data, up to its cutoff date. Yesterday's price change does not exist for it.
- No private data: Your product catalog, support tickets, and internal documents were never included in its training data.
- Hallucination: When a model doesn't know something, it often guesses fluently instead of saying, "I don't know."
Retrieval-Augmented Generation (RAG) addresses all three problems without retraining the model.
It is now a common architecture behind AI chatbots that answer questions using company-specific data.
What Is RAG?
RAG means: before the model answers, retrieve relevant information and include it in the prompt.
The model then generates an answer using that information instead of relying entirely on its internal knowledge.
Think of it as turning a closed-book exam into an open-book exam.
The student (the LLM) is still responsible for writing the answer, but now it can look at the right pages first.
The name describes three steps:
- Retrieval — Search your knowledge base for passages related to the question.
- Augmentation — Add those passages to the prompt as context.
- Generation — The LLM generates an answer grounded in that context, ideally with citations.
How Does RAG Work?
A RAG system consists of two pipelines that share a vector store.
- Data Ingestion & Indexing: Runs offline. It chunks documents, converts each chunk into an embedding, and stores the vectors.
- Retrieval & Generation: Runs whenever someone asks a question. It converts the question into an embedding, retrieves the closest chunks, and passes them to the LLM inside the prompt.
The augmented prompt is where retrieval and generation meet.
Core Concepts of RAG
Five building blocks make up a basic RAG system.
1. Chunking
Documents are divided into smaller passages, typically 200–800 tokens.
A small overlap is often maintained between chunks so that sentences are not separated from their surrounding context.
- Chunks that are too large dilute relevance.
- Chunks that are too small lose meaning.
2. Embeddings
An embedding model converts each chunk into a vector — a list of numbers (for example, 1,536 floating-point values) representing its semantic meaning.
Texts with similar meanings are placed close together in vector space, even when they use different words.
For example:
- "How long does delivery take?"
- "Shipping time is 2–3 days."
These sentences can have similar embeddings despite using different wording.
3. Vector Store
The generated vectors are stored in a database designed for nearest-neighbor searches.
Popular options include:
- pgvector (PostgreSQL)
- Qdrant
- Weaviate
- Pinecone
- Milvus
- Chroma (useful for prototypes)
Each vector is stored alongside its original text and metadata, such as source, date, and category.
4. Similarity Search
When a user asks a question, the question is embedded using the same embedding model.
The vector store returns the top-k closest chunks.
Closeness is commonly measured using cosine similarity:
A score close to 1 indicates highly similar meaning, while a score close to 0 indicates unrelated content.
5. Prompt Augmentation
The retrieved chunks are added to a prompt template with clear instructions.
For example:
- Answer only using the provided context.
- Cite the sources used.
- Say "I don't know" when the context does not contain the answer.
This helps keep generated responses grounded in retrieved information.
Worked Example: An Online Store's Support Bot
Imagine an online shop wants to build a chatbot that answers customer questions using its own policy documents.
Let's follow one question through the entire RAG pipeline.
Note: The similarity scores below are illustrative.
Step 1 — Build the Knowledge Base
The store has several policy documents.
After chunking, five example chunks look like this:
| Chunk | Source | Content |
|---|---|---|
| C1 | returns.md | Items can be returned within 7 days of delivery if unused and in original packaging. |
| C2 | returns.md | Refunds are sent to the original payment method within 5–7 business days after we receive the item. |
| C3 | shipping.md | Inside Dhaka, delivery takes 1–2 days. Outside Dhaka, 3–5 days. |
| C4 | payments.md | We accept bKash, Nagad, cards, and cash on delivery. |
| C5 | returns.md | Cash-on-delivery orders are refunded via bKash or bank transfer. |
Each chunk is embedded once and stored in the vector database.
Step 2 — The Customer's Question
A customer asks:
I paid cash on delivery and want to return my shoes. How do I get my money back and how long will it take?
Step 3 — Retrieve Relevant Information
The question is converted into an embedding and compared with the stored vectors.
The top results are:
| Rank | Chunk | Cosine Score | Kept? |
|---|---|---|---|
| 1 | C5 — COD refunds via bKash/bank | 0.89 | Yes |
| 2 | C2 — Refund in 5–7 business days | 0.84 | Yes |
| 3 | C1 — 7-day return window | 0.81 | Yes |
| 4 | C4 — Payment methods | 0.62 | No (below 0.7 threshold) |
| 5 | C3 — Delivery times | 0.41 | No |
Notice that C5 ranks first even though the customer wrote "cash on delivery" and "money back", while the document says "Cash-on-delivery orders are refunded."
Embeddings understand semantic meaning, not just exact keyword matches.
Step 4 — Augment the Prompt
The retrieved chunks are added to the prompt:
You are a support assistant for our store.
Answer ONLY using the context below.
Cite the chunk IDs you used.
If the answer is not in the context,
say you don't know and offer a human agent.
Context:
[C5] Cash-on-delivery orders are refunded
via bKash or bank transfer.
[C2] Refunds are sent to the original payment
method within 5-7 business days after we
receive the item.
[C1] Items can be returned within 7 days
of delivery if unused and in original packaging.
Question:
I paid cash on delivery and want to return
my shoes. How do I get my money back
and how long will it take?
Step 5 — Generate the Answer
The LLM generates the following response:
You can return the shoes within 7 days of delivery, as long as they're unused and in the original packaging [C1]. Since you paid cash on delivery, your refund will be sent by bKash or bank transfer [C5], within 5–7 business days after we receive the shoes [C2].
Every claim is traceable to a source chunk.
Without RAG, the same model might invent a return window or incorrectly say that the refund would be sent to the original payment method, which is not possible for a cash-on-delivery order.
Building a Minimal RAG System in Laravel
The entire pipeline can be implemented using a database migration and a service class.
This example uses:
- PostgreSQL + pgvector: Vector storage and similarity search.
- OpenAI text-embedding-3-small: Generates embeddings with 1,536 dimensions.
- Claude: Generates answers using the retrieved context.
You can replace the embedding or chat API with other providers.
1. Database Migration
Create a table to store document chunks and their embeddings.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration {
public function up(): void
{
DB::statement('CREATE EXTENSION IF NOT EXISTS vector');
DB::statement('
CREATE TABLE knowledge_chunks (
id BIGSERIAL PRIMARY KEY,
source VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
embedding vector(1536) NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
)
');
// HNSW index for fast approximate cosine search
DB::statement('
CREATE INDEX ON knowledge_chunks
USING hnsw (embedding vector_cosine_ops)
');
}
public function down(): void
{
DB::statement('DROP TABLE IF EXISTS knowledge_chunks');
}
};
2. Create the RAG Service
Create a service class responsible for:
- Chunking documents.
- Generating embeddings.
- Storing vectors.
- Retrieving relevant chunks.
- Generating answers.
Create app/Services/RagService.php.
<?php
namespace App\Services;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
class RagService
{
// ---------- Indexing ----------
public function indexDocument(string $source, string $text): void
{
foreach ($this->chunk($text) as $piece) {
DB::insert(
'INSERT INTO knowledge_chunks
(source, content, embedding)
VALUES (?, ?, ?::vector)',
[
$source,
$piece,
$this->toPgVector($this->embed($piece))
]
);
}
}
/**
* Split on paragraphs, then pack into ~800-character
* chunks with overlap.
*/
private function chunk(
string $text,
int $size = 800,
int $overlap = 100
): array {
$chunks = [];
$current = '';
foreach (preg_split('/\n\s*\n/', trim($text)) as $para) {
if (
strlen($current) + strlen($para) > $size
&& $current !== ''
) {
$chunks[] = trim($current);
$current = substr($current, -$overlap);
}
$current .= "\n\n" . $para;
}
if (trim($current) !== '') {
$chunks[] = trim($current);
}
return $chunks;
}
private function embed(string $text): array
{
return Http::withToken(config('services.openai.key'))
->post('https://api.openai.com/v1/embeddings', [
'model' => 'text-embedding-3-small',
'input' => $text,
])
->throw()
->json('data.0.embedding');
}
private function toPgVector(array $v): string
{
return '[' . implode(',', $v) . ']';
}
// ---------- Querying ----------
/**
* Return the top-k chunks above a similarity threshold.
*/
public function retrieve(string $question, int $k = 4): array
{
$vector = $this->toPgVector($this->embed($question));
// <=> is pgvector's cosine DISTANCE.
// Similarity = 1 - distance.
return DB::select('
SELECT
id,
source,
content,
1 - (embedding <=> ?::vector) AS score
FROM knowledge_chunks
ORDER BY embedding <=> ?::vector
LIMIT ?
', [$vector, $vector, $k]);
}
public function answer(string $question): array
{
$chunks = array_filter(
$this->retrieve($question),
fn ($c) => $c->score >= 0.7
);
if (empty($chunks)) {
return [
'answer' => "I don't have information on that. Let me connect you to a human agent.",
'sources' => []
];
}
$context = collect($chunks)
->map(
fn ($c) => "[C{$c->id}] ({$c->source}) {$c->content}"
)
->implode("\n\n");
$response = Http::withHeaders([
'x-api-key' => config('services.anthropic.key'),
'anthropic-version' => '2023-06-01',
])
->post('https://api.anthropic.com/v1/messages', [
'model' => 'claude-sonnet-5-5',
'max_tokens' => 500,
'system' =>
'You are a support assistant. Answer ONLY from the provided context. '
. 'Cite chunk IDs like [C12]. If the context does not contain the answer, say so.',
'messages' => [[
'role' => 'user',
'content' => "Context:\n{$context}\n\nQuestion: {$question}",
]],
])
->throw();
return [
'answer' => $response->json('content.0.text'),
'sources' => array_values(
array_map(
fn ($c) => $c->source,
$chunks
)
),
];
}
}
3. Use the RAG Service
You can use the service inside a controller or Laravel Tinker.
$rag = app(\App\Services\RagService::class);
Index a document:
Run this once, or whenever a policy document changes.
$rag->indexDocument(
'returns.md',
file_get_contents(storage_path('kb/returns.md'))
);
Ask a question:
return $rag->answer(
'I paid cash on delivery and want to return my shoes. How do I get my money back?'
);
Production Considerations
Before deploying this system to production:
- Run
indexDocument()inside a queued job. - Re-index a document whenever it is edited.
- Delete its old chunks before inserting updated chunks.
- For multi-tenant applications, add a
tenant_idcolumn. - Filter by
tenant_idinsideretrieve()to prevent one store's data from leaking into another store's answers.
The Same Idea in Python
You can experiment with the basic RAG retrieval concept using approximately 20 lines of Python.
This example uses NumPy and the OpenAI embeddings API. It keeps the vectors in memory rather than using a vector database.
Install Dependencies
pip install numpy openai
Python Implementation
import numpy as np
from openai import OpenAI
client = OpenAI()
def embed(texts):
res = client.embeddings.create(
model="text-embedding-3-small",
input=texts
)
return np.array([
d.embedding for d in res.data
])
chunks = [
"Items can be returned within 7 days of delivery if unused.",
"Refunds are sent within 5-7 business days after we receive the item.",
"Cash-on-delivery orders are refunded via bKash or bank transfer.",
"Inside Dhaka, delivery takes 1-2 days.",
]
chunk_vecs = embed(chunks)
def retrieve(question, k=3):
q = embed([question])[0]
scores = (
chunk_vecs @ q
/
(
np.linalg.norm(chunk_vecs, axis=1)
* np.linalg.norm(q)
)
)
top = np.argsort(scores)[::-1][:k]
return [
(chunks[i], float(scores[i]))
for i in top
]
for text, score in retrieve(
"I paid cash, how do I get a refund?"
):
print(f"{score:.2f} {text}")
This simple example demonstrates how embeddings and cosine similarity can retrieve relevant information from a collection of documents.
Making RAG Better
The basic pipeline gets you surprisingly far.
However, when answers start missing relevant information, several improvements can help.
| Technique | What It Fixes | How |
|---|---|---|
| Better chunking | Answers cut off mid-thought | Split by headings and paragraphs instead of fixed character counts. Keep the section title in each chunk. |
| Metadata filters | Wrong tenant, product, or outdated document retrieved | Store tenant_id, category, language, and date. Filter before vector search. |
| Hybrid search | Misses exact terms such as SKU codes, order IDs, and product names | Combine keyword search (BM25 / PostgreSQL full-text search) with vector search and merge the rankings. |
| Reranking | The right chunk is in the top 20 but not the top 4 | Retrieve around 20 candidates, re-score them with a cross-encoder or reranker model, and keep the best 4. |
| Query rewriting | Follow-up questions like "and for Chittagong?" lack context | Have the LLM rewrite the question into a standalone query using chat history before retrieval. |
| Evaluation set | You cannot tell whether a change improved the system | Maintain 50–100 real questions with expected answers. Measure retrieval hit rate and answer faithfulness after every change. |
**Of these improvements


Top comments (0)