Zero Labs
Industry News / AI

Building a Knowledge Assistant with RAG and Python

Source · Towards AI By Anwar

From the publisher’s feed, collected in the ZeroLabs newsroom.

A knowledge assistant built with RAG and Python retrieves relevant passages from internal documents to generate answers supported by traceable sources.1. The Challenge: Information Overload Across Internal DocumentationDuring a critical production incident, a support team must navigate scattered internal PDF standard operating procedures (SOPs) and Markdown technical documentation to execute recovery workflows. An incident commander facing an active service disruption might issue a time-sensitive operational query:“What is the escalation procedure when a critical incident remains unresolved?”Locating the authoritative response across disjointed repositories under time constraints introduces severe operational delay. Large Language Models (LLMs) excel at linguistic synthesis and cognitive processing, yet relying on raw foundation models for internal technical inquiries exposes three structural failure modes:Lack of Private Data Access: Foundation models are trained exclusively on pre-existing public datasets. They possess zero intrinsic visibility into private corporate repositories, internal wiki pages, or proprietary SOPs unless explicitly provided in the request payload.Context Window Bounds and Economics: Although theoretical context limits have expanded, stuffing entire documentation repositories into a single prompt is computationally inefficient, drastically elevates processing latency, and incurs prohibitive token API costs.Hallucination Under Uncertainty: When an LLM lacks ground-truth information, its autoregressive objective favors generating statistically plausible but factual nonsense (hallucinations) rather than executing a hard abstention.Retrieval-Augmented Generation (RAG) resolves these limitations by decoupling knowledge storage from model parameter weights. RAG dynamically retrieves precise evidence passages from an external index and binds them into the model’s prompt context at query time.[ User Query ] ---> [ Search Index ] ---> [ Fetch Context Chunks ] |[ Grounded Response ] Context Economics and System ScopeInserting external evidence into an LLM prompt consumes context capacity, increasing API request charges and processing latency. Crucially, populating context space with retrieved text does not guarantee generation accuracy; models can misinterpret provided evidence, succumb to middle-of-the-prompt attention degradation, or ignore context constraints.RAG vs. Direct Prompting: For trivial document sets that easily fit within a standard context window, direct context insertion without indexing infrastructure is often sufficient. RAG becomes mandatory when document volume exceeds practical context budgets or when retrieval efficiency across thousands of files is required.RAG vs. Fine-Tuning: Fine-tuning alters static model parameter weights to adjust style, tone, or specific formatting rules. Fine-tuning does not dynamically inject up-to-date internal document context and cannot guarantee factual grounding. RAG dynamically fetches up-to-date, external document passages at query time, keeping answers strictly aligned with live documentation.Note: The architecture presented here represents an illustrative conceptual design model for context-grounded document assistants, rather than a claims-based report of a deployed, benchmarked production system.2. Architectural Framework: Decoupling Ingestion from Question AnsweringA production-grade RAG system separates data preparation from real-time execution by decoupling into two discrete pipelines: an offline Indexing Pipeline and an online Question-Answering Pipeline.=================================================================================OFFLINE INDEXING PIPELINE=================================================================================[ PDF / MD Files ] -> [ Loading & Chunking ] -> [ Metadata Enrichment ] -> [ Embeddings & Vector Index ]=================================================================================ONLINE QUESTION-ANSWERING PIPELINE=================================================================================[ User Query ] -> [ Hybrid Search & Filtering ] -> [ Reranking ] -> [ LLM Generation / Structured Output ]Sequential Pipeline StagesLoading & Chunking: Ingesting PDF and Markdown files and splitting text into discrete segments using document-aware splitting logic to prevent contextual fragmentation across chunk boundaries.Metadata Enrichment: Attaching critical metadata — such as doc_id, page_number, section_header, version, and access tier—to each text chunk to support deterministic filtering prior to vector distance calculations.Embedding & Vector Indexing: Mapping text chunks into numerical vector spaces using an embedding model and indexing them inside a vector store (e.g., Chroma or PostgreSQL with pgvector).Retrieval & Context Assembly: Converting incoming user queries into vector representations, executing similarity and lexical searches, applying metadata filters, and assembling top candidate passages into an explicit context payload.Generation: Constructing a constrained prompt containing retrieved evidence chunks, submitting it to a foundation model, and enforcing strict inline citations or explicit abstention triggers.3. Python Walkthrough: End-to-End Conceptual ImplementationThe following conceptual Python walkthrough models an end-to-end RAG application. System secrets and API credentials are loaded dynamically from environment files via .env.Environment Management & Client Initialization# Dependency Requirements: python-dotenv, chromadb, openai, pydanticimport osfrom dotenv import load_dotenvimport openai# Load API credentials securely from local environmentload_dotenv()openai_client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY"))Step 1: Document Loading & Document-Aware ChunkingSimulating document-aware text splitting that respects structural headers (#, ##) and paragraph breaks before enforcing character limits.# Pseudocode / Conceptual Pythonimport refrom typing import List, Dict, Anydef load_and_chunk_document(file_path: str, doc_id: str, version: str) -> List[Dict[str, Any]]: """ Parses Markdown/PDF source text using document-aware boundaries (headers/paragraphs) to minimize chunk boundary contextual fragmentation. """ raw_text = fake_document_reader(file_path) # Split primary text by top-level Markdown section headers sections = re.split(r'\n(?=# )', raw_text) chunks = [] for page_idx, section_text in enumerate(sections, start=1): # Determine active section header header_match = re.search(r'^#+\s+(.*)', section_text) current_section = header_match.group(1) if header_match else "General Protocols" # Sub-split lengthy sections by double newlines to keep paragraph semantic coherence paragraphs = section_text.split("\n\n") current_chunk = "" for para in paragraphs: if len(current_chunk) + len(para) current_chunk += para + "\n\n" else: if current_chunk.strip(): chunks.append({ "text": current_chunk.strip(), "metadata": { "doc_id": doc_id, "version": version, "page_number": page_idx, "section": current_section } }) current_chunk = para + "\n\n" if current_chunk.strip(): chunks.append({ "text": current_chunk.strip(), "metadata": { "doc_id": doc_id, "version": version, "page_number": page_idx, "section": current_section } }) return chunksdef fake_document_reader(file_path: str) -> str: return ( "# SOP-101: Critical Incident Escalation\n\n" "If an unresolved SEV-1 ticket sits stale for >15 mins, notify the Incident Commander.\n\n" "## Technical Escalation Paths\n\n" "Escalate directly to On-Call Infrastructure Lead via PagerDuty priority channel." )Step 2: Vector Store Embedding & IndexingPersisting document embeddings and structural metadata inside a vector database.# Pseudocode / Conceptual Pythonimport chromadbdef initialize_vector_index(chunks: List[Dict[str, Any]], collection_name: str) -> Any: """ Indexes document chunks alongside structured metadata attributes in Chroma. """ # Initialize persistent Chroma client instance chroma_client = chromadb.PersistentClient(path="./chroma_db") collection = chroma_client.get_or_create_collection(name=collection_name) documents = [c["text"] for c in chunks] metadatas = [c["metadata"] for c in chunks] ids = [f"{c['metadata']['doc_id']}_chunk_{i}" for i, c in enumerate(chunks)] collection.add( documents=documents, metadatas=metadatas, ids=ids ) return collectionStep 3: Retrieval & Deterministic Metadata FilteringQuerying an existing collection instance with structural metadata scoping.# Pseudocode / Conceptual Pythondef retrieve_relevant_context( query: str, collection: Any, target_version: str, top_k: int = 3) -> List[Dict[str, Any]]: """ Executes similarity search on an existing collection, applying hard scope filters. """ results = collection.query( query_texts=[query], n_results=top_k, where={"version": target_version} # Hard filter restricting query scope to current version ) retrieved_passages = [] if results and "documents" in results and results["documents"]: for doc, meta in zip(results["documents"][0], results["metadatas"][0]): retrieved_passages.append({ "text": doc, "metadata": meta }) return retrieved_passagesStep 4: Grounded Generation with Explicit Abstention and Structured OutputsPassing context blocks into an LLM with strict citation guidelines and programmatic Pydantic output schemas.# Pseudocode / Conceptual Pythonfrom pydantic import BaseModel, Fieldclass CitationAnswerSchema(BaseModel): answer: str = Field(description="The factual answer grounded strictly in context.") citations: List[str] = Field(description="Exact document IDs and page numbers used.") has_sufficient_evidence: bool = Field(description="False if retrieved context was insufficient.")def generate_grounded_answer( user_query: str, retrieved_context: List[Dict[str, Any]], client: openai.OpenAI) -> CitationAnswerSchema: """ Generates a citation-backed response using OpenAI SDK Structured Outputs with Pydantic. """ context_blocks = [] for idx, item in enumerate(retrieved_context): m = item["metadata"] block = f"[Source {idx+1}] Doc: {m['doc_id']} (Page {m['page_number']}, Section: {m['section']})\nContent: {item['text']}" context_blocks.append(block) formatted_context = "\n\n".join(context_blocks) system_prompt = ( "You are an enterprise knowledge assistant. Answer queries using ONLY the provided Context Blocks.\n" "For every statement, include an inline citation matching [Source X].\n" "If context is insufficient, set has_sufficient_evidence to False and abstain." ) user_payload = f"Context Blocks:\n{formatted_context}\n\nQuery: {user_query}" # Utilizing Structured Outputs (Chapter 2.7) for programmatic guarantees completion = client.beta.chat.completions.parse( model="gpt-4o", messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_payload} ], response_format=CitationAnswerSchema, temperature=0.0 ) return completion.choices[0].message.parsedEngineering Note on Programmatic Guarantees: Prompt instructions requiring an LLM to abstain when context is absent reduce hallucination frequency, but do not provide a deterministic safety guarantee. To enforce programmatic reliability, engineers must pair system prompts with Pydantic structured output validation schemas via the OpenAI SDK (Chapter 2.7) and enforce secondary evaluation guardrails.4. Navigating Failures, Reliability, and Architectural TradeoffsCommon Failure Modes Across the RAG PipelineExtraction & Parsing Failures: Complex PDF structures, multi-column layouts, and nested tables lose visual hierarchy during text extraction, leading to garbled text streams.Chunking Pitfalls: Arbitrary character slicing triggers chunk boundary contextual fragmentation, severing core entity relationships across separate chunks.Retrieval Failures: Pure vector similarity suffers from vector space drift, missing exact alphanumeric codes (e.g., SEV-1, SOP-101) when query terms sit outside dense embedding clusters.Data Quality Degradation: Duplicate files, unindexed revisions, or obsolete SOP versions coexisting in the knowledge base pollute search spaces and surface conflicting evidence.Generation Failures: Autoregressive models may ignore provided context blocks, invent facts under high temperature settings, or fail to output standardized citation tags.Advanced Retrieval Mitigation StrategiesTo resolve structural retrieval limitations, production architectures integrate advanced patterns detailed across Chapter 7 of the source context:Hybrid Search (Lexical + Dense Vector)Dense vector search maps broad semantic intent but struggles with exact alphanumeric strings or proprietary technical error codes. Hybrid search executes parallel sparse lexical searches (e.g., BM25 or PostgreSQL tsvector text matching) and dense vector searches, merging score distributions via Reciprocal Rank Fusion (RRF).Metadata ScopingApplying deterministic metadata filters restricts search boundaries prior to computing vector similarity. By filtering across attributes like version, access_tier, or doc_type, systems eliminate deprecated procedure versions and enforce row-level security constraints without degrading search accuracy.Cross-Encoder RerankingInitial similarity retrieval fetched via bi-encoder vector distance prioritized computational speed over deep semantic interaction. Passing top-k candidate passages through a heavy Cross-Encoder model re-scores passage relevance against the user prompt. Tradeoff: Significantly elevates retrieval relevancy, but adds measurable latency and cross-encoder compute overhead to request cycles.Auto-Merging RetrieversTo prevent splitting large context blocks while preserving search accuracy, Auto-Merging Retrievers (Chapter 7.5) store granular child chunks (e.g., 100 tokens) for vector indexing. During retrieval, if the system fetches a designated threshold of child chunks originating from the same parent block, it automatically merges them back into the parent document block before prompt assembly.Sentence Window RetrievalSentence Window Retrieval (Chapter 7.6) decouples the text segment used for vector matching from the text segment supplied to the generation model. The database indexes individual sentences as dense vectors to maximize semantic similarity precision. Upon retrieval, the system automatically fetches a surrounding window of sentences (e.g., ± 3 sentences) around the target hit, supplying full context to the model.Hypothetical Document Embeddings (HyDE)When incoming user prompts are short or abstract, vector similarity distances between the query and target document passages may fail to align. HyDE (Chapter 7.2) uses an LLM to generate a hypothetical ideal document answer. The system then embeds this synthetic document and uses its vector representation to search the vector database, bridging the semantic gap between short queries and detailed document passages.Empirical Parameter TuningHyperparameters cannot be copied blindly from template designs. Parameters such as chunk sizes, overlap ratios, top-k candidate counts, cross-encoder score thresholds, and similarity metrics (cosine vs. inner product) must be empirically calibrated using automated offline evaluation suites against domain-specific documents.5. Systematic Evaluation: Measuring Retrieval and GenerationEvaluating RAG system performance requires decoupling Retrieval Quality (verifying whether correct context was fetched) from Generation Quality (verifying whether the model synthesized answers accurately).Decoupled Quality MetricsRetrieval Metrics:Context Precision@k (Chapter 10.4): Measures whether retrieved context chunks are relevant to the query and whether relevant chunks rank near the top of the context window.Context Recall: Evaluates whether all factual evidence components necessary to answer the query were successfully fetched from the database.Generation Metrics:Faithfulness (Chapter 10.5): Evaluates via LLM-as-a-judge patterns whether every individual assertion in the generated answer is directly derived from the provided context blocks.Answer Relevancy (Chapter 10.6): Quantifies how directly the generated output addresses the user query without straying into extraneous information.Automated Testing via Synthetic Data GenerationManually annotating golden evaluation datasets is time-consuming and difficult to scale as documentation evolves. In alignment with Chapter 10.3, engineering teams utilize LLMs to automate testing dataset generation.By passing chunked document segments to an offline LLM, the model generates synthetic query-context pairs, hypothetical questions, and ground-truth answers for each chunk. These synthetic test pairs form a baseline validation benchmark, enabling continuous automated computation of Context Precision@k and Faithfulness metrics across pipeline revisions without manual labeling overhead.Illustrative Evaluation Test CasesTable 1: Illustrative evaluation test casesNon-Functional Engineering TradeoffsCitation & Evidence Accuracy vs. System Latency: Multi-stage retrieval, cross-encoder reranking, and HyDE transformations maximize context precision and response faithfulness, but accumulate processing latency that can impact user experience.Top-k Payload Volume vs. Inference API Costs: Expanding top-k context payload sizes maximizes context recall, but directly increases prompt token volume, driving up per-query inference costs and reducing generation throughput.6. Production Considerations & Actionable Next StepsTransitioning a Python proof-of-concept into a reliable production system requires addressing core operational engineering requirements:Data Lifecycle & Invalidation: Implement dynamic synchronization between source document repositories and vector databases. When internal documentation is modified or purged, associated embeddings and parent/child index entries must be re-indexed or invalidated to prevent serving stale information.Access Control & Sensitive Data: Enforce row-level and chunk-level Access Control Lists (ACLs). Access filtering rules corresponding to user authorization tiers must execute alongside similarity searches to prevent unauthorized information disclosure.Security Guardrails & Prompt Injection: Secure retrieval and generation endpoints against prompt injection attacks. Indirect prompt injection can occur if retrieved third-party or user-generated text chunks contain adversarial instructions designed to hijack model outputs.Observability & Continuous Monitoring: Deploy continuous tracing across both pipelines. Track input prompts, retrieved context blocks, similarity score distributions, token usage costs, request latencies, and generation drift over time using telemetry frameworks.Actionable Next StepsEngineering teams should begin by defining a tightly bounded document collection and establishing an evaluation dataset combining synthetic test cases with human-verified queries. Establish baseline scores for context precision and faithfulness, then iteratively optimize the weakest pipeline stage, whether by adjusting chunk splitting boundaries, implementing hybrid search with metadata filters, or adding cross-encoder reranking.7. ReferencesDhyani, D. (2026). RAG with Python cookbook. BPB Publications. https://bpbonline.com/products/rag-with-python-cookbook⁠Dhyani, D. (2026). RAG with Python cookbook. BPB Publications (accessed by Helion). https://helion.pl/ksiazki/rag-with-python-cookbook-deepak-dhyani,e_4tsr.htm⁠Kulkarni, S. S. (n.d.). Building reliable RAG applications: From PoC to production [Online course]. O’Reilly Media. https://www.oreilly.com/live-events/building-reliable-rag-applications-from-poc-to-production/0642572012347/⁠Polzer, D. (2026). Foundation models. Dalam RAG with Python cookbook (Bab 2). O’Reilly Media. https://www.oreilly.com/library/view/rag-with-python/9798341600553/ch02.html⁠Polzer, D. (2026). Getting started with RAG. Dalam RAG with Python cookbook (Chapter 1). O’Reilly Media. https://www.oreilly.com/library/view/rag-with-python/9798341600553/ch01.html⁠Building a Knowledge Assistant with RAG and Python was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.