Skip to main content
Coderhives
Artificial IntelligenceOct 18, 20267 min read

What Is RAG and How Does It Work?

A clear engineering walkthrough of Retrieval-Augmented Generation: chunking, embeddings, vector search, reranking, and grounded LLM responses.

AI

Coderhives AI Lab

Applied ML Engineering

#RAG#LLMs#Vector Search#AI Systems
What Is RAG and How Does It Work?

Why Plain LLMs Are Not Enough for Company Data

Large Language Models are trained on broad public snapshots and do not natively know your private product documentation, internal SOPs, or yesterday's policy updates. Asking an ungrounded model about proprietary facts often leads to confident hallucinations.

Retrieval-Augmented Generation (RAG) solves this by fetching relevant, up-to-date context from your own knowledge base at query time and injecting it into the model's prompt.

The Two Core Pipelines: Indexing and Retrieval

A production RAG system operates in two distinct stages: an offline ingestion pipeline that prepares documents, and an online query pipeline that retrieves and synthesizes answers.

  • 1. Load & Clean: Extract text from Markdown, PDFs, or database records while preserving headings.
  • 2. Chunking: Split long documents into semantically coherent segments (typically 300–600 tokens with overlap).
  • 3. Embeddings: Convert each chunk into dense numerical vectors representing semantic meaning.
  • 4. Hybrid Search + Rerank: Combine vector similarity with keyword (BM25) matching for exact terms and IDs.
  • 5. Grounded Generation: Instruct the LLM to answer strictly from retrieved passages and cite sources.
tslib/rag-pipeline.ts
export async function answerWithRag(question: string) {
  const queryVector = await embedText(question);
  const passages = await hybridSearch({ query: question, vector: queryVector, topK: 5 });

  const context = passages
    .map((p, idx) => `[Source ${idx + 1}: ${p.title}]\n${p.content}`)
    .join("\n\n");

  return generateGroundedAnswer({ question, context });
}

Measuring Retrieval Accuracy Before Tuning Prompts

Most RAG failures are retrieval failures, not LLM failures. If the right paragraph never reaches the context window, prompt engineering cannot rescue the answer. Always track recall@K, citation accuracy, and latency across a curated evaluation set.

Keep Reading

Related Engineering Guides

View All Articles
Ready When You Are

Have an Idea? Let's Build Something Amazing.

Whether you're launching a new product or modernizing an existing system, we're ready to help.