Building
Build a RAG pipeline
Answer questions over your own documents with retrieval-augmented generation: chunking, embeddings, vector search and grounded prompts.
9 min read · Updated November 1, 2026
Retrieval-augmented generation (RAG) lets a model answer questions using your documents instead of only what it learned in training. You retrieve the most relevant passages for each question and include them in the prompt. This guide builds a complete, minimal pipeline in Python, then shows how to improve it.
How RAG works
- Ingest: split documents into chunks.
- Embed: convert each chunk into a vector with an embedding model.
- Store: save vectors and text in a vector database.
- Retrieve: embed the user's question and find the nearest chunks.
- Generate: send the question plus retrieved chunks to a chat model with instructions to answer only from them.
Setup
pip install openai qdrant-client
export AILABSTORE_API_KEY="als_live_..."
We use an in-memory Qdrant instance for the example. In production, point the client at a managed Qdrant instance from Portal → Managed tools (Enterprise) or any Qdrant server.
import os
from openai import OpenAI
from qdrant_client import QdrantClient
from qdrant_client.models import Distance, VectorParams, PointStruct
client = OpenAI(base_url="https://api.ailabstore.cc/v1", api_key=os.environ["AILABSTORE_API_KEY"])
qdrant = QdrantClient(":memory:")
EMBED_MODEL = "openai/text-embedding-3-small" # 1536 dimensions
CHAT_MODEL = "anthropic/claude-sonnet-5.5"
COLLECTION = "docs"
1. Chunk your documents
Chunks should be small enough to be specific but large enough to carry meaning. 500 to 1,000 characters with some overlap is a good starting point.
def chunk(text: str, size: int = 800, overlap: int = 150) -> list[str]:
chunks, start = [], 0
while start < len(text):
end = min(start + size, len(text))
if end < len(text):
# Prefer to break on a paragraph, then a sentence boundary
cut = text.rfind("\n\n", start + size // 2, end)
if cut == -1:
cut = text.rfind(". ", start + size // 2, end)
if cut != -1:
end = cut + 1
chunks.append(text[start:end].strip())
if end >= len(text):
break
start = end - overlap
return [c for c in chunks if c]
For PDFs, Word files and HTML, parse to clean text first. The managed Unstructured tool handles complex layouts and tables.
2. Embed and store
Embed in batches to reduce round trips:
def embed(texts: list[str]) -> list[list[float]]:
resp = client.embeddings.create(model=EMBED_MODEL, input=texts)
return [d.embedding for d in resp.data]
qdrant.create_collection(
COLLECTION,
vectors_config=VectorParams(size=1536, distance=Distance.COSINE),
)
def ingest(doc_id: str, title: str, text: str):
pieces = chunk(text)
vectors = []
for i in range(0, len(pieces), 64):
vectors.extend(embed(pieces[i : i + 64]))
qdrant.upsert(
COLLECTION,
points=[
PointStruct(
id=abs(hash(f"{doc_id}-{i}")) % (2**63),
vector=v,
payload={"doc_id": doc_id, "title": title, "text": p, "chunk": i},
)
for i, (p, v) in enumerate(zip(pieces, vectors))
],
)
Store useful metadata in the payload (title, URL, section, date, access level). You will use it for citations and filtering.
3. Retrieve
def retrieve(question: str, k: int = 5):
[qvec] = embed([question])
hits = qdrant.query_points(COLLECTION, query=qvec, limit=k).points
return [h.payload | {"score": h.score} for h in hits]
4. Generate a grounded answer
The prompt matters as much as retrieval. Tell the model to use only the provided context, cite sources and admit when the answer is not there.
SYSTEM = """You answer questions using only the provided context.
Cite sources as [n] after each claim, where n is the context number.
If the context does not contain the answer, say you don't know.
Be concise."""
def answer(question: str) -> str:
hits = retrieve(question)
context = "\n\n".join(
f"[{i + 1}] ({h['title']})\n{h['text']}" for i, h in enumerate(hits)
)
resp = client.chat.completions.create(
model=CHAT_MODEL,
temperature=0.2,
messages=[
{"role": "system", "content": SYSTEM},
{"role": "user", "content": f"Context:\n{context}\n\nQuestion: {question}"},
],
)
return resp.choices[0].message.content
ingest("handbook", "Employee Handbook", open("handbook.txt").read())
print(answer("How many days of annual leave do new employees get?"))
Improving quality
Once the basic pipeline works, these changes give the largest gains.
Hybrid search
Pure vector search can miss exact terms such as product codes or names. Combine it with keyword (BM25) search. Qdrant, Weaviate and Milvus support hybrid queries; with pgvector you can combine tsvector full-text search and vector distance in SQL.
Reranking
Retrieve more candidates (say 20), then use a reranker to pick the best 5. Rerankers read the question and passage together, so they are more accurate than vector similarity alone.
import json
def rerank(question: str, candidates: list[dict], top_n: int = 5) -> list[dict]:
listing = "\n".join(f"{i}: {c['text'][:400]}" for i, c in enumerate(candidates))
resp = client.chat.completions.create(
model="anthropic/claude-haiku-5.5",
temperature=0,
messages=[{
"role": "user",
"content": f"Question: {question}\n\nPassages:\n{listing}\n\n"
f"Return a JSON array of the {top_n} most relevant passage numbers, best first.",
}],
)
order = json.loads(resp.choices[0].message.content)
return [candidates[i] for i in order if 0 <= i < len(candidates)][:top_n]
hits = rerank(question, retrieve(question, k=20))
Dedicated rerank models such as cohere/rerank-3.5, voyage/rerank-2.5 and jina/jina-reranker-v2 are available in the catalog.
Query rewriting
Conversational follow-ups like "what about part-timers?" retrieve poorly on their own. Ask a small model to rewrite the question into a standalone query using the chat history before retrieving.
Metadata filtering
Filter by department, date or permission level at query time. This improves relevance and prevents users from seeing documents they should not.
Chunking by structure
Split on headings and sections rather than fixed character counts when your documents have structure. Include the section title in each chunk's text to give the embedding more context.
Evaluating your pipeline
Build a small test set of 30 to 50 real questions with known answers, then measure:
- Retrieval hit rate: does the correct chunk appear in the top k?
- Faithfulness: is every claim supported by the context?
- Answer relevance: does the answer address the question?
Libraries such as Ragas and DeepEval automate these metrics, and managed Langfuse or Phoenix let you trace each step in production.
Going further without code
If you prefer a visual approach, Dify, Flowise and Langflow (included in the Builder package) provide drag-and-drop RAG pipelines that connect to AILabStore with the same base URL and key.