<?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 Milind Agarwal on Medium]]></title>
        <description><![CDATA[Stories by Milind Agarwal on Medium]]></description>
        <link>https://medium.com/@milind.1979?source=rss-58471d576277------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*eqmS2dXnvWZvCZp7</url>
            <title>Stories by Milind Agarwal on Medium</title>
            <link>https://medium.com/@milind.1979?source=rss-58471d576277------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 01:42:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@milind.1979/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[When RAG isn’t enough: a GraphRAG copilot for telecom network delivery]]></title>
            <link>https://medium.com/@milind.1979/when-rag-isnt-enough-a-graphrag-copilot-for-telecom-network-delivery-04376048de1b?source=rss-58471d576277------2</link>
            <guid isPermaLink="false">https://medium.com/p/04376048de1b</guid>
            <category><![CDATA[relationships]]></category>
            <category><![CDATA[5g]]></category>
            <category><![CDATA[telco]]></category>
            <category><![CDATA[autonomous-network]]></category>
            <category><![CDATA[knowledge-graph-rag]]></category>
            <dc:creator><![CDATA[Milind Agarwal]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 01:04:08 GMT</pubDate>
            <atom:updated>2026-10-23T01:04:08.854Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>What this is.</em></strong><em> A learning project that explores </em><strong><em>GraphRAG</em></strong><em> — knowledge-graph-augmented retrieval — over the delivery lifecycle of a cloud-native 5G packet core. It started as a plain document-RAG chatbot I’d built earlier, and grew a knowledge-graph layer on top to answer the </em>relationship<em> questions that plain retrieval quietly fails at. Everything here runs on </em><strong><em>synthetic, sanitized data</em></strong><em> — invented releases, network functions, test cases, and defects that resemble real delivery artifacts in </em>shape<em> but contain nothing real. The code is open source (MIT).</em></blockquote><h3>The problem this solves</h3><p>In telecom network delivery, the work lives across a pile of disconnected documents: per-network-function release notes, Methods of Procedure (MOPs), Customer Information Questionnaires (CIQs), test-case catalogs, acceptance-test results, defect registers, alarm dictionaries, troubleshooting runbooks, implementation records. Any single document is easy to search. The questions that actually matter in delivery are the ones that <strong>span many of them at once</strong>:</p><blockquote>“If we upgrade this network function, which test cases break, what’s blocking go-live, and what’s the evidence?”</blockquote><p>That is not a retrieval question. It’s a <strong>relationship</strong> question. And that distinction is the whole reason this project exists.</p><p>A plain Retrieval-Augmented Generation (RAG) pipeline answers <em>“what does this document say?”</em> beautifully — it embeds chunks of text, finds the ones most similar to your question, and hands them to a language model. But “what is <em>affected</em> if I change X?” has no good answer in any single chunk of text. The answer lives in the <strong>connections</strong> between artifacts: a test is <em>blocked by</em> a defect, which was <em>reported in</em> a release note, which <em>documents</em> a network function, which is <em>deployed on</em> an environment that <em>gates</em> go-live. Plain RAG has no notion of those edges. It can only return paragraphs that happen to look like your question.</p><p>So I built the thing that does: a knowledge graph, sitting next to the vector store, that makes those relationships explicit and traversable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fF_2BoVCcbtMYBhN.png" /></figure><p><em>The same question, two approaches. Plain RAG (left) returns relevant passages you must connect yourself; graph-augmented retrieval (right) assembles the dependency chain and cites every link.</em></p><h3>The big picture (how it works in two layers)</h3><p>The system has two retrieval layers over the same synthetic corpus, and the interesting part is how they combine:</p><ol><li><strong>Vector RAG (the baseline).</strong> Documents are chunked, embedded locally, and stored in a vector database. A question retrieves the most relevant passages and — optionally — a language model synthesizes a grounded, cited answer from them. This is the “what does it say?” layer.</li><li><strong>A knowledge graph (the differentiator).</strong> The same corpus is parsed into a typed graph: <strong>nodes</strong> are entities (test cases, defects, alarms, network functions, software versions, release notes, environments, documents) and <strong>edges</strong> are the relationships between them ( validates, blocked_by, fixed_in, reports, documents, certified_with, gates, precedes, ...). This is the &quot;what&#39;s connected to what?&quot; layer.</li></ol><p>When you ask a question, the system detects which graph entities you mentioned (by ID like TC-204, or by name like a network function), <strong>traverses outward</strong> from them to pull in the connected neighborhood, and feeds that relationship context to the answerer <em>alongside</em> the vector passages - each edge carrying the source document it came from, so the graph is just as citable as the text.</p><p>The result: the answer to <em>“what’s impacted by this upgrade and what blocks go-live?”</em> is assembled by walking the graph, not by hoping one paragraph happened to state the whole chain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NsGLn7kd1-vkbr1q.png" /></figure><p><em>The two layers over one corpus: a vector store for similarity and a knowledge graph for relationships. A question draws on both.</em></p><h3>Why a graph, and why not just a bigger RAG</h3><p>It’s a fair challenge: couldn’t you just retrieve more chunks, or write the dependencies into one big document, and let RAG find it? You can — and it’s brittle. You’d be pre-computing every answer by hand and hoping the phrasing matches. The moment someone asks about a path you didn’t spell out in prose, RAG is blind to it.</p><p>A graph flips that. You state the <em>facts</em> once as edges ( TC-204 blocked_by DEF-1203, DEF-1203 reported_in release-note-pcc), and then <strong>any</strong> traversal question - one hop, three hops, upstream, downstream - is answerable without having written that specific answer anywhere. Impact analysis, dependency tracing, &quot;what else touches this&quot; - these are graph-shaped problems, and a graph solves a whole <em>class</em> of them at once.</p><p>I deliberately built it in two phases so the value of the graph is <em>demonstrated, not assumed</em>: first the RAG baseline, then the graph layer on top, with a toggle to turn the graph off and compare the two answers side by side on the same question.</p><h3>Modeling reality: release notes are per-network-function</h3><p>One modeling decision is worth calling out, because it’s where the synthetic data stopped being a toy and started reflecting how delivery actually works.</p><p>My first cut had a single, tidy “release note” listing every network function and its version in one table. Convenient — and wrong. In reality, each network function ships its <strong>own</strong> release note, on its <strong>own</strong> version cadence, often from a different vendor team. The “release” as a whole is not a source document at all; it’s an <strong>integration view</strong> that a delivery team <em>assembles</em> on top of many individual notes — essentially a compatibility matrix saying “these specific versions are certified to run together.”</p><p>So I split the corpus accordingly: one release note per network function, plus a separate integration/compatibility matrix. In the graph, the release became a <em>derived</em> node that includes each certified (function, version) pair, with certified_with and requires_min_version edges between versions - each sourced from the right per-function note.</p><p>This isn’t cosmetic. It unlocks a question class that was literally impossible before: <em>“does this control-plane version require a minimum version of the policy component?”</em> is a cross-document, cross-function compatibility question that no single release note answers — but the graph (or the matrix it models) does. The graph is, quite literally, doing the integration work a human does by hand today.</p><h3>The anchor demo: a failed acceptance test after an upgrade</h3><p>Every demo needs one story told end-to-end. Mine is a failure chain:</p><p>An acceptance test ( TC-204, event-parity on an interface) <strong>fails</strong> after a control-plane network function is upgraded. Why? The graph traces it:</p><ul><li>TC-204 is blocked_by defectDEF-1203 (a counter reset on warm restart),</li><li>DEF-1203 reported_in the policy component&#39;s release note andraised an alarm (ALM-SX-DOWN),</li><li>TC-204 gates the go-live environment, whichprecedes production -</li><li>so the failure doesn’t just fail a test; it <strong>holds the whole rollout</strong>, and the recommended fix (a documented workaround + re-run) is reachable through a troubleshooting runbook thatreferences the same defect and MOP.</li></ul><p>Ask that question with the graph off, and you get relevant passages — useful, but you have to connect the dots yourself. Ask it with the graph on, and the dependency chain comes back assembled, with a citation on every link.</p><h3>The Impact Explorer: seeing the graph</h3><p>Answers are one thing; <em>exploration</em> is another. The browser GUI has a second tab — an <strong>Impact Explorer</strong> — that is pure graph, no language model involved. You pick any entity (a test case, a defect, a network function, a release note), choose how many hops to traverse, and it renders the connected neighborhood as an <strong>interactive node-and-edge diagram</strong>: nodes colored by type, the selected entity highlighted, edges labeled with the relationship, draggable and hoverable.</p><p>This is the single clearest one-screen answer to “why GraphRAG and not just RAG?” — a reviewer picks an entity and immediately <em>sees</em> the slice of the delivery lifecycle connected to it, which plain document search would never assemble.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JS-M7b2SC4uwlVs3.png" /></figure><p><em>The whole graph, rendered from the project’s own data: test cases, defects, alarms, network functions, versions, release notes, and environments, wired together by typed relationships.</em></p><h3>A word on the extractor (deterministic, on purpose)</h3><p>For this synthetic corpus the entity/relationship extraction is <strong>rule-based</strong>, not LLM-driven: a small set of ID patterns plus a curated, auditable table of relationships, each carrying the document it came from. For a clean, invented corpus that’s the right call — it’s reproducible, needs no API key, and is 100% faithful to the text. Crucially, the graph layer’s <em>value</em> (traversal, impact analysis) is independent of <em>how</em> the graph was populated. So for messy real-world data later, an LLM-assisted extractor can slot in behind the exact same graph interface without touching retrieval or the UI.</p><h3>Running it</h3><p>The whole thing is self-contained and local — no server, no Docker, no cloud required to try it.</p><pre>python -m venv .venv &amp;&amp; ./.venv/bin/pip install -r requirements.txt ./.venv/bin/python -m src.ingest # embed the synthetic corpus into the vector store ./.venv/bin/python -m src.extract # build the knowledge graph (~36 nodes, ~69 edges) ./.venv/bin/streamlit run app.py # browser GUI: Ask a question + Impact Explorer</pre><p>By default the answerer runs in <em>extractive</em> mode — it shows the retrieved passages and the traversed graph relationships with no language model at all, so it works with zero API keys. Point it at a cloud model or a local small model for synthesized prose instead; the provider is a one-line config switch.</p><h3>Honest limitations (the questions a sharp reader will ask)</h3><ul><li><strong>The data is synthetic.</strong> It’s designed around one clean anchor story so the relationships are tidy. Real delivery data is messier — inconsistent naming, missing links, contradictory records. Proving the graph adds value on clean data first is deliberate; hardening it for real data is a separate job.</li><li><strong>The extractor is tuned to the corpus vocabulary.</strong> Rule-based extraction is faithful but not general; real data needs an LLM-assisted extractor (the interface is already built to accept one).</li><li><strong>Ingestion handles text formats only today.</strong> Real artifacts arrive as PDF, Word, and Excel (CIQs are notoriously spreadsheets). PDF/XLSX ingestion plus a PII-scrubbing pass are the main gaps before real data could flow in — and real data would stay strictly local, never in the shareable repo.</li><li><strong>The graph is small and in-process.</strong> It uses an in-memory graph persisted to a single JSON file — right-sized for ~100 nodes. A server-backed graph store could be swapped in behind the same interface if it ever needed to scale; the config hooks for that are already present but dormant.</li></ul><h3>Where this fits: the autonomous-network angle</h3><p>The telecom industry’s push toward <strong>autonomous networks</strong> is about intent-driven, closed-loop operations — and reaching higher levels of autonomy depends on machines being able to <strong>reason over relationships</strong> between network state, changes, tests, faults, and knowledge, not just store documents. This project is a small, concrete demonstration of that reasoning pattern on the delivery and assurance side: a connected knowledge substrate, plus explainable, cited answers. The anchor flow — change → failed test → root-cause defect → recommended fix with evidence — is exactly the <em>observe → analyze → decide</em> portion of a closed loop, applied to acceptance and go-live readiness.</p><h3>Toolset</h3><ul><li><strong>Knowledge graph:</strong> an in-process graph library (file-persisted; no server) — right-sized for the problem, with a backend-agnostic interface so a server-backed store could replace it later.</li><li><strong>Vector search:</strong> a local vector database with local, offline embeddings (ONNX, no GPU, no PyTorch).</li><li><strong>Answer engine:</strong> pluggable — a cloud model, a local small model, or an extractive no-model fallback that always works.</li><li><strong>Extraction:</strong> deterministic, rule-based, provenance-carrying (swap in an LLM extractor for real data).</li><li><strong>UI:</strong> a browser app with a Q&amp;A tab and an interactive graph-visualization Impact Explorer.</li><li><strong>Language:</strong> Python. <strong>License:</strong> MIT.</li></ul><h3>Closing thought</h3><p>Plain RAG is a genuinely great hammer — but not every question is a nail. The questions that keep delivery teams up at night are about <em>consequences</em>: if I touch this, what else moves? Those are graph questions. Building the graph layer turned a document search tool into something that can actually trace a failure from an upgrade all the way to a held production rollout, and show its work at every step. That’s the difference between a chatbot that <em>finds</em> text and one that can <em>reason</em> about a delivery program.</p><p><em>Code and synthetic data: open source (MIT). Built on personal time, with invented data, for learning and demonstration.</em></p><p><em>Originally published at </em><a href="https://milindagarwal2.github.io/telco-delivery-graphrag/docs/article-import.html"><em>https://milindagarwal2.github.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04376048de1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using an LLM to retrieve text, tables and images in a chatbot with RAG]]></title>
            <link>https://medium.com/@milind.1979/using-an-llm-to-retrieve-text-tables-and-images-in-a-chatbot-with-rag-40c33a22e3d1?source=rss-58471d576277------2</link>
            <guid isPermaLink="false">https://medium.com/p/40c33a22e3d1</guid>
            <category><![CDATA[text]]></category>
            <category><![CDATA[image]]></category>
            <category><![CDATA[table]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Milind Agarwal]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 16:34:48 GMT</pubDate>
            <atom:updated>2026-10-21T16:34:48.917Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>A note on this edition.</em></strong><em> I first published this article in January 2025 with a simple idea: a technical document is more than text, so a chatbot that answers questions about it shouldn’t throw away the tables and images during ingestion. That core idea still stands — but almost everything </em>around<em> it has grown up since. What started as two Python files and an </em><em>http.server for avatars is now a self‑hostable product: local offline embeddings, a pluggable answer engine (cloud </em><strong><em>or</em></strong><em> a local offline model </em><strong><em>or</em></strong><em> no model at all), PowerPoint support, grounded &quot;I don&#39;t know&quot; answers with per‑claim citations, an embeddable one‑line chat widget for any website, a Docker Compose stack, Postgres Q&amp;A logging, prompt‑injection defense, and an offline evaluation harness. This is the 2026 rewrite. If you read the original, you&#39;ll recognize the heart of it - it just wears a lot more armor now.</em></blockquote><h3>The problem this solves (still the whole point)</h3><p>In a technical document there is not just text, but images and tables too. Those images carry important information — architecture diagrams, formulas, flowcharts. The tables carry specifications, parameters, limits. Very often these images and tables convey <em>more</em> value than the prose around them.</p><p>If you build a chatbot to query such documents with a plain RAG approach, you first create a vector database — embeddings of chunks of the document’s <strong>text</strong>. During that embedding step the image and table information is simply ignored and lost. Even if you scrape the text out of a table, you lose the table’s <strong>structure</strong>. So when you query that store, all you get back is text — minus the images, minus the tables. Which is frequently unhelpful to the end user, and doesn’t exactly inspire confidence in the answer.</p><p>What if we could retrieve the tables and images too? That was the original ask, and the approach is the same: be a little <strong>smart during ingestion</strong> (extract and save the tables/images, keyed by document + page), and use a little <strong>ingenuity at query time</strong> (reconstruct those assets from metadata and render them inline next to the answer). Keep the page number and document name attached to everything, so every answer is <strong>explainable</strong> — the user can jump straight to the source page. That’s the XAI (explainable AI) angle, and it matters more than ever.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mTZdj4pP0v3J--tZ.png" /></figure><p><em>The same source document, two pipelines. Plain RAG (left) embeds only text, so tables are flattened and images are discarded — the query returns text alone. This approach (right) keeps the tables and images and even embeds each table’s content as its own searchable chunk, so the answer comes back grounded, with the real table/figure inline and a page citation.</em></p><p>What’s new is <em>how well</em> we can do all of this now, and how production‑ready the whole thing has become. Let me walk you through it. As before — bear with me to the end. 🙂</p><h3>The big picture (how it works in three parts)</h3><p>The original article had two parts: ingestion and the chatbot. There’s now a third.</p><ul><li><strong>Part 1 — Ingestion (</strong><strong>embeddingEngine.py).</strong> For each <strong>PDF page or PPTX slide</strong>, extract text, tables, and images. Embed the text -<em>and the table content itself</em> - into a Chroma vector store with metadata. Save tables and images to disk keyed by document + page. A small dispatcher routes.pdf and .pptx to the right extractor;<strong>slides map to page numbers</strong>, so everything downstream treats a deck exactly like a PDF.</li><li><strong>Part 2 — Chatbot (</strong><strong>chatBOT_engine.py).</strong> A Streamlit chat app. For a follow‑up question it first<strong>rewrites</strong> the question into a standalone query using recent history, runs MMR vector search, then<strong>streams a single synthesized answer</strong> grounded in the retrieved context with inline[document p.N] citations. Based on sidebar toggles it also reconstructs and renders the images/tables from the<strong>cited</strong> pages, offers a download of each cited source, and suggests clickable follow‑ups.</li><li><strong>Part 3 — Embeddable widget (</strong><strong>api_server.py +</strong><strong>widget/).</strong> The <em>same</em> retrieval and answer logic (via a shared, UI‑freegenerate_answer()) exposed over an HTTP API (FastAPI) plus a one‑line JavaScript widget that drops a floating chat bubble onto<em>any</em> website.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AbeNe7C-Q9ITyB0q.png" /></figure><p><em>The whole pipeline at a glance: ingestion (left) extracts text, tables, and images and splits them between the Chroma vector store and an on-disk sidecar store; the query side (right) retrieves, generates a grounded answer with a pluggable engine, and renders it — the same </em><em>generate_answer() core feeding both the Streamlit app and the embeddable widget.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7kTRWq1NbEATs8Cm.png" /></figure><p><em>Ask a question → get a synthesized answer with the </em><strong><em>actual table from the source page</em></strong><em> rendered inline, and a</em><em>[document p.N] citation. Most RAG apps would have lost that table during ingestion.</em></p><h3>What changed since the 2025 article (the honest changelog)</h3><p>If you only read one section, read this one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q-aRj-csw9p0zBzZ.png" /></figure><p>Let’s go through the ones that change how you’d <em>build</em> this.</p><h3>Part 1: Ingestion — now smarter, and format‑agnostic</h3><h3>Local, offline embeddings (goodbye PyTorch)</h3><p>The original used SentenceTransformerEmbeddings(model_name=&quot;all-mpnet-base-v2&quot;), which pulls in PyTorch. The rewrite uses<strong>fastembed</strong>, which runs the embedding model as ONNX - no PyTorch, smaller install, fully offline after a one‑time ~130 MB model download. The vector store construction is centralized in one function that ingestion and the chatbot both call, so the embedding model can never drift between write and read (a classic &quot;empty answers / dimension mismatch&quot; footgun):</p><pre>def get_vectorstore(): &quot;&quot;&quot;Return the shared Chroma vector store (same config everywhere).&quot;&quot;&quot; return Chroma( &quot;Project_NAME&quot;, embedding_function, &quot;./chroma_Name&quot;, )</pre><h3>One dispatcher, two formats (PDF and PowerPoint)</h3><p>The original was PDF‑only and noted you <em>could</em> extend it. I did. A tiny dispatcher routes files to the right extractor, and — this is the trick that keeps everything downstream simple — <strong>a slide’s index is treated as its page number</strong>. So a deck behaves exactly like a PDF everywhere else in the app:</p><pre>def ingest_file(filepath, vectorstore): lower = filepath.lower() return ingest_pdf(filepath, vectorstore) return ingest_pptx(filepath, vectorstore)</pre><p>python-pptx gives us slide text, <strong>native PowerPoint tables</strong>, and <strong>inserted raster pictures</strong>. (Charts, SmartArt, and vector graphics aren&#39;t raster images, so they aren&#39;t extracted - reference them in text, or paste them as a picture if you need them rendered.)</p><h3>The “page‑as‑anchor” sidecar store (unchanged idea, cleaner code)</h3><p>The join key between embedded text and non‑text assets is still <strong>file_name + </strong><strong>pagenumber</strong>. Every text chunk is embedded with metadata flags saying whether its page has an image/table, and the assets live on disk at predictable paths:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kdQNfMdOm9mdhOn3.png" /></figure><h3>Tables are now semantically searchable (not just stored)</h3><p>This is one of my favorite upgrades. In 2025 I saved the table to disk but only embedded the <em>prose</em> on the page — so if the answer lived <strong>inside</strong> the table, a content query might never pull that page. Now each extracted table is flattened to a label‑rich text form and embedded as its <strong>own</strong> chunk ( contentType: &quot;table&quot;):</p><p>So now “what’s the VBUS current?” can retrieve a page <em>because the number is in a table cell</em>, not because the prose happened to mention it.</p><h3>Re‑embedding is a safe upsert (no more reset_collection())</h3><p>The original reset the whole collection on every run to avoid duplicates — fine for a full rebuild, terrible for incrementally adding one document. Now every document is content‑addressed by a SHA‑256 of its bytes, stored on each chunk as doc_hash:</p><p>Re‑embedding <strong>identical</strong> content is a no‑op. Re‑embedding <strong>changed</strong> content (or the same filename with new bytes) deletes the old chunks + stale assets first, then re‑adds. Duplicates never accumulate — and you never nuke your whole store to add one file.</p><h3>Part 2: The chatbot — grounded, conversational, and inline</h3><h3>From per‑chunk summaries to one synthesized, grounded answer</h3><p>The 2025 version ran each retrieved chunk through a BART summarizer and concatenated the results. It was honest about the trade‑off — detailed but not clean. The rewrite retrieves with <strong>MMR</strong> ( k=8, fetch_k=24, lambda_mult=0.6, for better recall and less near‑duplicate noise) and produces <strong>one</strong> synthesized answer that <strong>streams in</strong>, with inline[document p.N] citations for each claim.</p><p>Crucially, it’s <strong>grounded</strong>: if the retrieved context doesn’t contain the answer, the assistant says it doesn’t know rather than inventing something. On such a refusal it shows <strong>no</strong> source downloads, figures, or follow‑ups (those would reflect off‑topic chunks, not your question). A <strong>low‑confidence banner</strong> appears when the best retrieval score falls below a configurable threshold (default <strong>0.63</strong>, which — nice touch — is backed by the evaluation harness, not guessed).</p><h3>The answer engine is pluggable (and can be no engine)</h3><p>This is the biggest conceptual change. The answer backend is <strong>single‑select</strong>, chosen in the admin GUI and stored in config.json. The chatbot reads it once per session and uses it transparently - chat users never see or pick the engine:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QYuL3aNSx5hkFwK3.png" /></figure><p>And there’s an <strong>auto‑fallback</strong>: if the selected provider isn’t actually available at runtime (missing key, missing GGUF), it silently falls back to extractive so the app never breaks. A fresh clone defaults to none and runs with no key and no model download. This means the whole thing can run <strong>100% offline</strong> (local embeddings + Qwen or extractive = no outbound calls) - which matters a lot for confidential docs.</p><h3>Follow‑ups that actually understand context</h3><p>Ask “What’s the Pico’s VBUS current?” then “What about at 85°C?” — the second question is meaningless to a retriever on its own. So before searching, the app <strong>rewrites</strong> it into a standalone query using recent history:</p><p>The app also suggests clickable follow‑up questions under each answer (suppressed when the question was out of context or low‑confidence).</p><h3>Assets render inline — no more companion web server</h3><p>In 2025 the templates linked to http://localhost:8000/AI.png and friends, so you had to run python -m http.server 8000 in a second terminal just to see avatars and download links. Now <strong>images, source PDFs, and tables are inlined directly into the page</strong> - images and PDFs as base64 data: URIs, tables as HTML - so <strong>no static file server is needed</strong>. One service runs the whole chatbot. (Very large source PDFs &gt;8 MB are shown as a plain filename label instead of an inline download, to keep the page light.) And attribution is scoped to the pages the answer <strong>actually cited</strong>, so a chunk retrieval pulled in but the answer didn&#39;t use won&#39;t leave a stray asset behind.</p><p>There’s also a <strong>“Prepare PDF of chat”</strong> button that exports the whole conversation — images and tables included — via xhtml2pdf.</p><p>The same RAG backend is now exposed as a one‑line embeddable widget. A site owner adds a single tag before &lt;/body&gt;:</p><pre>&lt; script src = &quot;https://YOUR_HOST/widget/widget.js&quot; data-api= &quot;https://YOUR_HOST/api&quot; &gt;&lt;/ script &gt;</pre><p>That drops a floating chat bubble on the page which talks to a <strong>FastAPI</strong> backend ( POST /api/chat, GET /api/health, GET /api/source/{name}) and renders answers with clickable source citations and suggested follow‑ups. The widget and the Streamlit app share the <strong>exact same</strong> generate_answer() core - there&#39;s no second implementation to keep in sync.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5qupKeE-QdpVxOWa.png" /></figure><p>The /api/source/{name} endpoint only serves whitelisted document types by basename, with path‑traversal protection. A demo site (a fake third‑party page on a different origin) is included to prove the cross‑origin embed works.</p><blockquote><strong><em>Honest caveat (and my top roadmap item):</em></strong><em> the API and Streamlit app are currently </em><strong><em>open and unauthenticated</em></strong><em>, with open CORS. That’s fine for a local demo, but before any public or multi‑user deployment you must add auth, an origin allowlist, rate limiting, and request‑size caps — especially for internal/confidential material.</em></blockquote><h3>Security: defending a RAG app from the documents themselves</h3><p>A RAG app pastes retrieved document text straight into the LLM prompt. So a poisoned document could carry text like <em>“ignore previous instructions and…”</em> — an <strong>indirect prompt injection</strong>. The rewrite defends against this by fencing the retrieved context as untrusted data and establishing an instruction hierarchy in the system prompt (everything inside the fence is <em>data to quote and cite</em>, never instructions to obey):</p><p>The defense applies to both generative providers (extractive mode has no LLM, so it’s inherently immune), and it’s regression‑tested. Output rendering is injection‑safe too: the widget inserts text via textContent (HTML‑escaped), and the Streamlit app only uses unsafe_allow_html for its <em>own</em> figure/table HTML built from local files - never for model output.</p><h3>Running it (so much simpler now)</h3><h3>One command, locally</h3><pre>python3 -m venv .venv &amp;&amp; source .venv/bin/activate mkdir -p pdf pptx &amp;&amp; cp /path/to/*.pdf pdf/ &amp;&amp; cp /path/to/*.pptx pptx/</pre><p>No second terminal for a file server. No PyTorch. No API key unless you opt into Claude.</p><h3>The whole stack in Docker</h3><p>That brings up <strong>five services</strong>: the chatbot (:8501), the admin GUI (:8502), the widget API (:8000), a demo site (:9000), and a Postgres db for Q&amp;A logging. Config lives in a mounted config.json, so you can retune the app without a redeploy.</p><h3>A web admin console (no CLI required)</h3><p>Upload or delete documents (with a pages/tables/images summary), pick the answer engine, tune the confidence threshold, edit every piece of user‑facing text, set the widget theme, configure logging, and browse the Q&amp;A history — all from a tabbed Streamlit UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*unx22d5pvRn6s9qG.png" /></figure><h3>Proving it works: an offline evaluation harness</h3><p>I added something the original lacked entirely — a way to <strong>measure</strong> retrieval quality with evidence, so I can catch regressions and tune settings instead of guessing. It’s <strong>embedding‑only (no LLM calls, no API cost)</strong> and drives the same functions the chatbot uses:</p><p>It reports two things:</p><ul><li><strong>Retrieval recall@k</strong> — for each ground‑truth question, is the expected page in the top‑k retrieved chunks? It exits non‑zero below arecall_floor, so retrieval regressions are caught in CI before users see them.</li><li><strong>Confidence calibration</strong> — the score distributions for in‑corpus vs off‑topic questions, and a<strong>suggested </strong><strong>low_confidence_threshold</strong> sitting in the gap between them. (That&#39;s where the 0.63 default came from: in‑corpus min ≈0.65, off‑topic max ≈0.61.)</li></ul><p>The reference set is plain JSON of human‑asserted question→page pairs, and it adapts to a changing store — a question whose document isn’t currently embedded is skipped, not failed.</p><h3>Observability: you can finally see what the bot did</h3><p>Every answered question logs <strong>one structured line</strong> (provider, retrieval breadth, best relevance score, low‑confidence/refusal flags, source count, latency), and — for both the chatbot and the widget — a row in a Postgres qa_log table ( asked_at, source, question, answer, provider, best_score, sources as JSONB, latency_ms, ...). Logging is <strong>fail‑safe</strong>: if Postgres is unreachable, answering still works and the write silently no‑ops, failing fast so it never adds latency. The admin console&#39;s Q&amp;A History tab gives you stats, filters, a read‑only table, CSV export, and retention purge.</p><h3>Honest limitations (the questions a sharp reader will ask)</h3><ul><li><strong>No authentication yet.</strong> The app and widget API are open — top‑priority before any public/multi‑user deployment.</li><li><strong>The widget is text + citations only</strong> today — no streaming, no inline figures/tables (the Streamlit app has all three).</li><li><strong>No OCR</strong> — scanned/image‑only PDFs aren’t text‑extracted.</li><li><strong>Non‑raster graphics</strong> (charts, SmartArt, vector art) aren’t extracted as images.</li><li><strong>Local Qwen is slow on CPU</strong> (~1–2 min/answer) and may omit inline citation markers — use Claude when speed and strict citations matter.</li></ul><h3>How it compares to other RAG approaches</h3><p>People reasonably ask: why not just use a hosted upload-and-chat SaaS, assemble something with LangChain yourself, buy an enterprise RAG platform, or paste the PDF into a general LLM chat? Each of those is a legitimate choice — they just optimize for different things. Here’s the honest positioning across the capabilities this project leads with (these are <em>general category</em> characteristics; verify specifics against any given vendor’s current docs):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Kw4WPhTTMwM2qjEr.png" /></figure><p>The short version:</p><ul><li><strong>vs. hosted SaaS doc-chat</strong> — this wins on data residency (fully self-hosted, can be offline), table/figure fidelity (most SaaS flatten to text), no per-seat/token bill, and a white-labelable widget. They win on turnkey auth/SSO and multi-tenant user management out of the box — which is still a roadmap item here.</li><li><strong>vs. a DIY framework stack</strong> — this is a <em>finished, runnable product</em> (ingestion + chat + admin GUI + widget + Docker + eval harness), not a toolkit you assemble. They win on unlimited flexibility and a huge connector ecosystem.</li><li><strong>vs. an enterprise RAG platform</strong> — this wins on footprint, cost, transparency (open, inspectable code and prompts), and offline capability. They win on enterprise auth/RBAC, SharePoint/Confluence connectors, compliance certs, SLAs, and scale/HA.</li><li><strong>vs. general LLM chat with file upload</strong> — this wins on a persistent indexed corpus (no re-uploading per chat), exact-page attribution, rendered tables/figures, and grounded refusal. They win on general reasoning breadth and zero setup for a one-off.</li></ul><p>The one row where this project is honestly behind is <strong>enterprise auth</strong> — it’s the top of my roadmap, and I’d rather state it plainly than hide it.</p><h3>Why bother keeping tables and images?</h3><p>Same reason as 2025, and it’s held up: for technical readers, the <em>artifact</em> often <strong>is</strong> the answer. A spec table or an architecture diagram tells them what they need far faster than a paragraph summarizing it — and seeing the real table, on the real cited page, builds the trust that a bare generated sentence never will. What’s new is that the whole thing is now grounded (it refuses when it doesn’t know), self‑hostable and offline‑capable (nothing has to leave your machine), embeddable anywhere, and provable (the eval harness).</p><p>If you read the original: thank you, and the heart of it is unchanged. It just grew up.</p><h3>Toolset (2026)</h3><ul><li><strong>Embeddings:</strong> fastembed ONNX,BAAI/bge-small-en-v1.5 (local, offline, no PyTorch)</li><li><strong>Answer engine:</strong> Claude (API) · Qwen 1.5B GGUF viallama-cpp-python (local) · None (extractive)</li><li><strong>Retrieval / store:</strong> Chroma with MMR (k=8, fetch_k=24, lambda_mult=0.6)</li><li><strong>PDF:</strong> pymupdf4llm (text),pymupdf/fitz (tables), Spire.PDF (images)</li><li><strong>PPTX:</strong> python-pptx (text, native tables, pictures)</li><li><strong>UI:</strong> Streamlit chat primitives ·<strong>Widget:</strong> vanilla JS · <strong>API:</strong> FastAPI</li><li><strong>Chat‑to‑PDF:</strong> xhtml2pdf ·<strong>Q&amp;A logging:</strong> Postgres via psycopg 3</li><li><strong>Deployment:</strong> Docker Compose (5 services)</li></ul><h3>References</h3><ul><li>Streamlit — <a href="https://docs.streamlit.io/">https://docs.streamlit.io/</a></li><li>LangChain — <a href="https://python.langchain.com/docs/introduction/">https://python.langchain.com/docs/introduction/</a></li><li>Chroma — <a href="https://www.trychroma.com/">https://www.trychroma.com/</a></li><li>PyMuPDF / pymupdf4llm — <a href="https://pymupdf.readthedocs.io/en/latest/pymupdf4llm/index.html">https://pymupdf.readthedocs.io/en/latest/pymupdf4llm/index.html</a></li><li>fastembed — <a href="https://github.com/qdrant/fastembed">https://github.com/qdrant/fastembed</a></li><li>llama.cpp / llama-cpp-python — <a href="https://github.com/abetlen/llama-cpp-python">https://github.com/abetlen/llama-cpp-python</a></li></ul><p><em>GitHub: milindagarwal2/ChatBOT</em></p><p><em>Originally published at </em><a href="https://milindagarwal2.github.io/doc-intelligence-rag/article-import.html"><em>https://milindagarwal2.github.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40c33a22e3d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using LLM to retrieve text, table and images in chatbot using RAG and achieve multi-modal impact]]></title>
            <link>https://medium.com/@milind.1979/using-llm-to-retrieve-text-table-and-images-in-chatbot-using-rag-and-achieve-multi-modal-impact-21cbd32ac7cd?source=rss-58471d576277------2</link>
            <guid isPermaLink="false">https://medium.com/p/21cbd32ac7cd</guid>
            <category><![CDATA[multi-modal-llm]]></category>
            <category><![CDATA[image]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[text]]></category>
            <dc:creator><![CDATA[Milind Agarwal]]></dc:creator>
            <pubDate>Mon, 06 Jan 2025 00:06:07 GMT</pubDate>
            <atom:updated>2026-09-21T22:01:15.201Z</atom:updated>
            <content:encoded><![CDATA[<h3>## Setup &amp; Running Locally</h3><p>Prerequisites: Python 3, and PDF documents you want to query.</p><p>1. **Create a virtual environment and install dependencies** (no `requirements.txt` is checked in yet, so install what the code imports):<br> ```<br> python3 -m venv .venv<br> source .venv/bin/activate<br> pip install streamlit python-dotenv anthropic langchain langchain-community \<br> langchain-chroma langchain-text-splitters langchain-core sentence-transformers \<br> transformers torch PyPDF2 pandas requests attrs Spire.PDF pymupdf4llm PyMuPDF<br> ```</p><p>2. **Configure your Anthropic API key.** Copy `.env.example` to `.env` and fill in a real key from [console.anthropic.com](<a href="https://console.anthrop/">https://console.anthrop</a><br>ic.com):<br> ```<br> cp .env.example .env<br> ```<br> `.env` is gitignored, so the key never gets committed.</p><p>3. **Add your source PDFs** to the `pdf/` folder.</p><p>4. **Build the vector index** (extracts text/images/tables from each PDF and embeds them into Chroma):<br> ```<br> python embeddingEngine.py<br> ```</p><p>5. **Serve chat avatars and downloadable files.** `htmlTemplates.py` expects `AI.png` and `users.png` at the repo root and links to source PDFs/im<br>ages/tables via `<a href="http://localhost:8000/...%60">http://localhost:8000/...`</a>. Add those two avatar images, then in a second terminal:<br> ```<br> python -m http.server 8000<br> ```</p><p>6. **Run the app:**<br> ```<br> streamlit run chatBOT_engine.py<br> ```<br> Opens at `<a href="http://localhost:8501`">http://localhost:8501`</a>.</p><p>— -Using LLM to retrieve text, table and images in chatbot using RAG and achieve multi-modal impact</p><p>In a technical document there is not just text but images and tables too. These images could convey important information such as architecture diagram, formulas etc. Tables could have information such as specifications and more. In many cases these images and tables convey much more valuable information than text itself.</p><p>If we have to create a chatbot application to query these technical documents using a regular RAG approach, first we will have to we create a vector database which is nothing but embedding of chunks of text information in these documents. During this embedding process we loose the image and table information as regular embedding process simply ignores the information present here. Even if do pickup text from the table for embedding, we end up loosing the table structure. Hence when we query this vector table all we get back is the text information minus images and tables. Which many times is not useful to the end user. Also it does not instill confidence in the answer given by chatbot. What if we could also retrieve the table and images too ?? Below I am going to explain how we can do this using using regular LLM but being little smart when extracting information from technical document during embedding or vectorization process and also using little bit of ingenuity when displaying the results of the query. Since this is little bit longer process then regular RAG based chatbot application please bear with me till the end….</p><p>I have divided the below explanation in two parts :</p><p><strong>Part 1</strong> : on how to create embeddings on the chucks of documents while also extracting and saving tables and images separately with proper marker of page numbers and document name etc.</p><p><strong>Part 2</strong>: This part will be focused on creating a chat bot which will query the vector database created in first part while also retrieving the relevant images and tables which were also saved while executing the first part.</p><p>Toolset used is Langchain, Chroma DB, Sentence Transformer, SpirePDF, pymupdf4llm</p><p><strong>Part 1: Creating embedding and extracting images and tables:</strong></p><p>Start with the following imports:</p><pre>import gc<br>import glob<br>from dotenv import load_dotenv<br>from langchain.text_splitter import CharacterTextSplitter<br>from langchain_chroma import Chroma<br>from langchain_community.embeddings.sentence_transformer import (<br>SentenceTransformerEmbeddings,<br>)<br>from langchain_core.documents import Document<br>from spire.pdf import *<br>import pymupdf4llm<br>import fitz<br>import pandas as pd</pre><p>Define Main function which will be calling all the functions to embed chunks and also to extract tables and images.</p><ol><li>Load environment variables</li><li>Define the vector store</li><li>Reset the vector store collection</li></ol><pre>def main():<br>    load_dotenv()<br><br>    # create the open-source embedding function<br>    embedding_function = SentenceTransformerEmbeddings(model_name=&quot;all-mpnet-base-v2&quot;)<br><br>    # Define your vectore store with the name &quot;Project_NAME&quot;<br>    vectorstore = Chroma(&quot;Project_NAME&quot;, embedding_function, &quot;./chroma_name&quot;,collection_metadata={&quot;hnsw:space&quot;: &quot;cosine&quot;})<br><br>    # I prefer to reset the collection every time I run this code, but you can impement<br>    # or ignore this option based on your requirement.<br>    # this helps in avoiding creating a duplicte embeddings<br>    vectorstore.reset_collection()<br>    <br>    # defining a counter for images<br>    image_count = 0</pre><p><strong>Section 1</strong>: Now we start loading the pdf documents from the local folder. You can also customize the code for docx or any other format as per your choice. I have taken PDF’s as its widely used. the detailed explanation is in the comments of the code.</p><pre>    # pick all the pdfs from the local folder to be eembedded<br>    pdf_names = list(glob.glob(&quot;pdf\\*.pdf&quot;))<br><br>    for filepath in pdf_names:<br>        # each pdf name will create a file path with its own name to store a<br>        # tables and images <br>        print(filepath) <br><br>        # clear the garbage collection<br>        gc.collect() <br><br>        # Create a PdfDocument object<br>        doc = PdfDocument()<br><br>        # Load a PDF document<br>        # the below object will be used in below code to extract page <br>        # level information<br>        doc.LoadFromFile(filepath) <br>        <br>        #loading as this will plugin will help extarct the tables from pdf<br>        tableDoc = fitz.open(filepath) <br><br>        # laoding as this will help extract the images from the pdf<br>        imageDir = getdirname(filepath)<br>        image_helper = PdfImageHelper()<br><br>        # extarct the text from the pdf for each page with page_chunks true<br>        output = pymupdf4llm.to_markdown(filepath, page_chunks=True)</pre><p><strong>Section 2:</strong> Below is continuation in the above for loop showing how to extract tables from each page of the PDF and storing it in the local directory. Please follow the comments in the below code.</p><pre>     # Loop through the pages in the document<br>     # I am starting from page number 4 as initial page is just contents/tables<br>     # I want to ingnore those as it messes the embeddings and gives wrong info<br>        for i in range(4,doc.Pages.Count):<br><br>            # this is print is just for debugging and tracking the page number<br>            print(i)<br>            <br>            # setting a flag to just confirm if page has table<br>            hasTable = 0<br><br>            # this tableDoc object was defined in previous block using fitz <br>            # plugin<br>            tablePage = tableDoc[i]<br><br>            # check if the page has any tabular information<br>            tables = tablePage.find_tables()<br><br>            # define the path where this table will be stored<br>            pathToStoreTable = f&quot;table\\&quot; + imageDir + &quot;\\&quot; + str(i)<br>            j = 1<br><br>            # extracting and store each table availabe on the page<br>            for table in tables:<br>                # Process each table here<br>                hasTable = 1<br><br>                # create the path if it does not exist already<br>                if not os.path.exists(pathToStoreTable):<br>                    os.makedirs(pathToStoreTable)<br><br>                # create a pickle file name under which the table information<br>                # will be stored<br>                pickleTableName = pathToStoreTable+&quot;\\table&quot;+str(j)+&quot;.pkl&quot;<br><br>                # extract the table in dataframe format from the table.<br>                df = pd.DataFrame(table.extract())<br><br>                # convert the dataframe to pickle with pickleTableName created <br>                # two steps above<br>                df.to_pickle(pickleTableName)<br>                <br>                # This print is just for the debugging purpose to print <br>                # the content of the table, you can turn if off if not required<br>                print(table.extract())<br><br>                # move the counter<br>                j = j + 1</pre><p><strong>Section 3:</strong> Below is continuation in the for loop defined in section 1 showing how to extract images from each page of the PDF and storing it in the local directory. Please follow the comments in the below code.</p><pre>            # extract image information using the image_helper object defined <br>            # in Section 1 <br>            images_info = image_helper.GetImagesInfo(doc.Pages[i])<br><br>            # Save images to specified location with specified format extension<br>           <br>            # flag to check if the document page has image or not<br>            hasImage = 0<br><br>            for j in range(len(images_info)):<br>                hasImage = 1<br><br>                # define the path to store each image on the page<br>                # Format for directory is pdf\&lt;PDF_FILE_NAME&gt;\&lt;PAGE_NUMBER&gt;<br>                pathToStoreImage = f&quot;pdf\\&quot; + imageDir+&quot;\\&quot;+str(i)<br><br>                # create the path to store the image if does not exist already<br>                if not os.path.exists(pathToStoreImage):<br>                    os.makedirs(f&quot;pdf\\&quot; + imageDir+&quot;\\&quot;+str(i))<br><br>                # extract the image information from the page<br>                image_info = images_info[j]<br><br>                # covert the image information in file format<br>                output_file = pathToStoreImage+&quot;\\image&quot;+str(j)+&quot;.png&quot;<br>                <br>                # Save the final image file in the image output directory  <br>                image_info.Image.Save(output_file)<br><br>                # increment the image counter by 1<br>                image_count += 1</pre><p><strong>Section 4:</strong> Below is continuation in the for loop defined in section 1 showing how to extract text from each page of the PDF and storing it in the embedded form in the vector database.</p><pre>            # get the markdown text for given page number i from the ouput <br>            # variable defined in section 1<br>            text = output[i].get(&quot;text&quot;)<br><br>            # divide the text on each page further into chunks of 500 characters<br>            text_chunks = get_text_chunks(text)<br><br>            # store the text chunks in vectore store database with the filepath<br>            # of where the image and tables are stored and also flat whether <br>            # page has image or table information or not<br>            storetextembedding(text_chunks, vectorstore, filepath, i, hasImage, hasTable)<br><br>if __name__ == &#39;__main__&#39;:<br>    main()</pre><p><strong>Section 4A:</strong> In section we will see the functions which were used in section 4.</p><pre># function defined to split the text in chunk size of 500 chars with <br># overlap of 200 chars<br>def get_text_chunks(text):<br>    <br>    # define the textsplitter function<br>    text_splitter = CharacterTextSplitter(<br>        chunk_size=500,  #This means thousand characters<br>        chunk_overlap=200,<br>        length_function=len,<br>        separator=&quot;\n&quot;<br>    )<br>    <br>    # create chunks based on the above text splitter function    <br>    chunks = text_splitter.split_text(text)<br><br>    # return the collection of chunks<br>    return chunks<br><br>#funtion to store the text embedding of collection of chunks<br>def storetextembedding(text_chunks, vectorstore, file, pagenumber, hasImage, hasTable):<br><br>    loadingdocuments =  []<br><br>    # create a collection of documents to be loaded in vectore store<br>    for text in text_chunks:<br>        # define the doucment with text, and metadata with filename information<br>        # page number to which this chunk belongs<br>        # whether this page has image and table information in the form of flags<br>        # &quot;imagePresent&quot;: hasImage, &quot;tablePresent&quot;:hasTable        <br>        document_1 = Document(page_content=text, metadata={&quot;file_name&quot;: file, &quot;pagenumber&quot;: pagenumber, &quot;imagePresent&quot;: hasImage, &quot;tablePresent&quot;:hasTable})<br>        loadingdocuments.append(document_1)<br><br>    # load the entire collection of documents of collection of chunks of text <br>    # on a page in the vectore store<br>    if len(loadingdocuments) != 0:<br>        vectorstore.add_documents(documents=loadingdocuments)<br><br>    # retur the file name<br>    return file</pre><p>With this we have completed the part 1 of the coding. Now we will turn our focus on part 2 of the application where we create a chat bot functionality using stream lit. Hope I have not lost you ……….</p><p><strong>Part 2: Chatbot implementation to retrieve text, images and tables for the query</strong></p><p>For chatbot UI we are going to use Streamlit along with langchain, chromaDB. In support of GUI we will also be using some HTML and CSS.</p><p>There are two parts to GUI. One is HTML template file and other is the core AI engine file which supports the chatbot operations. Both are python files. I will not be explaining the HTML template file. As its nothing but consist of different elements of GUI created using HTML and CSS. In the end I will be pasting the HTML template PY file as it is. Same will also be available in my Git repo.</p><p>One thing to remember is that below core chatbot file is to be run as Streamlit file using streamlit run command and not a regular python file. Now lets look at the code for the chatbot engine.</p><p>Start with the following imports:</p><pre>import base64<br>import glob<br>from pathlib import Path<br><br>import pandas as pd<br>import requests<br>import streamlit as st<br>from PyPDF2 import PdfReader<br>from attr import validators<br>from dotenv import load_dotenv<br>from transformers import pipeline<br><br>#htmlTemplates file will be shared at the end<br>from htmlTemplates import css, bot_template, user_template</pre><p>Define Main function which will be calling all the functions to embed chunks and also to extract tables and images.</p><ol><li>Load environment variables</li><li>Define the primary chatbot GUI using Streamlit API</li></ol><pre>def main():<br>    # load env variable<br>    load_dotenv()<br><br>    # Define page title<br>    st.set_page_config(page_title=&quot;Chat with project solution&quot;,<br>                       page_icon=&quot;:books:&quot;)<br>    <br>    # define the streamlit parameters<br>    st.write(css, unsafe_allow_html=True)<br><br>    # check if the session is active<br>    if &#39;clicked&#39; not in st.session_state:<br>        st.session_state.clicked = False<br><br>    # define the section where user will post the question<br>    user_question = st.text_input(&quot;Ask a question about your project solution:&quot;,key=&#39;text_input_widget&#39;, on_change=text_input_handler)<br><br>    # define checkbox to get userinput whether user wants to include <br>    # image or tables in the chatbot answer or not<br>    st.checkbox(&quot;Include Image&quot;,key=&quot;include_image&quot;,on_change=click_image)<br>    st.checkbox(&quot;Include Tables&quot;, key=&quot;include_table&quot;, on_change=click_table)<br><br>    # check the session state to ensure that there is no chat history or <br>    # conversation state from previous run<br>    if &quot;conversation&quot; not in st.session_state:<br>        st.session_state.conversation = None<br>    if &quot;chat_history&quot; not in st.session_state:<br>        st.session_state.chat_history = {}<br><br>    # if user has posted the question than handle the user input and <br>    # retrieve the required document from the vector database<br>    if user_question:<br>        handle_userinput_getdocuments(user_question)<br><br>if __name__ == &#39;__main__&#39;:<br>    main()</pre><p><strong>Section 1: </strong>here we will define the function handle_userinput_getdocuments which will be used the retrieve the document and display the query and answer in chat format to the user.</p><pre># define the function to retrieve the answer for question posted by the user<br>def handle_userinput_getdocuments(user_question):<br>    # define the embedding function, this should be same as the <br>    # one defined while creating the embedding<br>    embedding_function = SentenceTransformerEmbeddings(model_name=&quot;all-mpnet-base-v2&quot;)<br><br>    # define the verctore store. this should be also be the same in which <br>    # the embedding was stored.<br>    vectorstore = Chroma(&quot;Project_MCPTT&quot;, persist_directory=&quot;./chroma_mcptt&quot;,<br>                         embedding_function=embedding_function, collection_metadata={&quot;hnsw:space&quot;: &quot;cosine&quot;})<br><br>    # create a pipelin with summarization effect on each of the retrieved <br>    # document  <br>    summarizer = pipeline(&quot;summarization&quot;, model=&quot;facebook/bart-large-cnn&quot;)<br><br>    # Retrieve and generate using the relevant snippets of the documents<br>    retriever = vectorstore.as_retriever()<br><br>    # retrieve the documets using the retriever of the vectore store.<br>    docs = retriever.get_relevant_documents(user_question)<br><br>    responsetoquestion = &quot;&quot;<br>    filename = &quot;&quot;<br>    pageNumber = &quot;&quot;</pre><p><strong>Section 2:</strong> Now we traverse through each of the retrieved document and extract text, image and table from it and append to the response. We also add the link to the document along with the page number so that if user wants he can open the document and check the answer itself. It helps improve the eXplainability of the AI (XAI) solution.</p><pre>    # traverse through each document retrieved by the retriever.<br>    for text in docs:<br>        # for given doc extract the filename<br>        newfilename = text.metadata[&#39;file_name&#39;]<br>        # for given doc extract the page number<br>        newpageNumber = text.metadata[&#39;pagenumber&#39;]<br>        # for given doc extract the flag whether there is imagepresent<br>        imagePresent = text.metadata[&#39;imagePresent&#39;]<br>        # for given doc extract the flag whether there is any table present<br>        tablePresent = text.metadata[&#39;tablePresent&#39;]<br>        <br>        # if filename is not asame as the previous document, treat it as new <br>        # filename and append a link to it to the answer response<br>        if filename != newfilename:<br>           filename = newfilename<br>           print(&quot;Filename:&quot;,filename)<br>           file_url = f&quot;http://localhost:8000/{filename}&quot;<br>           responsetoquestion += f&quot;From: &lt;a href=&#39;{file_url}&#39; download&gt;{filename}&lt;/a&gt; | &quot;<br>        <br>        # if page number is not asame as the previous pagenumber, <br>        # treat it as new pagenumber<br>        # and append a link to it to the answer response<br>        if pageNumber != newpageNumber:<br>           pageNumber = newpageNumber<br>           responsetoquestion += f&quot;&lt;p style=&#39;color:Tomato;&#39;&gt;Page Number: {pageNumber} &lt;/p&gt;&quot;<br><br>        # create summary of response text retrieved from the page<br>        summary = summarizer(text.page_content, min_length=5, max_length=300)<br>        # append summary of text to the response<br>        responsetoquestion = responsetoquestion + summary[0][&quot;summary_text&quot;] + &quot;\n &lt;br&gt;&quot;<br><br>        # if the flag image present is true and user has asked to see relevant <br>        # image in the response<br>        # call the function to append the image to the response<br>        if imagePresent == 1 and st.session_state[&#39;include_image&#39;]:<br>            responsetoquestion = appendImage(responsetoquestion,newfilename,newpageNumber)<br>        <br>        # if the flag table present is true and user has asked to see relevant <br>        # table in the response<br>        # call the function to append the table the response<br>        if tablePresent == 1 and st.session_state[&#39;include_table&#39;]:<br>            responsetoquestion = appendTable(responsetoquestion, newfilename, newpageNumber)</pre><p>Below lines will be outside the above for loop….</p><pre>    # if the user opted to include image in the answer<br>    # we include the _IMG at the end of question in chat history <br>    if st.session_state[&#39;include_image&#39;]:<br>        user_question = user_question + &quot;_IMG&quot;<br>    <br>    # if the user opted to include table in the answer<br>    # we include the _TAB at the end of question in chat history<br>    if st.session_state[&#39;include_table&#39;]:<br>        user_question = user_question + &quot;_TAB&quot;<br><br>    # add the question and the final response to the chat hisotry map in the <br>    # chat session<br>    st.session_state.chat_history[user_question] = responsetoquestion<br><br>    # display the entire chat history<br>    displaychathistory()</pre><p>Some of the functions which we used in the above 2 code blocks….</p><p>This method is to display the complete chat history….</p><pre>def displaychathistory():<br>    reversechat = dict(reversed(list(st.session_state.chat_history.items())))<br>    for i, (k, v) in enumerate(reversechat.items()):<br>        st.write(user_template.replace(&quot;{{MSG}}&quot;, k), unsafe_allow_html=True)<br>        st.write(bot_template.replace(&quot;{{MSG}}&quot;, v), unsafe_allow_html=True)</pre><p>This method is use to append the image to the response….</p><pre>def appendImage(responsetoquestion,newfilename,newpageNumber):<br>    # from the page number, filename construct the directory <br>    # where the images are stored<br>    imageDir = getdirname(newfilename)<br><br>    # covert it to path where images are stored<br>    pathToStoreImage = f&quot;pdf\\&quot; + imageDir + &quot;\\&quot; + str(newpageNumber)<br><br>    # get list of all the images in the above directory<br>    imageNames = list(glob.glob(pathToStoreImage+&quot;\\*.png&quot;))<br><br>    # converse throuch all the image names<br>    for filepath in imageNames:<br>        print(&quot;Image file path&quot;,filepath) # this just of debugging purpose<br><br>        # construct the url for image<br>        file_url = f&quot;http://localhost:8000/{filepath}&quot;<br>        print(&quot;File URL&quot;,file_url)<br>        imageTag = f&quot;&lt;img src=&#39;{file_url}&#39;&gt;&lt;br&gt;&quot;<br><br>        # append the image url to the response and move to next image or exit<br>        responsetoquestion = responsetoquestion + imageTag<br>    # return the response with the image names with url embedded <br>    # in html format<br>    return responsetoquestion</pre><p>This method is use to append the image to the response….</p><pre>def appendTable(responsetoquestion,newfilename,newpageNumber):<br>    # from the page number, filename construct the directory <br>    # where the tables are stored<br>    tableDir = getdirname(newfilename)<br><br>    # covert it to path where tables are stored<br>    pathToStoreTable = f&quot;table\\&quot; + tableDir + &quot;\\&quot; + str(newpageNumber)<br><br>    # get list of table filenames in pkl format from directory<br>    tableNames = list(glob.glob(pathToStoreTable+&quot;\\*.pkl&quot;))<br><br>    for filepath in tableNames:<br>        print(&quot;Table file path&quot;,filepath) # for debugging purpose<br>        # convert the pickle file to dataframe<br>        df = pd.read_pickle(filepath)<br><br>        # remove the very first column from the dataframe<br>        df = df.iloc[1:]<br><br>        #set the css style for the table<br>        df.style.set_table_styles([{&#39;selector&#39;: &#39;&#39;, &#39;props&#39;: [(&#39;border&#39;, &#39;2px solid green&#39;)]}])<br>      <br>        # append the table content to response in html format       <br>        responsetoquestion = responsetoquestion + df.to_html(index=False, header=False, border=5)<br><br>    # return the final response after adding all the tables<br>    return responsetoquestion</pre><p>In this chatbot solution I have not summarized the final response using a prompt. We can also do that. But when we summarise all the response sections using a prompt and present it as single answer, we loose track of the page and document number. As the final answer is summary of all the text received from vector search irrespective. Instead that we had opted for more detailed answer where we have shown summary of each or retrieved text chunk along with images/table on that page to which the chunk belongs to. The answer will not look clean but will be helpful to technical folks, who for the most part are looking for direction to the right document rather than some final answer (which many a times are very doubt full).</p><p>Code for htmltemplate file: Save it as htmlTemplates.py and put it in same directory as core chatbot engine py file.</p><pre>css = &#39;&#39;&#39;<br>&lt;style&gt;<br>.chat-message {<br>    padding: 1.5rem; border-radius: 0.5rem; margin-bottom: 1rem; display: flex<br>}<br>.chat-message.user {<br>    background-color: #2b313e<br>}<br>.chat-message.bot {<br>    background-color: #475063<br>}<br>.chat-message .avatar {<br>  width: 20%;<br>}<br>.chat-message .avatar img {<br>  max-width: 78px;<br>  max-height: 78px;<br>  border-radius: 50%;<br>  object-fit: cover;<br>}<br>.chat-message .message {<br>  width: 80%;<br>  padding: 0 1.5rem;<br>  color: #fff;<br>}<br>&#39;&#39;&#39;<br><br>bot_template = &#39;&#39;&#39;<br>&lt;div class=&quot;chat-message bot&quot;&gt;<br>    &lt;div class=&quot;avatar&quot;&gt;<br>        &lt;img src=&quot;http://localhost:8000/AI.png&quot;&gt;<br>    &lt;/div&gt;<br>    &lt;div class=&quot;message&quot;&gt;&lt;span style=&quot;white-space: pre-line&quot;&gt;{{MSG}}&lt;/span&gt;&lt;/div&gt;<br>&lt;/div&gt;<br>&#39;&#39;&#39;<br><br>user_template = &#39;&#39;&#39;<br>&lt;div class=&quot;chat-message user&quot;&gt;<br>    &lt;div class=&quot;avatar&quot;&gt;<br>        &lt;img src=&quot;http://localhost:8000/users.png&quot;&gt;<br>    &lt;/div&gt;    <br>    &lt;div class=&quot;message&quot;&gt;&lt;span style=&quot;white-space: pre-line&quot;&gt;{{MSG}}&lt;/span&gt;&lt;/div&gt;<br>&lt;/div&gt;<br>&#39;&#39;&#39;<br><br>file_list_template = &#39;&#39;&#39;<br>&lt;div class=&quot;chat-message user&quot;&gt;<br>    &lt;div class=&quot;avatar&quot;&gt;<br>        &lt;img src=&quot;http://localhost:8000/users.png&quot;&gt;<br>    &lt;/div&gt;    <br>    &lt;div class=&quot;message&quot;&gt;&lt;span style=&quot;white-space: pre-line&quot;&gt;{{MSG}}&lt;/span&gt;&lt;/div&gt;<br>&lt;/div&gt;<br>&#39;&#39;&#39;<br><br>check_box = &#39;&#39;&#39;<br>   &lt;div class=&quot;checkbox-container&quot;&gt;<br>        &lt;div id=&quot;custom-checkbox&quot; style=&quot;width: 20px; height: 20px; border: 1px solid black; display: inline-block; cursor: pointer;&quot; onclick=&quot;toggleCheckbox()&quot;&gt;&lt;/div&gt;<br>        &lt;label for=&quot;custom-checkbox&quot;&gt;Custom Div Checkbox&lt;/label&gt;<br>   &lt;/div&gt;<br>   &lt;br&gt;<br>    &lt;input type=&quot;submit&quot; value=&quot;Submit&quot; onclick=&quot;return sendDivCheckboxValue();&quot;&gt;<br>&#39;&#39;&#39;</pre><p>Folder structure will all the files will look like below. pdf folder will have all the pdf files for which you want to create the embeddings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*QHNDNG5QYeu5p-udtYunwg.png" /><figcaption>Folder structure for the solution.</figcaption></figure><p>GitHubLink: <a href="https://github.com/Naina2023/ChatBOT">Naina2023/ChatBOT</a></p><p>References:</p><ol><li>Streamlit : <a href="https://docs.streamlit.io/">https://docs.streamlit.io/</a></li><li>Langchain: <a href="https://python.langchain.com/docs/introduction/">https://python.langchain.com/docs/introduction/</a></li><li>ChormaDB : <a href="https://www.trychroma.com/">https://www.trychroma.com/</a></li><li>PyMuPDF : <a href="https://pymupdf.readthedocs.io/en/latest/pymupdf4llm/index.html">https://pymupdf.readthedocs.io/en/latest/pymupdf4llm/index.html</a></li></ol><p>5. Langchain + Chromabd: <a href="https://python.langchain.com/docs/integrations/vectorstores/chroma/">https://python.langchain.com/docs/integrations/vectorstores/chroma/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21cbd32ac7cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>