AI Agent RAG Pipeline Tutorial 2026

🤖 Agents 2026-07-16 · Updated 2026-11-10 4 min read

An LLM's knowledge stops at its training cutoff, while your manuals change weekly. RAG lets an agent look things up before answering. This walks through chunking, indexing, retrieval, tool wiring and evaluation.

📜 Table of Contents

📖 Keep reading

Building an Agent + RAG Pipeline: Teaching Your Agent to Read Your Docs

An LLM knows what it was trained on. Product manuals and internal policies change every week, and stuffing them all into a prompt is not viable. Retrieval-augmented generation fixes this: search the document store first, then hand the relevant chunks to the model with the question.

This guide follows the engineering order: chunking, indexing, retrieval, tool wiring, evaluation. Code targets LangChain 0.3 with local Chroma; swap in any vector store later.

1. Four stages, four failure modes

Stage Input Output Symptom when broken
Chunking Raw documents Chunks Answers cut off mid-sentence
Indexing Chunks Vectors + metadata Zero recall
Retrieval Question Top-k chunks Found, but irrelevant
Generation Question + chunks Answer + citations Made-up content

Most failed projects break at chunking, not at the model.

2. Setup

python -m venv .venv && source .venv/bin/activate
pip install -U langchain langchain-community langchain-openai \
    langchain-text-splitters langchain-chroma chromadb \
    rank-bm25 sentence-transformers

Since LangChain 0.2, splitters live in the separate langchain-text-splitters package. Older imports of langchain.text_splitter are deprecated and fail on some versions. Same for langchain_chroma.

3. Chunking

from langchain_community.document_loaders import PyPDFLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter

docs = PyPDFLoader("manual.pdf").load()
splitter = RecursiveCharacterTextSplitter(
    chunk_size=500, chunk_overlap=80,
    separators=["\n\n", "\n", "。", "!", "?", " ", ""],
)
chunks = splitter.split_documents(docs)

For Chinese text, add full-width punctuation to the separators or sentences get cut in half.

chunk_size (chars) Best for Cost
200-300 FAQs, bullet lists Too little context, model guesses
400-600 Manuals, general docs Needs reranking
800-1200 Papers, long prose High recall, more noise

Use 10-20% overlap. Keep tables and code blocks intact; splitting them mid-row makes them useless.

4. Build the index, keep a keyword path

from langchain_openai import OpenAIEmbeddings
from langchain_chroma import Chroma

emb = OpenAIEmbeddings(model="text-embedding-3-small")
vs = Chroma(persist_directory="./chroma", embedding_function=emb)
vs.add_documents(chunks)

Embedding dimensions and pricing follow the official docs. Changing models means rebuilding the index; never mix vector spaces.

Dense retrieval is weak on part numbers and error codes. Add BM25 and fuse the two lists with reciprocal rank fusion:

from langchain_community.retrievers import BM25Retriever
from langchain.retrievers import EnsembleRetriever

hybrid = EnsembleRetriever(
    retrievers=[BM25Retriever.from_documents(chunks, k=4),
                vs.as_retriever(search_kwargs={"k": 4})],
    weights=[0.4, 0.6],
)

For Chinese corpora, tokenize before building BM25. Whitespace splitting degrades recall badly.

5. Expose retrieval as a tool

from langchain_core.tools import tool

@tool
def search_manual(query: str) -> str:
    """Search the product manual for features, specs, error codes and procedures."""
    hits = hybrid.invoke(query)
    if not hits:
        return "No relevant content found. Tell the user honestly."
    return "\n\n".join(
        f"[{d.metadata.get('source','?')} p{d.metadata.get('page','?')}]\n{d.page_content}"
        for d in hits[:4]
    )

Two rules pay off immediately: include source and page in the returned text, and return an explicit "not found" instead of an empty string.

6. Three things before launch

  1. Evaluation set: 50-100 real questions with the correct source document labeled. Track Recall@4 and faithfulness on every change.
  2. Reranking: retrieve top-20, rerank with a cross-encoder, pass top-3 to the model. Usually a bigger win than a larger generator.
  3. Citations: every answer must link back to the source. Without it there is no acceptance criterion and no way to debug.

FAQ

Scanned PDFs return no text? Run OCR or layout parsing first; text-layer loaders return blanks.

The answer is in the docs but the model says it does not know? Check chunk completeness, print top-k, then check whether context truncation dropped the hit.

Do I need a vector database? A few thousand chunks run fine in memory with Chroma or FAISS. Move to Qdrant or Milvus when you need multi-tenant isolation and incremental updates.

Can this run fully local? Yes, with a local embedding model such as bge-m3 plus a local LLM. The trade-off is hardware and latency.

Related

Related Articles
2026-07-16
Choosing an Open Source RAG Stack in 2026: Three Categories, Eight Projects
2026-07-20
AI Agent Best Practices 2026: Design Patterns for Reliable Autonomous Systems
2026-07-16
AI Agent User Feedback Loop 2026
2026-08-31
Spent a week doing dirty work with Doubao Seed Evolving: A hands-on report from a veteran Agent user
2026-07-17
AI Agent CI CD Pipeline 2026
2026-07-19
Self-Hosted AI Agent Platform: Build Your Private AI Assistant

Written by our editorial team; tools listed here are tested or verified against public sources. Links point to official sites or GitHub repos for reference only — no paid placements.

💬 Comments (0)

No comments yet. Be the first!

Login to comment