The Concept
The offline path: ingestion, chunking, embedding, indexing
The diagram below shows how the offline (batch) path and the online (query-time) path fit together into a single RAG pipeline.
# OFFLINE PATH: runs as a batch job (Airflow DAG, cron, CI/CD)
# Can take hours — runs daily or on-demand when new documents arrive
import openai
import pinecone
from chunker import semantic_chunk
# Step 1: Ingest documents from source (SharePoint, S3, database)
def ingest_documents(source_config):
"""Extract documents from client source systems."""
documents = []
for doc in source_config.list_documents():
documents.append({
"doc_id": doc["id"],
"title": doc["name"],
"content": doc["content"],
"department": doc.get("department", "general"),
"classification": doc.get("classification", "internal"),
"url": doc["url"],
"modified": doc["lastModified"],
})
return documents
# Step 2: Chunk documents (semantic chunking at 512 tokens, 50 overlap)
def chunk_documents(documents, max_tokens=512, overlap_tokens=50):
"""Chunk documents for embedding. Semantic chunking outperforms fixed by 15-25%."""
all_chunks = []
for doc in documents:
chunks = semantic_chunk(
text=doc["content"],
max_tokens=max_tokens,
overlap_tokens=overlap_tokens,
)
for i, chunk in enumerate(chunks):
all_chunks.append({
"chunk_id": f"{doc['doc_id']}_chunk_{i}",
"doc_id": doc["doc_id"],
"content": chunk,
"chunk_index": i,
# Metadata for access control filtering at query time
"department": doc["department"],
"classification": doc["classification"],
"url": doc["url"],
"title": doc["title"],
})
return all_chunks
# Step 3: Embed chunks (batch API for cost efficiency)
def embed_chunks(chunks, model="text-embedding-3-small", batch_size=100):
"""Embed chunks using OpenAI's batch API."""
client = openai.OpenAI()
embeddings = []
for i in range(0, len(chunks), batch_size):
batch = chunks[i:i + batch_size]
texts = [c["content"] for c in batch]
response = client.embeddings.create(
input=texts,
model=model,
dimensions=1536, # text-embedding-3-small supports dimension reduction
)
for j, embedding in enumerate(response.data):
embeddings.append({
"chunk_id": batch[j]["chunk_id"],
"values": embedding.embedding,
"metadata": batch[j],
})
return embeddings
# Step 4: Index embeddings in vector store
def index_embeddings(embeddings, index_name="rag-prod"):
"""Upsert embeddings into Pinecone with metadata for filtering."""
pc = pinecone.Pinecone(api_key="...")
index = pc.Index(index_name)
# Upsert in batches of 100 (Pinecone limit)
for i in range(0, len(embeddings), 100):
batch = embeddings[i:i + 100]
vectors = [
{
"id": e["chunk_id"],
"values": e["values"],
"metadata": e["metadata"],
}
for e in batch
]
index.upsert(vectors=vectors)
return {"indexed": len(embeddings)}
# Full offline pipeline
documents = ingest_documents(source_config)
chunks = chunk_documents(documents, max_tokens=512, overlap_tokens=50)
embeddings = embed_chunks(chunks, model="text-embedding-3-small")
result = index_embeddings(embeddings, index_name="rag-prod")
print(f"Offline path complete: {result['indexed']} chunks indexed")
The online path: query → retrieval → reranking → generation (1-5s SLO)
# ONLINE PATH: must complete in 1-5 seconds (user-facing SLO)
# Every millisecond counts — measure each stage
import time
import openai
def rag_query(user_query, user_permissions, top_k=5):
"""Online RAG path: query → retrieve → rerank → generate. Target: <5s."""
timings = {}
# Stage 1: Embed query (~100ms)
t0 = time.time()
client = openai.OpenAI()
query_embedding = client.embeddings.create(
input=user_query,
model="text-embedding-3-small",
dimensions=1536,
).data[0].embedding
timings["embed_query"] = time.time() - t0
# Stage 2: Vector search with access control filter (~200ms)
t0 = time.time()
index = pinecone.Pinecone(api_key="...").Index("rag-prod")
# Metadata filter enforces access control at retrieval time
# User can only see chunks from their department + non-confidential
filter = {
"department": {"$in": user_permissions["departments"]},
"classification": {"$ne": "confidential"} if not user_permissions["can_see_confidential"] else {"$in": ["internal", "confidential"]},
}
results = index.query(
vector=query_embedding,
top_k=50, # Over-retrieve for reranking
include_metadata=True,
filter=filter, # Access control filtering
)
timings["vector_search"] = time.time() - t0
# Stage 3: Rerank with cross-encoder (~500ms)
t0 = time.time()
from cohere import Client as CohereClient
cohere = CohereClient(api_key="...")
candidates = [match["metadata"]["content"] for match in results["matches"]]
rerank_response = cohere.rerank(
model="rerank-english-v3.0",
query=user_query,
documents=candidates,
top_n=top_k, # Keep only top 5 after reranking
)
reranked = []
for result in rerank_response.results:
match = results["matches"][result.index]
reranked.append({
"content": match["metadata"]["content"],
"score": result.relevance_score,
"url": match["metadata"]["url"],
"title": match["metadata"]["title"],
})
timings["rerank"] = time.time() - t0
# Stage 4: Context assembly (~10ms)
t0 = time.time()
context = assemble_context(reranked, max_tokens=3000)
timings["context_assembly"] = time.time() - t0
# Stage 5: Generate answer (~2-3s)
t0 = time.time()
response = client.chat.completions.create(
model="gpt-6.1-sol",
messages=[
{"role": "system", "content": "Answer based on the provided context. Cite sources. If the context doesn't contain the answer, say so."},
{"role": "user", "content": f"Context:\n{context}\n\nQuestion: {user_query}"},
],
temperature=0.1, # Low temperature for factual answers
max_tokens=500,
)
answer = response.choices[0].message.content
timings["generation"] = time.time() - t0
total = sum(timings.values())
print(f"Total: {total:.2f}s | " + " | ".join(f"{k}: {v:.3f}s" for k, v in timings.items()))
if total > 5.0:
print(f"⚠️ SLO breach: {total:.2f}s > 5.0s target")
return {
"answer": answer,
"sources": [{"url": r["url"], "title": r["title"]} for r in reranked],
"timings": timings,
"total_time": total,
}
def assemble_context(reranked_chunks, max_tokens=3000):
"""Assemble context from reranked chunks, respecting token budget."""
import tiktoken
enc = tiktoken.encoding_for_model("gpt-4")
context_parts = []
token_count = 0
for chunk in reranked_chunks:
chunk_tokens = len(enc.encode(chunk["content"]))
if token_count + chunk_tokens > max_tokens:
break
# Citation format: [1] Title (URL)
citation = f"[{len(context_parts) + 1}] {chunk['title']}"
context_parts.append(f"{citation}\n{chunk['content']}")
token_count += chunk_tokens
return "\n\n---\n\n".join(context_parts)
Choosing and versioning embedding models
# Embedding model selection: trade-offs between cost, quality, and latency
embedding_models = {
"text-embedding-3-small": {
"provider": "OpenAI",
"dimensions": 1536,
"cost_per_1m_tokens": 0.02,
"quality": "Good (MTEB: 62.3)",
"use_when": "Default choice — good quality, low cost, fast",
},
"text-embedding-3-large": {
"provider": "OpenAI",
"dimensions": 3072,
"cost_per_1m_tokens": 0.13,
"quality": "Better (MTEB: 64.6)",
"use_when": "Higher quality needed, budget allows",
},
"embed-english-v3.0": {
"provider": "Cohere",
"dimensions": 1024,
"cost_per_1m_tokens": 0.10,
"quality": "Good (MTEB: 61.0)",
"use_when": "Already using Cohere ecosystem, need multilingual",
},
"voyage-2": {
"provider": "Voyage AI",
"dimensions": 1024,
"cost_per_1m_tokens": 0.10,
"quality": "Best (MTEB: 68.3)",
"use_when": "Quality is critical, proprietary documents",
},
"bge-large-en-v1.5": {
"provider": "Open source (BAAI)",
"dimensions": 1024,
"cost_per_1m_tokens": 0.0, # Self-hosted
"quality": "Good (MTEB: 63.5)",
"use_when": "Data can't leave client environment (on-premise)",
},
}
# Versioning: never change embedding model without re-indexing
# Different models produce incompatible vectors — mixing them breaks search
def migrate_embedding_model(old_model, new_model, index_name):
"""Safely migrate to a new embedding model."""
print(f"Migrating from {old_model} to {new_model}")
print("Steps:")
print(" 1. Create new index: rag-prod-v2")
print(" 2. Re-embed all chunks with new model")
print(" 3. Run eval harness on new index (compare MRR@k)")
print(" 4. If quality improves: switch query path to new index")
print(" 5. Keep old index for 30 days (rollback)")
print(" 6. Delete old index after confidence period")
print("\n⚠️ NEVER mix embeddings from different models in the same index")
Build
Practical application
In the lab, you'll build both the offline and online paths of a RAG pipeline. You'll implement semantic chunking at 512 tokens, embed with OpenAI text-embedding-3-small, index in Pinecone with access control metadata, query with metadata filtering, rerank with Cohere, and generate with GPT-6.1 Sol — all within a 5-second SLO.
Before touching a real vector database, it helps to simulate the context-assembly step in isolation: given a token budget, greedily pack reranked chunks in priority order and stop before you blow the budget.
# Simulate context assembly under a token budget (pure stdlib, no real embeddings)
def fake_token_count(text):
# Rough approximation: ~1 token per 4 characters
return max(1, len(text) // 4)
reranked_chunks = [
{"title": "Q3 Revenue Report", "content": "Total revenue was $12.5M, up 15% YoY." * 3, "score": 0.94},
{"title": "Depreciation Policy", "content": "Assets depreciate straight-line over 5 years." * 3, "score": 0.81},
{"title": "Dress Code Memo", "content": "Business casual Monday through Thursday." * 3, "score": 0.40},
]
def assemble_context(chunks, max_tokens=40):
parts = []
used = 0
for chunk in chunks:
cost = fake_token_count(chunk["content"])
if used + cost > max_tokens:
print(f"Skipping '{chunk['title']}' (score={chunk['score']}) — would exceed budget")
continue
citation = f"[{len(parts) + 1}] {chunk['title']}"
parts.append(f"{citation}\n{chunk['content']}")
used += cost
return "\n---\n".join(parts), used
context, tokens_used = assemble_context(reranked_chunks, max_tokens=40)
print(f"\nAssembled context using {tokens_used} tokens:\n")
print(context)
Your RAG system takes 8 seconds per query. The timings show: embed_query=0.1s, vector_search=0.2s, rerank=0.5s, generation=7.2s. What's the most effective optimization?
Generation is 7.2s out of 8s total (90% of latency). The bottleneck is clearly the LLM generation, not retrieval. Two levers: (1) reduce max_tokens — fewer output tokens means less generation time, and (2) use a faster model for simple queries. GPT-6 Luna costs a twentieth of GPT-6.1 Sol per input token and is built for high-volume, low-latency work, and for straightforward factual questions it performs nearly as well. A query router can classify query complexity and route simple queries to the fast model. Switching embedding models saves 0.1s — irrelevant when generation takes 7.2s. Reducing top_k affects retrieval quality, not generation speed (the model processes whatever context you give it). More context would slow generation further.