<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Oyedunni Oyewumi on Medium]]></title>
        <description><![CDATA[Stories by Oyedunni Oyewumi on Medium]]></description>
        <link>https://medium.com/@oyedunniwumi3?source=rss-d4789e5133f3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*dLqp_aXLSidx_z1A</url>
            <title>Stories by Oyedunni Oyewumi on Medium</title>
            <link>https://medium.com/@oyedunniwumi3?source=rss-d4789e5133f3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 16:21:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@oyedunniwumi3/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[I built a RAG system from scratch as a data scientist. Here’s Exactly How]]></title>
            <link>https://medium.com/@oyedunniwumi3/i-built-a-rag-system-from-scratch-as-a-data-scientist-heres-exactly-how-c27bdc0d7476?source=rss-d4789e5133f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c27bdc0d7476</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Oyedunni Oyewumi]]></dc:creator>
            <pubDate>Sat, 21 Mar 2026 13:50:50 GMT</pubDate>
            <atom:updated>2026-03-21T13:53:42.936Z</atom:updated>
            <content:encoded><![CDATA[<p><em>An honest, step-by-step walkthrough of building a document intelligence app with Gemini, ChromaDB, and Streamlit, including every mistake I made along the way.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wa-A-Vz0Nvy0E1MHIElsVw.png" /></figure><p>I am not a senior engineer. I don’t have years of production AI experience. I’m a data scientist actively transitioning into AI engineering, and a few days ago I deployed a fully working RAG-powered document intelligence app to the internet.</p><p>You can upload any document to it, a PDF, a Word file, a CSV, anything. Ask it questions in plain English, and get accurate, grounded answers sourced directly from your document.</p><p>This article is not a sanitised tutorial where everything works first try, but an honest account of what I built, how I built it, what broke, and how I fixed it.</p><p>By the end of this, you will have built the same thing.</p><h3>First, What Even Is RAG?</h3><p>Before we write a single line of code, you need to understand what we’re building and why.</p><p><strong>RAG stands for Retrieval-Augmented Generation.</strong></p><p>Here’s the simplest analogy I know: Imagine a brilliant friend, let’s call her Ada. Ada is incredibly smart, went to the best schools, and can talk confidently about almost any topic. But Ada graduated two years ago and hasn’t read anything new since. So if you ask her about your personal documents, or anything recent, she either makes something up or admits she doesn’t know.</p><p>Now imagine Ada has a research assistant, let’s call him Femi. Every time you ask Ada a question, Femi runs to your filing cabinet, finds the 3 most relevant pages, and hands them to Ada. Ada reads those pages and answers your question based on what’s actually written there.</p><p><strong>That combination: Ada’s intelligence + Femi’s retrieval = RAG.</strong></p><p>The LLM (Gemini, in our case) is Ada. The retrieval system is Femi. Instead of relying on what the model memorised during training, you give it exactly the information it needs at the moment of the question.</p><p>This matters because:</p><ul><li>LLMs have a knowledge cutoff — they don’t know about recent events or your personal files</li><li>LLMs hallucinate — when they don’t know something, they sometimes make up a confident answer</li><li>RAG fixes both problems by grounding every answer in your actual documents</li></ul><h3>The Architecture</h3><p>The system has two distinct phases:</p><p><strong>Phase 1 — Ingestion (happens once):</strong> Document → Extract text → Split into chunks → Convert to vectors → Store in ChromaDB</p><p><strong>Phase 2 — Query (happens every time a user asks):</strong> Question → Convert to vector → Find similar chunks → Send chunks + question to LLM → Answer</p><p>Let’s build each piece.</p><h3>Project Setup</h3><p>First, create your project and install dependencies:</p><pre>mkdir rag-document-intelligence<br>cd rag-document-intelligence<br>python -m venv venv<br>venv\Scripts\activate  # Windows<br># source venv/bin/activate  # Mac/Linux</pre><pre>pip install streamlit google-genai chromadb pdfplumber \ python-docx python-dotenv pandas beautifulsoup4 openpyxl</pre><p>Create a .env file with your Gemini API key (get one free at aistudio.google.com):</p><pre>GOOGLE_API_KEY=your_key_here</pre><p>Add this to .gitignore — never push your API key to GitHub:</p><pre>venv/<br>.env<br>__pycache__/<br>chroma_db/<br>uploads/</pre><p>Your project structure:</p><pre>rag-document-intelligence/<br>├── uploads/<br>├── app.py<br>├── loader.py<br>├── chunker.py<br>├── embedder.py<br>├── retriever.py<br>├── .env<br>└── .gitignore</pre><h3>Stage 1: The Document Loader</h3><p>The loader’s job is simple: take any file path, return clean text. I built a router that detects the file type and dispatches to the right parser.</p><pre># loader.py<br>import os<br>from pathlib import Path</pre><pre>def load_document(file_path: str) -&gt; str:<br>    ext = Path(file_path).suffix.lower()</pre><pre>    if ext == &quot;.pdf&quot;:<br>        return load_pdf(file_path)<br>    elif ext == &quot;.docx&quot;:<br>        return load_docx(file_path)<br>    elif ext == &quot;.txt&quot; or ext == &quot;.md&quot;:<br>        return load_txt(file_path)<br>    elif ext == &quot;.csv&quot;:<br>        return load_csv(file_path)<br>    elif ext == &quot;.html&quot;:<br>        return load_html(file_path)<br>    else:<br>        raise ValueError(f&quot;Unsupported file type: {ext}&quot;)</pre><pre>def load_pdf(path):<br>    import pdfplumber<br>    text = &quot;&quot;<br>    with pdfplumber.open(path) as pdf:<br>        for page in pdf.pages:<br>            page_text = page.extract_text(x_tolerance=2, y_tolerance=2)<br>            if page_text:<br>                text += page_text + &quot;\n&quot;<br>    return text</pre><pre>def load_docx(path):<br>    from docx import Document<br>    doc = Document(path)<br>    return &quot;\n&quot;.join(para.text for para in doc.paragraphs if para.text.strip())</pre><pre>def load_txt(path):<br>    with open(path, &quot;r&quot;, encoding=&quot;utf-8&quot;) as f:<br>        return f.read()</pre><pre>def load_csv(path):<br>    import pandas as pd<br>    df = pd.read_csv(path)<br>    return df.to_string(index=False)</pre><pre>def load_html(path):<br>    from bs4 import BeautifulSoup<br>    with open(path, &quot;r&quot;, encoding=&quot;utf-8&quot;) as f:<br>        soup = BeautifulSoup(f.read(), &quot;html.parser&quot;)<br>    return soup.get_text(separator=&quot;\n&quot;)</pre><p><strong>The mistake I made here:</strong> I originally used pypdf instead of pdfplumber. When I tested it on my Statement of Purpose PDF, the output looked like this:</p><pre>STATEMENTOFPURPOSEFORMASTERSINDATASCIENCE<br>Myjourneytowardsacareer inDataSciencehasbeenagradual</pre><p>Every word was clumped together with no spaces. This happens because some PDFs don’t embed proper spacing at the character level — pypdf extracts the raw characters without reconstructing the spacing. pdfplumber handles this much better, using tolerance parameters to correctly merge adjacent characters into words.</p><p>After switching to pdfplumber, the same PDF returned:</p><pre>STATEMENT OF PURPOSE<br>FOR MASTERS IN DATA SCIENCE<br>My journey towards a career in Data Science has been<br>a gradual yet purposeful exploration.</pre><p><strong>Lesson:</strong> Always test your document loader on real files before moving forward. What works in theory often breaks on real-world PDFs.</p><h3>Stage 2: The Chunker</h3><p>Once you have clean text, you can’t store the whole document as one block. Imagine a 100-page contract, if someone asks about the termination clause, you don’t want to send all 100 pages to the LLM. You want to send just the relevant 3 paragraphs.</p><p>Chunking splits text into smaller, overlapping passages:</p><pre># chunker.py<br>def chunk_text(text: str, chunk_size: int = 500, overlap: int = 50) -&gt; list[str]:<br>    chunks = []<br>    start = 0</pre><pre>    while start &lt; len(text):<br>        end = start + chunk_size<br>        chunk = text[start:end]</pre><pre>        if chunk.strip():<br>            chunks.append(chunk.strip())</pre><pre>        start = end - overlap</pre><pre>    return chunks</pre><p><strong>Why overlap matters:</strong> Without overlap, a sentence split across a chunk boundary loses context. With 50 characters of overlap, the end of one chunk and the start of the next share content, so key information is always preserved in at least one complete chunk.</p><h3>Stage 3: Embeddings and Vector Storage</h3><p>This is the most conceptually important stage. Read this carefully.</p><p><strong>What is an embedding?</strong></p><p>An embedding converts text into a list of numbers — a vector. This vector captures the <em>meaning</em> of the text, not just the words. Text with similar meaning gets similar vectors, even if the words are completely different.</p><p>Think of every piece of text as a point on a map. Happy things cluster in one corner. Legal things in another. Sports things somewhere else. When you ask a question, your question also becomes a point on the map. The system finds the text points closest to your question point. That’s semantic search.</p><p>This is why “When can I terminate the contract?” will find the clause about “conditions for dissolution of agreement”. They mean the same thing, even though they share no words.</p><pre># embedder.py<br>import os<br>import chromadb<br>from dotenv import load_dotenv<br>from google import genai<br>from google.genai import types</pre><pre>load_dotenv()</pre><pre>try:<br>    import streamlit as st<br>    api_key = st.secrets[&quot;GOOGLE_API_KEY&quot;]<br>except Exception:<br>    api_key = os.getenv(&quot;GOOGLE_API_KEY&quot;)</pre><pre>client_ai = genai.Client(api_key=api_key)</pre><pre>try:<br>    import streamlit as st<br>    st.secrets[&quot;GOOGLE_API_KEY&quot;]<br>    client_db = chromadb.EphemeralClient()<br>except Exception:<br>    client_db = chromadb.PersistentClient(path=&quot;./chroma_db&quot;)<br></pre><pre>def embed_and_store(chunks: list[str], collection_name: str = &quot;documents&quot;):<br>    try:<br>        client_db.delete_collection(name=collection_name)<br>    except Exception:<br>        pass</pre><pre>    collection = client_db.get_or_create_collection(name=collection_name)</pre><pre>    for i, chunk in enumerate(chunks):<br>        result = client_ai.models.embed_content(<br>            model=&quot;models/gemini-embedding-2-preview&quot;,<br>            contents=chunk,<br>            config=types.EmbedContentConfig(task_type=&quot;RETRIEVAL_DOCUMENT&quot;)<br>        )<br>        collection.add(<br>            documents=[chunk],<br>            embeddings=[result.embeddings[0].values],<br>            ids=[f&quot;chunk_{i}&quot;]<br>        )</pre><pre>    print(f&quot;Done! {len(chunks)} chunks stored.&quot;)<br></pre><pre>def embed_query(query: str) -&gt; list[float]:<br>    result = client_ai.models.embed_content(<br>        model=&quot;models/gemini-embedding-2-preview&quot;,<br>        contents=query,<br>        config=types.EmbedContentConfig(task_type=&quot;RETRIEVAL_QUERY&quot;)<br>    )<br>    return result.embeddings[0].values</pre><p><strong>Three things to notice:</strong></p><ol><li>I delete the old collection before creating a new one. Without this, uploading a new document adds chunks on top of the old ones, and the system answers questions from the wrong document.</li><li>I use task_type=&quot;RETRIEVAL_DOCUMENT&quot; when storing chunks and task_type=&quot;RETRIEVAL_QUERY&quot; when embedding questions. Gemini&#39;s embedding model is optimised differently for each task. Using the wrong task type measurably reduces retrieval quality.</li><li>I use EphemeralClient on Streamlit Cloud (in-memory) and PersistentClient locally (saves to disk). Cloud environments have file permission restrictions that break ChromaDB&#39;s default disk storage.</li></ol><p><strong>The mistake I made here:</strong> I originally used the deprecated google.generativeai package instead of the new google.genai package. I also used the wrong model name (models/embedding-004 which didn&#39;t exist for my API version). I found the correct model name by listing available models:</p><pre>from google import genai<br>client = genai.Client(api_key=&quot;your_key&quot;)<br>for model in client.models.list():<br>    if &#39;embed&#39; in model.name.lower():<br>        print(model.name)</pre><p>Always list available models before hardcoding a model name. APIs change.</p><h3>Stage 4: The Retriever</h3><p>This is where everything connects. The retriever embeds the user’s question, searches ChromaDB for the most similar chunks, constructs a prompt, and calls Gemini:</p><pre># retriever.py<br>import os<br>import chromadb<br>from dotenv import load_dotenv<br>from google import genai</pre><pre>load_dotenv()</pre><pre>try:<br>    import streamlit as st<br>    api_key = st.secrets[&quot;GOOGLE_API_KEY&quot;]<br>except Exception:<br>    api_key = os.getenv(&quot;GOOGLE_API_KEY&quot;)</pre><pre>client_ai = genai.Client(api_key=api_key)</pre><pre>try:<br>    import streamlit as st<br>    st.secrets[&quot;GOOGLE_API_KEY&quot;]<br>    client_db = chromadb.EphemeralClient()<br>except Exception:<br>    client_db = chromadb.PersistentClient(path=&quot;./chroma_db&quot;)<br></pre><pre>def retrieve_and_answer(query: str, collection_name: str = &quot;documents&quot;) -&gt; str:<br>    from embedder import embed_query</pre><pre>    collection = client_db.get_or_create_collection(name=collection_name)<br>    query_vector = embed_query(query)</pre><pre>    results = collection.query(<br>        query_embeddings=[query_vector],<br>        n_results=3<br>    )</pre><pre>    chunks = results[&quot;documents&quot;][0]<br>    context = &quot;\n\n---\n\n&quot;.join(chunks)</pre><pre>    prompt = f&quot;&quot;&quot;You are a helpful assistant. Answer the user&#39;s question using ONLY the context provided below. If the answer is not in the context, say &quot;I couldn&#39;t find that in the document.&quot;</pre><pre>CONTEXT:<br>{context}</pre><pre>QUESTION:<br>{query}</pre><pre>ANSWER:&quot;&quot;&quot;</pre><pre>    response = client_ai.models.generate_content(<br>        model=&quot;gemini-2.5-flash&quot;,<br>        contents=prompt<br>    )</pre><pre>    return response.text</pre><p><strong>The prompt structure matters.</strong> Context comes before the question (this improves the model’s attention on the provided text). Chunks are separated by --- for clear delineation. The instruction &quot;Answer using ONLY the context&quot; is explicit — without it, the model may mix retrieved content with its own training knowledge and hallucinate.</p><h3>Stage 5: The Streamlit Frontend</h3><p>The full app.py is too long to paste here in full, but these are the key patterns you need to understand:</p><p><strong>Session state management:</strong> Streamlit reruns the entire script on every user interaction. You must store all state in st.session_state , otherwise it resets on every click.</p><pre>if &quot;doc_loaded&quot; not in st.session_state:<br>    st.session_state.doc_loaded = False<br>if &quot;doc_name&quot; not in st.session_state:<br>    st.session_state.doc_name = &quot;&quot;<br>if &quot;session_id&quot; not in st.session_state:<br>    import uuid<br>    st.session_state.session_id = str(uuid.uuid4())[:8]</pre><p><strong>Session isolation:</strong> When I first deployed the app, I discovered that two users uploading different documents at the same time would overwrite each other’s data, they shared the same ChromaDB collection named &quot;documents&quot;. The fix was to give each browser session its own unique collection name:</p><pre># Each session gets a unique 8-character ID<br>st.session_state.session_id = str(uuid.uuid4())[:8]</pre><pre># Use it as the collection name<br>embed_and_store(chunks, collection_name=st.session_state.session_id)<br>answer = retrieve_and_answer(query, collection_name=st.session_state.session_id)</pre><p><strong>The uploader reset trick:</strong> Streamlit identifies widgets by their key. To force-reset a file uploader (so it&#39;s blank after clearing), increment a counter used as the key:</p><pre>if &quot;uploader_key&quot; not in st.session_state:<br>    st.session_state.uploader_key = 0</pre><pre>uploaded_file = st.file_uploader(<br>    &quot;Upload a document&quot;,<br>    key=f&quot;uploader_{st.session_state.uploader_key}&quot;<br>)</pre><pre># When clearing:<br>st.session_state.uploader_key += 1<br>st.rerun()</pre><p><strong>The most painful mistake:</strong> After several rounds of edits, my indentation broke — st.rerun() slipped outside its if block and ran on every single page load, causing an infinite reload loop. The app just showed a spinning circle with no error message. The fix was to carefully read through the entire file and check every block&#39;s indentation. Python&#39;s meaningful whitespace means one misplaced indent can break everything silently.</p><h3>Deploying to Streamlit Cloud</h3><p>Deployment is three steps:</p><p><strong>1. Create a clean requirements.txt:</strong></p><pre>streamlit<br>google-genai<br>chromadb<br>pdfplumber<br>python-docx<br>python-dotenv<br>pandas<br>beautifulsoup4<br>openpyxl</pre><p>Don’t use pip freeze &gt; requirements.txt , it generates a Windows-specific requirements file that fails on Streamlit Cloud&#39;s Linux environment.</p><p><strong>2. Push to GitHub and deploy:</strong></p><p>Go to share.streamlit.io, connect your GitHub repo, set the main file to app.py, and deploy.</p><p><strong>3. Add your API key as a secret:</strong></p><p>In Advanced Settings, add:</p><pre>GOOGLE_API_KEY = &quot;your_key_here&quot;</pre><p>Your live URL will look like: <a href="https://yourapp.streamlit.app/">https://yourapp.streamlit.app</a></p><h3>What I Would Do Differently in Production</h3><p>This is a portfolio project, not a production system. Here’s what would change at scale:</p><ul><li><strong>FastAPI backend:</strong> Separate the AI logic from the UI. The Streamlit app would call API endpoints, enabling multiple frontends and proper testing.</li><li><strong>Source citations:</strong> Show which chunk each claim came from, with a link to the source.</li><li><strong>Conversation memory:</strong> Right now each question is independent. Production systems maintain conversation history for follow-up questions.</li><li><strong>Re-ranking:</strong> After retrieving the top-k chunks, run a second model to re-score them by relevance. Significantly improves answer quality.</li><li><strong>Hybrid search:</strong> Combine semantic search with keyword search for better retrieval on exact references like “Article 7, Clause 3(b)”.</li><li><strong>Evaluation:</strong> Use RAGAS to measure faithfulness (does the answer stick to the context?) and context precision (did we retrieve the right chunks?).</li></ul><h3>The Honest Part</h3><p>I broke this app many times. I got SSL errors, model not found errors, import errors, permission errors, infinite reload loops, and session isolation bugs. Every one of them taught me something that no tutorial could have.</p><p>The thing about building something real, even something imperfect, is that you end up understanding it at a level that reading about it never gives you. When an interviewer asks me how RAG works, I don’t have to remember a definition. I remember the exact moment I watched my Statement of Purpose get embedded into 6 chunks and stored in ChromaDB, and the first time the app answered a question about it correctly.</p><p>That’s the only way this stuff actually sticks.</p><p>If you build this and hit errors I haven’t covered, drop a comment. I’ll help.</p><h3>Links</h3><ul><li><strong>Live app:</strong> <a href="https://rag-document-intelligence-vvsun9pvqjctp3wslay8lq.streamlit.app/">https://rag-document-intelligence-vvsun9pvqjctp3wslay8lq.streamlit.app/</a></li><li><strong>GitHub:</strong> <a href="https://github.com/Oyedunni1/rag-document-intelligence">https://github.com/Oyedunni1/rag-document-intelligence</a></li><li><strong>My portfolio:</strong> <a href="https://oyedunni1.github.io/">https://oyedunni1.github.io</a></li></ul><p><em>Oyedunni Oyewumi is a data scientist transitioning into AI engineering, based in Lagos, Nigeria.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c27bdc0d7476" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>