<?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 Raghava Ashok on Medium]]></title>
        <description><![CDATA[Stories by Raghava Ashok on Medium]]></description>
        <link>https://medium.com/@raghavaashok2004?source=rss-2087991e115a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QVcNEeeumMnLFACafB99Ow.png</url>
            <title>Stories by Raghava Ashok on Medium</title>
            <link>https://medium.com/@raghavaashok2004?source=rss-2087991e115a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 06:48:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@raghavaashok2004/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 PDF & Excel AI Assistant Upload any document, ask questions, get summaries, and generate]]></title>
            <link>https://medium.com/@raghavaashok2004/i-built-a-pdf-excel-ai-assistant-upload-any-document-ask-questions-get-summaries-and-generate-68113e021e20?source=rss-2087991e115a------2</link>
            <guid isPermaLink="false">https://medium.com/p/68113e021e20</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Raghava Ashok]]></dc:creator>
            <pubDate>Thu, 04 Jun 2026 19:19:38 GMT</pubDate>
            <atom:updated>2026-06-04T19:19:38.674Z</atom:updated>
            <content:encoded><![CDATA[<h3>I Built a PDF &amp; Excel AI Assistant Upload any document, ask questions, get summaries, and generate quizzes</h3><h3>The Problem</h3><p>Every time I had a large PDF or Excel file, I’d spend 20–30 minutes manually searching through it for answers. I thought — what if I could just <em>ask</em> the document a question and get an instant answer?</p><p>That’s exactly what I built: <strong>DocAI</strong> — a full-stack web app where you upload PDFs or Excel files and interact with them using natural language.</p><h3>What It Does</h3><ul><li><strong>PDF Q&amp;A</strong> — Upload any PDF and ask questions about it</li><li><strong>Excel Summarization</strong> — Upload .xlsx or .csv and get AI-generated insights using pandas</li><li><strong>Quiz Generator</strong> — Auto-generate multiple choice questions from any document with scoring</li><li><strong>Fast</strong> — Powered by Groq API (llama-3.1–8b-instant) — one of the fastest LLMs available</li></ul><h4><strong>GitHub:</strong> <a href="https://github.com/Raghava2004-cpu/DocAI">github.com/Raghava2004-cpu/DocAI</a></h4><h4><strong>Live demo:</strong> <a href="https://doc-ai-jet.vercel.app/">docai.vercel.app</a></h4><h3>Architecture — How It Works</h3><p>The core idea is <strong>RAG (Retrieval Augmented Generation)</strong>. Here’s why it matters:</p><p>Groq’s free models have a context limit of ~8,000 tokens. A typical PDF has 50,000–200,000 tokens. You simply cannot send the whole document to the AI.</p><p><strong>RAG solves this in 3 steps:</strong></p><pre>1. SPLIT   → Break PDF into 500-word chunks<br>2. SEARCH  → Find the top 4 chunks relevant to the question<br>3. ANSWER  → Send only those chunks to Groq → get a precise answer</pre><p>This means the “smart search” runs entirely on your server for free — Groq only handles the final answer generation</p><h3>Building the Backend — FastAPI + Python</h3><p>The backend has 4 endpoints:</p><p>python</p><pre>POST /upload     → accepts PDF/Excel, processes and stores in session<br>POST /ask        → answers questions about the uploaded file<br>POST /summarize  → generates a full document summary<br>POST /quiz       → generates MCQ questions with answers and explanations</pre><h3>PDF Processing</h3><p>python</p><pre>import fitz  # PyMuPDF<br><br>def extract_pdf_text(path: str) -&gt; list[str]:<br>    doc = fitz.open(path)<br>    full_text = &quot;&quot;<br>    for page in doc:<br>        full_text += page.get_text()<br>    <br>    # Split into 500-word chunks with 50-word overlap<br>    words = full_text.split()<br>    chunks = []<br>    i = 0<br>    while i &lt; len(words):<br>        chunk = &quot; &quot;.join(words[i:i + 500])<br>        chunks.append(chunk)<br>        i += 450  # overlap<br>    return chunks</pre><h3>Excel Summarization with pandas</h3><p>python</p><pre>import pandas as pd<br><br>def parse_excel(path: str) -&gt; str:<br>    df = pd.read_excel(path)<br>    <br>    info = []<br>    info.append(f&quot;Shape: {df.shape[0]} rows × {df.shape[1]} columns&quot;)<br>    info.append(f&quot;Columns: {&#39;, &#39;.join(df.columns.tolist())}&quot;)<br>    info.append(f&quot;Numeric summary:\n{df.describe().round(2).to_string()}&quot;)<br>    info.append(f&quot;Sample:\n{df.head(5).to_string()}&quot;)<br>    <br>    return &quot;\n&quot;.join(info)</pre><p>This structured summary is then sent to Groq which writes a human-readable narrative about the data.</p><h3>Quiz Generation</h3><p>The quiz generator sends document text to Groq with a strict JSON prompt:</p><p>python</p><pre>prompt = f&quot;&quot;&quot;Generate {num} multiple choice questions from this text.<br>Return ONLY a JSON array. Each item must have:<br>&quot;question&quot;, &quot;options&quot; (list of 4), &quot;answer&quot; (exact text), &quot;explanation&quot;<br><br>Text: {text[:4500]}&quot;&quot;&quot;</pre><p>The frontend then renders the quiz, tracks answers, and shows scores with explanations.</p><h3>Building the Frontend — React + Vite</h3><p>The entire frontend is a single App.jsx file with three tabs:</p><ul><li><strong>Chat tab</strong> — message interface for Q&amp;A</li><li><strong>Summary tab</strong> — one-click document summary</li><li><strong>Quiz tab</strong> — configurable quiz with difficulty levels</li></ul><p>One key pattern I used — a safeFetch helper that properly handles both JSON and non-JSON error responses from the backend:</p><pre>async function safeFetch(url, options) {<br>  const res = await fetch(url, options)<br>  const text = await res.text()<br>  if (!res.ok) {<br>    let msg = text.slice(0, 300)<br>    try { msg = JSON.parse(text)?.detail || msg } catch {}<br>    throw new Error(`Server error ${res.status}: ${msg}`)<br>  }<br>  return JSON.parse(text)<br>}</pre><p><strong>Why Hugging Face Spaces?</strong> I tried Render (512MB RAM — too low for ML packages), Railway (ran out of credits), and Koyeb. HF Spaces won because it gives 2GB RAM, has no sleep on idle, and supports Docker natively.</p><p><strong>Key deployment lesson:</strong> On HF Spaces, never use .env files — set your API keys through the <strong>Secrets</strong> panel in Space Settings. The container never sees your local .env.</p><h3>Challenges I Faced</h3><p><strong>1. Memory limits on free hosting</strong> sentence-transformers + faiss-cpu together use ~450MB RAM, which crashes Render&#39;s free tier (512MB limit). I switched to a keyword-based search approach which uses under 150MB.</p><p><strong>2. Port configuration</strong> HF Spaces requires port 7860. Most other platforms use 8000 or 8080. One wrong port number = 30 minutes of debugging.</p><p><strong>3. Quiz answer matching</strong> The LLM sometimes returns &quot;answer&quot;: &quot;B&quot; (a letter) instead of the full option text. I fixed this with a normalizer that maps letters to their corresponding option text.</p><p><strong>4. CORS on deployment</strong> Locally I had allow_origins=[&quot;http://localhost:5173&quot;]. This blocks all production traffic. Changed to allow_origins=[&quot;*&quot;] for deployment.</p><h3>What I Learned</h3><ul><li><strong>RAG is powerful but lightweight</strong> — you don’t need a GPU or expensive vector DB for personal projects. Keyword search handles most real-world queries well.</li><li><strong>Free tiers have real constraints</strong> — RAM limits, port restrictions, and sleep-on-idle are real problems you’ll hit immediately.</li><li><strong>Error messages are your best debugging tool</strong> — adding traceback.format_exc() to every endpoint caught every bug in minutes.</li><li><strong>Groq is genuinely fast</strong> — responses come back in 1–2 seconds even on the free tier. Much better than expected.</li></ul><h3>What’s Next</h3><ul><li>Add OCR support for scanned PDFs (using Tesseract)</li><li>Support multiple file uploads in one session</li><li>Add chat history persistence with POSTGRESQL</li><li>Swap keyword search for true vector embeddings when on paid hosting</li></ul><h3>Try It Yourself</h3><p>The entire project is open source. Clone it, add your free Groq API key, and run:</p><p>bash</p><pre># Backend<br>cd backend<br>pip install -r requirements.txt<br>python main.py</pre><pre># Frontend<br>cd frontend<br>npm install &amp;&amp; npm run dev</pre><p>Get your free Groq key at <a href="https://console.groq.com/">console.groq.com</a> — no credit card needed.</p><p><strong>GitHub:</strong> <a href="https://github.com/Raghava2004-cpu/DocAI">github.com/Raghava2004-cpu/DocAI</a></p><p><em>If this helped you, leave a clap 👏 — it helps others find the article.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68113e021e20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Nanosecond Order Matching Engine in Rust]]></title>
            <link>https://medium.com/@raghavaashok2004/building-a-nanosecond-order-matching-engine-in-rust-4a7456452446?source=rss-2087991e115a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a7456452446</guid>
            <category><![CDATA[rust-low-latency]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <dc:creator><![CDATA[Raghava Ashok]]></dc:creator>
            <pubDate>Sun, 24 May 2026 13:06:34 GMT</pubDate>
            <atom:updated>2026-05-24T13:06:34.005Z</atom:updated>
            <content:encoded><![CDATA[<p>How I built a FIFO price-time priority matching engine that processes 10M+ orders/sec with P99 latency under 200ns</p><p>I recently built a limit order matching engine in Rust from scratch — the kind of system that sits at the core of every stock exchange and crypto trading platform. It processes <strong>10.6 million orders per second</strong> with a P99 match latency of <strong>197 nanoseconds</strong>.</p><p>Here’s exactly how I built it, what decisions I made, and why.</p><p><strong>What is an order book?</strong></p><p>Every trade on a financial exchange goes through a matching engine. It maintains two lists:</p><ul><li><strong>Bids</strong> — buyers, sorted from highest price to lowest</li><li><strong>Asks</strong> — sellers, sorted from lowest price to highest</li></ul><p>When a new order arrives, the engine checks if anyone on the opposite side is willing to trade. If yes — a <strong>fill</strong> (trade) happens at that price. If no — the order rests in the book and waits.</p><p>There are two order types. A <strong>limit order</strong> says “buy, but only at $100 or cheaper” — it waits if it can’t match. A <strong>market order</strong> says “buy right now at whatever price exists” — it walks down the book consuming quantity until it’s filled or the book is empty.</p><p><strong>Why Rust?</strong></p><p>The core problem in a matching engine is shared mutable state under concurrent access. Multiple threads need to read and write the same price levels simultaneously — one receiving orders, one matching, one broadcasting fills.</p><p>In C++ you manage this manually. Forget to unlock a mutex and you get a deadlock. Access freed memory and you get undefined behaviour. The compiler says nothing. The bug shows up in production.</p><p>Rust makes these bugs compile errors. Here’s the most instructive moment from building this project. I tried to pass self.fill_buf into a method on self simultaneously:</p><pre>// This does not compile:<br>OrderType::Market =&gt; self.match_market(order, &amp;mut self.fill_buf),</pre><pre>error[E0499]: cannot borrow `self.fill_buf` as mutable<br>more than once at a time</pre><p>The fix was std::mem::take — temporarily move the buffer out of self, use it, put it back:</p><p>Rust</p><pre>pub fn process(&amp;mut self, order: Order) -&gt; &amp;[Fill] {<br>    let mut buf = std::mem::take(&amp;mut self.fill_buf);<br>    buf.clear();<br>    match order.order_type {<br>        OrderType::Market =&gt; self.match_market(order, &amp;mut buf),<br>        OrderType::Limit  =&gt; self.match_limit(order, &amp;mut buf),<br>    }<br>    self.fill_buf = buf;<br>    &amp;self.fill_buf<br>}</pre><p>In C++ that original code compiles silently and produces a dangling pointer under load. Rust caught it instantly and pointed to the exact fix. That’s not just safety — it’s speed of development on hard problems.</p><p><strong>Three design decisions that matter</strong></p><p><strong>1. BTreeMap over HashMap for price levels</strong></p><p>The order book needs to iterate prices in sorted order constantly — best bid first, best ask first. A HashMap has no order. You&#39;d have to sort on every match cycle.</p><p>BTreeMap keeps keys sorted automatically. Walking the best bids is just:</p><pre>for (&amp;bid_price, level) in self.bids.iter_mut().rev() {</pre><p>No sorting. No scanning. O(log n) insertion, O(1) best-price lookup. This is the correct data structure for this problem and it’s worth being able to explain exactly why in an interview.</p><p><strong>2. Prices stored as integer cents, not floats</strong></p><p>Never store money as f64. Floating point comparison is broken for this use case:</p><pre>// This can be false due to float precision:<br>0.1 + 0.2 == 0.3  // false in most languages<br>// This is always correct:<br>10010u64 == 10010u64  // $100.10 stored as cents</pre><p>Every price in this engine is a u64 representing cents. No rounding errors, no comparison bugs, no surprises.</p><p><strong>3. SmallVec over VecDeque for price level queues</strong></p><p>Each price level holds a queue of orders. Most levels in a real book have 1–4 orders at any time. VecDeque always heap-allocates. SmallVec&lt;[Order; 4]&gt; stores the first 4 orders directly on the stack — the allocator is never called for the common case:</p><pre>type Level = SmallVec&lt;[Order; 4]&gt;;</pre><p>Combined with the zero-allocation fill buffer from earlier, the entire hot path — receive order, match, emit fills — touches the heap allocator zero times in the common case.</p><p><strong>Benchmark results</strong></p><p>Measured with criterion on Windows, 100 samples each:</p><pre>order-book/limit-order-no-match<br> time: [92.6 ns 94.1 ns 95.5 ns]<br> thrpt: [10.47 Melem/s 10.62 Melem/s 10.80 Melem/s]<br>order-book/limit-order-with-match<br> time: [196.1 ns 197.2 ns 198.2 ns]<br> thrpt: [5.04 Melem/s 5.07 Melem/s 5.10 Melem/s]<br> Performance has improved.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uJe1bnCW5chaOTntQKYfvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NC5J7acoXKmHhFZDzCULEg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6AxHtSgvem--zXe20p-vHg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-i5-EZ3YRaJ90rxPdCu-UA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tZGMVipR9r1zikQS8uw4uA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pF2n3bdRC42l_ECQCqH1wA.png" /></figure><p><strong>94ns</strong> to insert a limit order that doesn’t match — pure BTreeMap insertion cost. <strong>197ns</strong> for a full match cycle — find counterparty, calculate trade quantity, emit fill, update resting order. The 103ns difference is the actual matching logic.</p><p>P99 at 197ns means in the worst 1% of cases, a trade still completes in under 200 nanoseconds. Average latency hides tail risk — in trading, the worst-case order is what causes slippage. P99 is the number that matters.</p><p>The engine also ships with a live WebSocket dashboard — connects a browser to the Rust backend and streams throughput, P99 latency, and order book snapshot in real time.</p><p><strong>Full source code</strong></p><p>GitHub: <a href="https://github.com/Raghava2004-cpu/OrderBook">https://github.com/Raghava2004-cpu/OrderBook</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a7456452446" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>