As an AI engineer intern at BeProEx, I built a retrieval assistant over 2,000+ internal documents. The model was the easy part. Retrieval was not.
Chunk on structure, not tokens
Fixed 512-token windows split rules from their exceptions. I parsed each PDF into a heading tree, chunked it by section and prepended each section’s heading path, so every embedding carries its context.
Retrieval as a pipeline
Each query is expanded into sub-queries, and then dense and BM25 searches run in parallel under the user’s access filter, so nobody retrieves a document they can’t open. Weighted reciprocal rank fusion merges the results, a cross-encoder reranks the top 30 and MMR drops near-duplicates.
async def retrieve(query: str, user: User, k: int = 8) -> list[Chunk]:
acl = Filter(groups__any=user.groups, status="published")
subqueries = await rewriter.expand(query, max_n=3)
async with tracer.span("retrieve", user=user.id) as span:
results = await asyncio.gather(*(
search(q, acl=acl, limit=50)
for q in subqueries
for search in (dense.search, sparse.search)
))
fused = rrf(results, weights=[1.0, 0.7] * len(subqueries), k=60)
top = heapq.nlargest(30, fused, key=fused.get)
candidates = [chunks[i] for i in top]
pairs = [(query, c.text) for c in candidates]
scores = await asyncio.to_thread(
reranker.predict, pairs, batch_size=16
)
span.set("top_score", float(max(scores)))
if max(scores) < settings.min_relevance:
raise NoSourceFound(query)
return mmr(candidates, scores, lambda_=0.7, k=k)
Cite, abstain, measure
Every answer links to the exact page it came from, and weak matches get “I can’t find a source” instead of a guess. Each change to chunking, retrieval or prompts runs against a labeled eval set, and nothing ships if recall@8 drops.