<?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 Jaswant Jonnada on Medium]]></title>
        <description><![CDATA[Stories by Jaswant Jonnada on Medium]]></description>
        <link>https://medium.com/@jaswanth04?source=rss-9377ebaddb70------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qyBwXmD7WWx2BCAuLMUnZw.jpeg</url>
            <title>Stories by Jaswant Jonnada on Medium</title>
            <link>https://medium.com/@jaswanth04?source=rss-9377ebaddb70------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 13:21:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jaswanth04/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[Stop Calling the LLM Twice for the Same Question: A Practical Guide to Semantic Caching]]></title>
            <link>https://blog.stackademic.com/stop-calling-the-llm-twice-for-the-same-question-a-practical-guide-to-semantic-caching-98863b91159e?source=rss-9377ebaddb70------2</link>
            <guid isPermaLink="false">https://medium.com/p/98863b91159e</guid>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Jaswant Jonnada]]></dc:creator>
            <pubDate>Sat, 26 Sep 2026 10:25:29 GMT</pubDate>
            <atom:updated>2026-09-29T13:20:32.661Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*guuyNIzzwAakvRLdATtdFA.png" /><figcaption>Two paths to the same answer: the long, expensive route through the LLM — or the instant shortcut through a semantic cache. Semantic caching lets your users skip the slow road by reusing answers to questions you’ve already answered, saving cost and latency without sacrificing quality.</figcaption></figure><p>Every time you ask a large language model a question, it costs you money, time, and compute. Now imagine if many of those questions didn’t require the model at all — because the same or a very similar answer had already been generated before. That is the idea behind semantic caching.</p><p>In this article, I’ll explain what semantic caching is, why it matters, where it shines, and where it doesn’t. I’ll then walk through the three search strategies (exact, approximate, hybrid), how to evaluate and tune the approximate strategy, and how to design a TTL strategy that keeps your cache fresh. After that, I’ll show you how to measure performance, what the numbers mean in practice, and how to protect the cache from wrong answers — the quiet risk of caching. I’ll finish with a production checklist, a complete retrieval flowchart, and the storage rules that make the whole system compound in value over time.</p><h3>What Is Semantic Caching for LLMs?</h3><p>When you call an LLM, the model reprocesses your prompt, generates tokens, and returns an answer. That entire operation — network call, inference, token generation — happens again and again, even when users are asking essentially the same question in different words.</p><p>Semantic caching is the practice of storing LLM responses so that a repeated or closely related question can be answered from the cache instead of invoking the model again. The word “semantic” is the key: unlike a traditional cache that only matches exact strings, a semantic cache understands meaning, so “What is the refund policy?” and “Can I get my money back?” can be treated as the same question.</p><p>The result is a system that learns as it runs: the more questions it answers, the more similar future questions can be handled instantly, without burning tokens or budget.</p><h3>Why Do We Need It? (Uses of Semantic Caching)</h3><p>Semantic caching is useful for several reasons:</p><ul><li><strong>LLM responses are expensive.</strong> Every inference call consumes compute and tokens. At scale, even small per-request costs multiply into significant bills. Caching lets you pay for an answer once and reuse it many times.</li><li><strong>Many questions have stable, generic answers.</strong> Some questions can be answered the same way every time, either from a knowledge base or from information that doesn’t change. Forcing the LLM to recompute these is wasteful.</li><li><strong>RAG pipelines repeat a lot of work.</strong> In retrieval-augmented generation, every question triggers two expensive steps: a vector search over your documents and an LLM call to compose the answer. If a user asks a question that has already been answered, both steps are pure overhead. A semantic cache lets previously answered questions resolve instantly, saving the vector search and the LLM hit.</li><li><strong>Traffic patterns are naturally repetitive.</strong> Real users ask the same things over and over — the same refund question, the same setup question, the same product query. Semantic caching is specifically designed to exploit this repetition.</li></ul><p>In short, semantic caching is not about replacing the LLM — it’s about making sure you don’t pay full price for work you’ve already done.</p><h3>The Benefits</h3><p><strong>1. Lower cost.</strong> This is the most immediate and measurable win. By serving many requests from the cache, you cut the number of LLM invocations dramatically, which directly reduces your token spend and infrastructure costs.</p><p><strong>2. Better latency.</strong> A cached answer is retrieved in milliseconds from memory, compared to the seconds an LLM call can take. Users notice faster responses, and your application feels snappier.</p><p><strong>3. More predictable load.</strong> With fewer requests hitting the model and the vector database, your system has spare capacity for genuinely new queries, and you’re less likely to hit rate limits during traffic spikes.</p><p><strong>4. Consistent answers.</strong> Caching identical questions produces identical answers, which can improve user trust and makes your system’s behavior more stable and easier to debug.</p><h3>Where Should It Be Used?</h3><p>A great starting point is <strong>answering informational questions from a RAG pipeline</strong>. Consider a customer support chatbot backed by a help center. Users repeatedly ask about refunds, shipping times, and password resets. These are informational questions with fairly stable answers, so caching them is safe and highly effective. Any domain with a large base of users asking overlapping questions — e-commerce, banking, HR, education — benefits from this pattern.</p><p>Other good candidates:</p><ul><li><strong>Enterprise knowledge portals</strong>, where employees repeatedly ask about internal policies, IT setup, or onboarding steps.</li><li><strong>Public FAQs and documentation assistants</strong>, where the corpus changes slowly and the questions are highly repetitive.</li><li><strong>E-commerce product assistants</strong>, where descriptions and specs change rarely compared to prices (which should not be cached).</li><li><strong>Language learning or tutoring bots</strong>, where grammar explanations remain constant.</li></ul><p>The general rule: <strong>use semantic caching when the answers are mostly deterministic and independent of the specific user asking the question.</strong></p><h3>Where Should It NOT Be Used?</h3><p>There are cases where caching can do more harm than good. The clearest example is <strong>agentic AI</strong>.</p><p>Imagine an agent that must select a tool, extract parameters from a user’s question (like a date, a city, or an account number), and pass those to the tool for execution. Here, the output depends heavily on personalization and the specific values in the question. “Book a flight to Paris tomorrow” and “Book a flight to Paris next week” look similar semantically, but they produce completely different tool calls. Caching the first response and returning it for the second would be a serious correctness bug.</p><p>More generally, avoid caching when:</p><ul><li>Answers depend on real-time or user-specific data (prices, inventory, account balances, personalized recommendations).</li><li>The response must be guaranteed fresh and accurate by law or policy (medical advice, legal guidance, financial filings).</li><li>The question drives an action with side effects (sending an email, creating an order, executing a trade), not just an informational answer.</li><li>The content is highly personalized, or contains personally identifiable information that must not be persisted.</li></ul><p>When in doubt, ask: <strong>would returning a slightly earlier version of this answer be acceptable?</strong> If the answer is no, don’t cache it.</p><h3>The Three Ways to Search</h3><p>A semantic cache can find a stored answer in three ways:</p><ol><li><strong>Exact search.</strong> The incoming question is matched character-for-character against stored questions. This is simple, extremely fast, and 100% accurate — but it misses questions that ask the same thing in different words.</li><li><strong>Approximate search.</strong> The question is embedded into a vector and compared with stored questions by semantic similarity. This catches paraphrases and near-duplicates, but it requires choosing a similarity threshold and can occasionally return a wrong match.</li><li><strong>Hybrid approach.</strong> Combine both: use exact search for guaranteed hits and approximate search to catch everything else. As we’ll see, this gives you the best of both worlds.</li></ol><h3>What Should You Store?</h3><p>At its simplest, a semantic cache is a key-value store where the <strong>question is the key</strong> and the <strong>answer is the value</strong>. But you don’t have to stop there. The value can be a rich object containing the answer, the retrieved source documents, the confidence score, timestamps, or any other metadata you might want — such as the language of the question, the model version that produced the answer, or the cost it took to generate it. Storing this extra context makes your cache more than a lookup table; it becomes a small analytics layer.</p><p>A good rule of thumb: store only what you can meaningfully act on at read time. Adding filters (language, tenant, region, model version) costs storage but pays off by letting you serve exactly the right answer to the right user.</p><h3>Essential Cache Features</h3><p>Whatever approach you choose, a production-ready semantic cache should support these features:</p><ol><li><strong>Storage.</strong> A place to hold key-value pairs, usually in memory for speed.</li><li><strong>Fast retrieval.</strong> The ability to look up a stored value by its key in milliseconds.</li><li><strong>Expiration / TTL.</strong> A time-to-live on entries so the cache stays fresh and doesn’t serve stale answers forever. This lets you automatically retire old answers when you know the underlying information changes.</li><li><strong>Filtering / metadata-based selection.</strong> The ability to narrow results by metadata. For example, in a multilingual chatbot, a user might ask in English while the cached answer is in Chinese. If you store the language as metadata during writes, you can use it as a filter during reads to only retrieve English responses. Language is just one example — you might also filter by region, product, tenant, or model version, depending on your use case.</li></ol><h3>Exact Search — What is it ?</h3><p>Exact matching is typically done with <strong>key-value stores such as Redis, Cassandra, or MongoDB</strong>. These systems keep data in memory (or close to it), which makes them extraordinarily fast.</p><p>Their strengths are well known: they natively support storage, retrieval, TTL, and metadata filtering, and they’re battle-tested at massive scale.</p><p>Their weakness for this use case is that they’re literal — they match on the exact key. To make them useful for semantic caching, you often end up constructing <strong>complex, composite keys</strong> (for example, language:tenant:category:normalized-question), and you still can&#39;t catch a paraphrase that doesn&#39;t normalize to the same key. This is why exact matching alone is rarely enough.</p><h3>Approximate Search — What is it ?</h3><p>Approximate matching relies on <strong>vector databases such as Milvus, OpenSearch, Chroma, FAISS</strong>, and similar tools. The question is converted into a vector embedding and compared with stored vectors by distance or similarity scoring.</p><p>Most vector databases provide storage and retrieval, and many (Milvus being a good example) support metadata filtering natively. However, they typically <strong>do not offer TTL</strong>, so entries can linger and go stale unless you build a cleanup mechanism yourself.</p><p>Their superpower is resilience to wording. Because the search is based on meaning rather than exact text, they handle typos, synonyms, and entirely rewritten questions gracefully. Their challenge is precision: you must calibrate the similarity threshold carefully to avoid returning a plausible-sounding but wrong answer.</p><p>Many vector databases also support filtering. For example, if you need to filter the data by language and then perform vector search on the filtered data. Using this would make the system more robust.</p><h3>The Hyper-parameters That Shape the Approximation</h3><p>Because approximate search relies on machine-learned representations, several knobs determine its quality:</p><p><strong>1. Score and threshold.</strong> Every vector search returns a similarity score for each candidate. The threshold is the minimum score at which you trust a candidate as a genuine match. Set it too high and you miss paraphrases (lower recall); set it too low and you return wrong answers (lower precision). The right value is not guesswork — it should be calibrated on a labeled dataset and re-checked whenever you change your embedding model.</p><p><strong>2. The choice of embedding model.</strong> The embedding model defines what “similar” means.</p><ul><li><strong>Proprietary options</strong> like OpenAI’s text-embedding-3-small / text-embedding-3-large are easy to call via API, are consistently high quality, and require zero infrastructure — but incur per-token cost and external dependency.</li><li><strong>Open-source options</strong> from Hugging Face such as sentence-transformers/all-MiniLM-L6-v2, BAAI/bge-large-en, intfloat/e5-large-v2, or model families from Cohere and Google&#39;s Gemini can be self-hosted, cost nothing per query, and can be fine-tuned on your domain. They trade away some convenience for full control and privacy.</li></ul><p>Your choice should balance embedding quality on your specific domain, latency, infrastructure cost, and whether you’re allowed to send questions to a third-party API at all.</p><p><strong>3. Is a re-ranker necessary, or is the score enough?</strong> A vector database with approximate nearest-neighbor search (ANN) finds candidates quickly but imprecisely. A <strong>re-ranker</strong> (a second, more powerful model that scores the top candidates by actually computing pairwise relevance) can dramatically improve match quality at the cost of added latency and compute.</p><ul><li>If your questions are short and your similarity scores are already well-separated (clear matches vs. clear misses), the raw score is usually enough.</li><li>If your domain has subtle distinctions — e.g., “What is the difference between a refund and a return?” vs. “How do I get a refund?” — a re-ranker like cross-encoder/ms-marco-MiniLM-L-6-v2 can substantially reduce false matches.</li></ul><p>The pragmatic approach: start with a good embedding model and a well-calibrated threshold; add a re-ranker only if evaluation shows an unacceptable wrong-match rate.</p><p><strong>4. Fine-tuning the embedding model.</strong> Out-of-the-box embedding models are trained on general text, not your domain. If your questions use domain jargon, abbreviations, or internal terminology, you can <strong>fine-tune the embedding model on your own question pairs</strong> so that the same meaning maps closer in vector space. Fine-tuning typically improves retrieval quality and can even allow a smaller, faster model to match the quality of a larger one — a direct latency and cost win. It requires a labeled dataset and an evaluation loop, but the payoff is often the biggest quality lever available.</p><h3>How to Select the Best Embedding Model</h3><p>Choosing an embedding model should be an experiment, not an opinion. Follow this process:</p><ol><li><strong>Build a proper annotated dataset.</strong> Collect real (or representative) questions and label them: for each question, mark which previously asked questions (if any) should be considered its semantic duplicate, and which are decoys. This becomes your ground truth. Aim for a few hundred to a few thousand labeled pairs, covering the phrasing variations your users actually produce.</li><li><strong>Conduct experiments.</strong> Embed the labeled questions with each candidate model, run the retrieval logic exactly as it will run in production, and record the results. Test multiple thresholds and, if applicable, with and without a re-ranker.</li><li><strong>Select metrics — and evaluate.</strong> Choose metrics that reflect what you care about in production:</li></ol><h3>Metrics to consider for approximation search</h3><ol><li><strong>precision@1</strong> — of the top-1 retrieved question, how often is it truly a match?</li><li><strong>recall@1</strong> — of all true matches, how many are found in the top-1?</li><li><strong>Mean Reciprocal Rank (MRR)</strong> — rewards correct matches appearing high in the ranking, not just at position 1.</li><li><strong>nDCG</strong> — a graded metric that handles cases where some matches are better than others.</li><li><strong>Latency (p50/p95)</strong> — a slightly better model that triples your retrieval time may not be worth it.</li><li><strong>Cost per query</strong> — embedding cost (for API models) and inference cost (for self-hosted or re-rankers).</li></ol><p>Pick the model that wins on the metric that matters most for your failure mode: if wrong matches are dangerous, weight precision heavily; if users are frustrated by missed paraphrases, weight recall heavily.</p><h3>The Hybrid Approach: The Best of Both Worlds</h3><p>Here’s the key insight: exact search and approximate search have complementary strengths. Exact search is perfect but narrow; approximate search is flexible but fuzzy. By combining them smartly, you get all the benefits — fast storage and retrieval, TTL, and metadata filtering — while minimizing the downsides of each.</p><p>Here is what each piece contributes in a hybrid design:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-QHFnhomWfHF86OTM4pxWA.jpeg" /><figcaption>Responsibility table</figcaption></figure><p>The one notable disadvantage is operational complexity: you need a <strong>pipeline that periodically deletes or flushes stale vectors</strong> from the vector database, since it lacks built-in TTL.</p><h3>The Retrieval Strategy (Flowchart + Algorithm)</h3><p>The flow below is the heart of a hybrid semantic cache. It starts with the cheapest check, escalates only when needed, and only calls the LLM as a last resort.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fCThy7px21odt4nyG99e4w.jpeg" /><figcaption>Retrieval Strategy</figcaption></figure><p>Step by step Algorithm:</p><ol><li><strong>Check the cache for an exact match.</strong> If the incoming question is found verbatim, return the stored answer immediately. This is the cheapest and most reliable path.</li><li><strong>If there’s no exact hit, perform an approximate (vector) search.</strong> Retrieve the top-most similar question and its similarity score.</li><li><strong>Validate the score.</strong> The approximate search is considered successful only if the top match’s score crosses a predefined threshold. If it doesn’t, treat it as a miss — a low score means the cached question is probably not truly the same question.</li><li><strong>Fetch the answer from the cache.</strong> When the similarity check passes, use the matched question’s key to retrieve the final response from the cache, and return it.</li></ol><p><strong>Optimization:</strong> if you want lower latency, steps 1 and 2 can be <strong>run in parallel</strong>, and you can then <strong>always prefer the exact-match result</strong> when both succeed. This is a nice balance of speed and accuracy.</p><h3>When Filtering Is Required</h3><p>If your cache needs metadata filtering (say, by language), reverse the order slightly:</p><ol><li>Run the <strong>vector search first</strong>, applying your metadata filter (e.g., “only English questions”) during the similarity query.</li><li>Then run the <strong>exact search</strong> (with the same filter) against the cache.</li><li>Only consider a match valid if it passes the filter (for example, both the vector hit and the exact hit must be English).</li></ol><p>This ordering matters because the vector database is the component that understands metadata filtering best, and it prevents returning a semantically similar but filtered-out answer.</p><h3>Types of Retrieval Outcomes</h3><p>A given query ends in one of four outcomes, and each one tells you what to do next:</p><ol><li><strong>Exact hit.</strong> The question was found verbatim in the cache. Return the answer immediately; nothing needs to be stored.</li><li><strong>Approximate hit.</strong> A semantically similar question was found by vector search, and its answer was successfully retrieved from the cache. This is the real win of semantic caching — you just answered a brand-new phrasing without calling the LLM.</li><li><strong>Expired hit.</strong> The approximate search found a nearest question, but its cached entry has expired (TTL). You’ll need to regenerate the answer, and you should re-store it.</li><li><strong>No hit.</strong> Nothing matched in the cache or the vector database. This is a genuine new question, so you must call the LLM (and possibly run RAG) from scratch.</li></ol><h3>Storage Strategy</h3><p>What you store — and where — depends on the retrieval outcome:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G45zk9Ontvqk_lFfM8yrqg.png" /></figure><p>The logic is simple and elegant: <strong>every miss or partial hit is an opportunity to make the next query cheaper.</strong> On a no-hit, you write to both stores so future paraphrases can be caught by the vector DB and future identical questions by the exact cache. On an approximate hit, you add the exact question to the cache so the same wording will never need vector search again. Over time, the cache effectively “crystallizes” the most common phrasings into fast, exact lookups.</p><h3>TTL Strategy: Keeping the Cache Fresh</h3><p>Time-to-live is how you tell the cache how old an answer is allowed to be. The right TTL is driven entirely by your business use case:</p><ul><li><strong>Stable content, long TTL.</strong> If your knowledge base rarely changes (onboarding docs, grammar rules, company policies), you can use a very long TTL — even weeks — because answers stay valid.</li><li><strong>Fast-changing content, short TTL.</strong> If answers track volatile data (promotions, prices, news), use a short TTL — minutes to hours — so stale answers expire quickly.</li><li><strong>Event-driven invalidation.</strong> TTL is a blunt instrument. Whenever you <em>know</em> the source data changed, invalidate immediately rather than waiting for expiry.</li></ul><p><strong>A concrete RAG example.</strong> In retrieval-augmented generation, the source of truth is your knowledge base. The best practice is:</p><ol><li><strong>Clear the cache whenever the knowledge base changes and re-indexing happens.</strong> When you re-ingest documents, the old answers are no longer authoritative, so flush the cache at that moment instead of waiting for TTL.</li><li><strong>Treat the vector database separately.</strong> Since vector DBs typically lack TTL, they need their own cleanup pipeline, and it’s often better to clear them <strong>manually during the re-indexing step</strong> rather than on a timer.</li><li><strong>Watch the size of the vector DB.</strong> As rows accumulate, query latency can creep up. A practical rule is to flush the vector DB whenever its row count crosses a threshold where you observe latency degradation — or whenever re-indexing happens.</li><li><strong>Prefer a unified flush script.</strong> Rather than juggling two partial cleanups, write a single script that cleans both the cache and the vector DB together. It’s easier to reason about, reduces the chance of serving stale vectors with fresh cache entries (or vice versa), and gives you one button to press when the knowledge base changes.</li></ol><p>The mental model: <strong>TTL is your automatic safety net; knowledge-base invalidation is your surgical cleanup; and the two together keep the cache both fast and correct.</strong></p><h3>Measuring the Performance of Your Semantic Cache</h3><p>You can only improve what you measure. A semantic cache can deliver impressive cost and latency savings on paper — but until you instrument it, you don’t actually know whether it’s helping, or whether it’s silently serving too many wrong answers or stale content. So the metrics below aren’t vanity numbers; they’re the feedback loop that tells you when to raise a threshold, shorten a TTL, flush the vector DB, or change your embedding model.</p><p>Here are the metrics to track:</p><ul><li><strong>Exact hit rate</strong> — the fraction of queries answered by the literal key-value lookup. High exact hit rate means your traffic is repetitive; it also grows over time as common phrasings get cached.</li><li><strong>Approximate hit rate</strong> — the fraction of queries answered via semantic matching without calling the LLM. This is the true measure of <em>semantic</em> value: paraphrases you never had to regenerate.</li><li><strong>Overall hit rate</strong> — exact + approximate hits divided by total queries. This is your headline number for how much LLM work you’ve avoided. Miss rate = 1 − overall hit rate.</li><li><strong>Wrong-match rate (false positive rate)</strong> — of the approximate hits served, how many were actually incorrect? This is the most important quality metric; even a small percentage of wrong answers can erode user trust.</li><li><strong>Cache freshness / staleness</strong> — what fraction of served answers were expired or regenerated due to TTL, and how old is the typical served entry? This tells you whether your TTL is too aggressive (high regeneration, low freshness benefit) or too lax (stale answers).</li><li><strong>Latency savings</strong> — compare response time percentiles (p50, p95, p99) for cache hits vs. LLM calls. This is your user-visible win.</li><li><strong>Cost savings</strong> — estimated from hits × average tokens saved per query × price per token, or simply the reduction in LLM API spend over time.</li><li><strong>Fill / write volume</strong> — how many new entries your cache adds per day. It helps you plan storage, keep vector DB row counts in check, and detect pathological growth (e.g., unbounded variants of the same question).</li></ul><p>Track these over time in a dashboard, and review them whenever you change your embedding model, threshold, or TTL policy. That’s the loop that turns a decent cache into a great one: change one variable, watch the metrics, and keep what works.</p><h3>A Worked Example: What a 60% Hit Rate Actually Saves You</h3><p>Let’s make the benefits concrete. Imagine a customer-support chatbot that handles <strong>10,000 questions a day</strong>. Every uncached question has to run a full RAG pipeline: a vector search over the help center, then an LLM call to compose the answer. Each LLM call consumes on average <strong>400 input tokens and 300 output tokens</strong>.</p><p>The average uncached query takes about <strong>2.5 seconds</strong>. A cache hit, in contrast, takes about <strong>50 milliseconds</strong>.</p><p><strong>The cost side.</strong> Say you pay $3 per million input tokens and $15 per million output tokens. One uncached query costs:</p><ul><li>Input: 400 × $3/1M = <strong>$0.0012</strong></li><li>Output: 300 × $15/1M = <strong>$0.0045</strong></li><li><strong>Total: $0.0057 per uncached query</strong></li></ul><p>Now assume your hybrid cache achieves a <strong>60% overall hit rate</strong>. Of the 10,000 daily queries, 6,000 are answered from the cache instead of the LLM:</p><ul><li>Tokens saved per day: 6,000 × 700 tokens = <strong>4.2 million</strong></li><li>Money saved per day: 6,000 × $0.0057 = <strong>$34.20</strong></li><li>Money saved per month: roughly <strong>$1,026</strong></li><li>Money saved per year: roughly <strong>$12,300</strong></li></ul><p><strong>The latency side.</strong> Without caching, every query pays the full 2.5 seconds. With caching:</p><ul><li>Average response time = 0.6 × 50ms + 0.4 × 2,500ms ≈ <strong>1,030ms</strong></li><li>That’s a <strong>~59% reduction in average response time</strong> — and the improvement at p95 is even more dramatic, because cache hits are nearly instant bursts of consistent speed.</li></ul><p>So a single well-tuned semantic cache can save over $1,000 per month and roughly halve average response times on a modestly-sized workload — and those numbers scale linearly as traffic grows. More importantly, these are <em>your</em> numbers to compute from the metrics in the previous section: once your hit rate, token counts, and latency are being measured, converting them into dollars and seconds is a short calculation that makes the engineering case to stakeholders in two sentences.</p><h3>Protecting the Cache: Poisoning and Wrong Answers</h3><p>A cache doesn’t just store good answers — it stores whatever was written into it. If a wrong or low-quality answer ever enters the cache, it will be served repeatedly to every user who asks a similar question. This is called <strong>cache poisoning</strong>, and because a semantic cache is built to <em>amplify</em> reuse, the damage it can do is larger than in a traditional cache.</p><p><strong>How a wrong answer gets in:</strong></p><ul><li>The LLM produced a hallucinated or incorrect answer, and your system cached it without validation.</li><li>An approximate match slipped past the threshold, so the answer to a <em>different</em> question was served, then cached under the new phrasing.</li><li>The knowledge base changed, but an invalidation or TTL missed an entry, leaving an outdated answer alive.</li></ul><p><strong>How to defend against it:</strong></p><ol><li><strong>Validate before you cache.</strong> Cache aggressively only when you trust the source — for example, when the answer was generated from a verified knowledge base with high retrieval confidence. For low-confidence answers, serve them to the user but don’t store them.</li><li><strong>Make poisoning reversible.</strong> Build a <strong>delete-by-key</strong> admin endpoint that purges a specific entry from both the cache and the vector DB. When a user reports a wrong answer, you should be able to kill it in seconds, not days.</li><li><strong>Monitor the wrong-match rate.</strong> This metric is your early-warning system. If it climbs, investigate immediately — an elevated wrong-match rate is often the first sign of threshold drift or a regression in your embedding model.</li><li><strong>Add a kill switch.</strong> Every cache needs a global flush: one command that cleans both stores. Yes, it resets your hit rate to zero for a while — but a cold cache is always better than a poisonous one.</li><li><strong>Consider a verified-answer flag.</strong> Trust nothing by default. Answers that were manually verified or generated with high confidence can carry a verified: true flag. If you ever need to purge unverified entries en masse, the flag turns it into a single query.</li></ol><p>The mental model: a semantic cache is a liability as much as an asset. The same property that makes it cheap — automatic reuse — is the property that makes poisoning expensive. Design for the ability to undo mistakes from day one, not after an incident teaches you why you needed it.</p><h3>When to Skip the Cache: A Policy Checklist</h3><p>Before a query is even allowed to touch the cache, run it through a fast pre-filter. The goal is to keep sensitive, personalized, or action-driven queries away from the cache — <em>before</em> they can be matched, stored, or leaked. Think of this as the gatekeeper that sits in front of the retrieval flow.</p><p>A query should <strong>bypass the cache entirely</strong> if any of the following is true:</p><ul><li><strong>It contains personally identifiable information (PII) or secrets</strong> — names, emails, addresses, credit-card numbers, tokens in the prompt. These must never be persisted in a cache that other users’ queries could match against.</li><li><strong>The answer depends on the specific user</strong> — their account state, order history, balances, or preferences. Two users can ask the same question and legitimately need different answers.</li><li><strong>The intent is an action, not information</strong> — booking, purchasing, sending, deleting, or any tool execution with side effects. This is the agentic-AI case from earlier, encoded as a rule.</li><li><strong>It requires real-time or volatile data</strong> — current prices, inventory, live scores, breaking news.</li><li><strong>The domain is compliance-sensitive</strong> — medical, legal, or financial advice where a cached response could have real consequences for users.</li><li><strong>The classifier’s confidence is low.</strong> If your intent/quality classifier isn’t sure whether a query is safe to cache, default to the conservative choice: answer it live and don’t store it.</li></ul><p>This checklist is cheap to implement — a few checks on metadata before the cache lookup — and it turns the “where not to use” philosophy into an enforceable, production-grade rule. Log <em>why</em> each query was skipped; it doubles as an audit trail and a way to detect if your skip rules are over-triggering and silently shrinking your hit rate.</p><h3>A Production-Ready Checklist: Before You Ship</h3><p>There’s a gap between a concept that works in a notebook and one that runs reliably in production. Here’s the checklist to walk through before turning a semantic cache on for real users:</p><p><strong>Before launch</strong></p><ul><li>Choose your embedding model using a labeled dataset and the metrics from the approximate-search section.</li><li>Calibrate your similarity threshold on held-out data rather than by intuition.</li><li>Define which questions are cacheable per the skip-caching policy, and wire the pre-filter.</li><li>Set initial TTL values per content category — long for stable docs, short for volatile data.</li></ul><p><strong>Operational readiness</strong></p><ul><li>Implement the retrieval flow (exact → approximate → LLM) and its filtering variant.</li><li>Build the storage logic for all four outcomes (exact, approximate, expired, no-hit).</li><li>Write the unified flush script and connect it to your knowledge-base re-indexing pipeline.</li><li>Build a delete-by-key admin endpoint and a global-flush kill switch.</li><li>Namespace keys and vector partitions for multi-tenancy, if applicable.</li></ul><p><strong>After launch</strong></p><ul><li>Instrument every query: log hit type, latency, threshold score, and wrong-match flags.</li><li>Put the measurement metrics on a dashboard, with alerts on wrong-match rate and staleness.</li><li>Monitor vector DB row count and latency so you know when to flush.</li><li>Schedule a periodic review of threshold, TTL, and embedding model as traffic and content evolve.</li><li>Document the rollback procedure — a one-line “flush everything” should be runnable by anyone on call.</li></ul><p>None of these items is glamorous, but skipping any of them is how a cache goes from “great idea” to “outage during a traffic spike” in one bad afternoon.</p><h3>Additional Considerations</h3><p>A few cross-cutting concerns don’t fit neatly into any single section, but they’ll surface the moment your cache scales:</p><ul><li><strong>The cache isn’t free.</strong> Redis clusters and vector databases consume memory, storage, and compute even when idle. On large workloads, the cache’s own infrastructure cost is real — monitor it, and don’t assume the savings are 100% margin.</li><li><strong>Embedding drift and versioning.</strong> When you upgrade your embedding model, the vectors in your vector DB become incompatible with new queries. Plan a one-time re-embedding (or full flush) as part of any model upgrade, and tag cache entries with the embedding/LLM version that produced them so you can always tell what a stored answer represents.</li><li><strong>Cross-team impact.</strong> In many organizations, the knowledge base, the RAG pipeline, and the cache are owned by different people. Set clear ownership of the flush script, and document the re-indexing contract so that “we updated our docs” always triggers the right invalidation.</li><li><strong>Compliance and audits.</strong> If you operate under data-protection regulations, know exactly what your cache retains and for how long. Logged key hashes, documented TTL policies, and the skip-cache rules give you the artifacts an auditor will ask for.</li></ul><p>These concerns are rarely urgent on day one, but they become urgent quickly. Building them into the design now is far cheaper than retrofitting them after your cache is serving millions of requests a day.</p><h3>Conclusion</h3><p>Semantic caching is one of the highest-leverage optimizations you can add to a production LLM application. It cuts costs, improves latency, and reduces load — all without degrading answer quality, as long as you’re caching the right kind of questions.</p><p>The recipe is simple: use a hybrid of exact and approximate search, let the vector database handle semantic matching and metadata filtering, let your cache handle TTL and fast delivery, and store new questions on every miss so the system keeps getting faster. Tune your approximate strategy with a labeled dataset and honest metrics, design your TTL around how often your source data actually changes, measure the results so you can keep improving, and harden the cache against wrong answers before they ever become a habit.</p><p>And avoid caching where personalization or real-time data matters — agentic AI being the clearest example. If you’re building a customer-facing system where users repeat themselves, semantic caching isn’t just a nice-to-have. It’s a competitive advantage in both cost and speed.</p><p>I hope you have liked the article. Please clap and share if you have liked it. If you need a library for this, please comment on this and if I have enough comments, I will create a python library for the same. I will create it for a few cache/vector database like redis, milvus etc, and anyone interested can contribute.</p><p>In case of any questions, please reach out at jaswanth04@gmail.com.</p><p><strong>Before you go</strong></p><ul><li>Please take a moment to like the post and follow the writer!</li><li>Did you know that over 400,000 developers share what they’re building, learning, and discovering across our platforms every month? Learn how you can contribute <a href="https://plainenglish.io/write-for-us">here</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98863b91159e" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/stop-calling-the-llm-twice-for-the-same-question-a-practical-guide-to-semantic-caching-98863b91159e">Stop Calling the LLM Twice for the Same Question: A Practical Guide to Semantic Caching</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[History based Contextualization in LLM deployed as a Backend Service — FastAPI and…]]></title>
            <link>https://jaswanth04.medium.com/history-based-contextualization-in-llm-deployed-as-a-backend-service-fastapi-and-5a1759fdd32e?source=rss-9377ebaddb70------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a1759fdd32e</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[mistral-ai]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jaswant Jonnada]]></dc:creator>
            <pubDate>Sun, 04 Feb 2024 03:31:40 GMT</pubDate>
            <atom:updated>2024-02-04T03:31:40.886Z</atom:updated>
            <content:encoded><![CDATA[<h3>History based Contextualization in LLM deployed as a Backend Service — FastAPI and MongoDB</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oqCBlkCb7iYWsKSOxP_LQQ.jpeg" /><figcaption>Pictorial representation of LLM using History</figcaption></figure><p>When the word Contextualization appears in the context of a Large Language Model (LLM), the first thing that would come to our mind is about Retrieval Augmented Generation (RAG), where we extract the context and from a chunk of data, which was vectorized (or embedded) and stored in a vector db, which is then retrieved in real time, embedded into the prompt and is answered by a Large Language Model (LLM).</p><p>But there is an other method of contextualization called as History based contextualization, which is very well evident when you use tools like ChatGpt and Bard.</p><p>In this article I would like to touch upon the following:</p><ol><li>What is History based Contextualization ?</li><li>Where is it used ?</li><li>How can we achieve this History based Contextualization with Mistral-7B</li><li>How can we achieve the same with a Mistral-7B that is deployed as a Backend service using FastAPI. Here we will save the historical context in Mongodb and retrieve it whenever possible.</li></ol><p>We dont want to use any fancy packages like Langchain( where message list can be used), LLamaIndex, but we want to see how can this be possible with only basic packages in a production scenario like — FastAPI, pymongo etc.</p><h3>But, What is History based Contextualization?</h3><p>If you go to chat gpt and ask your first question, as expected it gives you the answer to the first question. Later you ask one more question which is related to the previous question that you ask. Surprisingly, it gives answer to that question, and the context is passed from question 1 to question 2. So, the process of passing the context from the questions asked previously to the current question is History based Contextualization.</p><p>Let us understand this with an example from ChatGPT. I will be asking the following questions to ChatGPT, in the same order</p><ol><li>Hi, I am Jaswant</li><li>I like Reading books</li><li>My favorite book is The White Tiger</li><li>What is my name ?</li><li>What is my favorite book ?</li><li>What do I like ?</li></ol><p>In the above questions, if you see the first three questions is more about my introduction and last three questions, was to see how does it remember me. Let us ask this to ChatGPT and see how does it respond.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*e96OPpRgYBhElnFM3Fkg-w.png" /><figcaption>ChatGPT’s answer to the above questions.</figcaption></figure><p>If you see above Image, ChatGPT was able to answer the questions correctly, as it is able to keep the history context.</p><p>If ChatGPT can do it, let us see how can we achieve it using Mistral-7B.</p><h3>Where is history based contextualization useful?</h3><p>It is useful when we are creating a chat application, to give the user an impression that the virtual agent is remembering and understanding your conversations.</p><p>It might not be useful in case of search scenarios, or a RAG based FAQ bot, where there is not context for search.</p><h3>History based contextualization with Mistral</h3><p>For this let us open a jupyter notebook, and load all the required packages, along with the Quantized Mistral Model. Also, we will be using the <a href="https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2">Instruct Mistral model</a> which is used for the Chat Purpose.</p><p>I am using a 12GB GPU for this, so I have gone ahead with 4-bit quantization. If you have a bigger GPU, please choose the quantization, that your GPU can support. Also, the concepts can very well work for other models as well.</p><pre># Importing the required packages<br>from transformers import AutoModelForCausalLM, AutoTokenizer, <br>                          BitsAndBytesConfig<br>import torch<br><br># Model name<br>model_id = &quot;mistralai/Mistral-7B-Instruct-v0.2&quot;<br><br># Quantization Configuration<br>bnb_config = BitsAndBytesConfig(load_in_4bit=True, <br>                                bnb_4bit_quant_type=&#39;nf4&#39;,<br>                                bnb_4bit_use_double_quant=True,<br>                                bnb_4bit_compute_dtype=torch.bfloat16)<br><br># Loading the tokenizer of mistral model<br>tokenizer = AutoTokenizer.from_pretrained(model_id)<br><br># Specifying the device name<br>device = &quot;cuda:0&quot;<br><br># Loading the model<br>model = AutoModelForCausalLM.from_pretrained(<br>        model_id,<br>        trust_remote_code=True,<br>        quantization_config=bnb_config,<br>        torch_dtype=torch.float16,<br>        device_map=device,<br>    )</pre><p>For Mistral to work, we need to provide a message in a given template. Then, you can tokenize with the chat template to create the input vector. The input vector is sent to the model for generation, as shown below</p><pre># Message given as a template which will be understood by Mistral<br>message = [{<br>    &quot;role&quot;: &quot;user&quot;,<br>    &quot;content&quot;: &quot;Hi, I am Jaswant&quot;<br>}]<br><br>max_new_tokens = 512<br># Creating the input using tokenizer chat template<br>input = tokenizer.apply_chat_template(message, <br>                            add_generation_prompt=True, <br>                            return_tensors=&quot;pt&quot;).to(device)<br><br># Generating the output<br>outputs = model.generate(input, <br>                        max_new_tokens=max_new_tokens, <br>                        pad_token_id=tokenizer.eos_token_id)<br><br>decoded_output = tokenizer.decode(outputs[0], skip_special_tokens=True)<br><br>print(decoded_output)</pre><p>Running the above function will provide the below output</p><pre>[INST] Hi, I am Jaswant [/INST] Hello Jaswant, nice to meet you. <br>How can I help you today? Is there a specific question or topic you&#39;d like <br>to discuss? I&#39;m here to provide information and answer any questions you <br>might have to the best of my ability.</pre><p>If you see the response, you can see the question is also coming in between [INST] [/INST] tags. This format is specific to <a href="https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2">Mistral Instruct model</a>.</p><p>Let us write a function which takes messages as an input, cleans the output by removing the data between the [INST] [/INST] tags, and outputs only the answer. The removal of data can be achieved using some basic string search operations.</p><pre># Function to get the answer of a question. <br># Model, tokenizer and device are global variables<br><br>def get_answer(messages):<br><br>    # Applu chat template to create input<br>    inputs = tokenizer.apply_chat_template(messages, <br>                                add_generation_prompt=True, <br>                                return_tensors=&quot;pt&quot;).to(device)<br>    max_new_tokens = 512<br><br>    # Generate the outputs<br>    outputs = model.generate(inputs, <br>                            max_new_tokens=max_new_tokens, <br>                            pad_token_id=tokenizer.eos_token_id)<br><br>    # Outputs post decoding<br>    decoded_output = tokenizer.decode(outputs[0], skip_special_tokens=True)<br><br>    # Removal of the INST tags<br>    while &#39;[INST]&#39; in decoded_output:<br>        start_index = decoded_output.find(&#39;[INST]&#39;)<br>        end_index = decoded_output.rfind(&#39;[/INST]&#39;) + len(&#39;[/INST]&#39;)<br>        output = decoded_output[:start_index] + decoded_output[end_index:]<br><br>    return output</pre><p>Now that we have our function ready, what we can do is keep updating the messages list using the template of the Mistral Instruction model.</p><p>The template is given below, which alternates between the role being user and assistant, and the content being User’s question and Mistral’s answer respectively. The sample multi conversation content is given below</p><pre>messages = [{<br>    &quot;role&quot;: &quot;user&quot;,<br>    &quot;content&quot;: &quot;Hi, I am Jaswant&quot;<br>},<br>{<br>    &quot;role&quot;: &quot;assistant&quot;,<br>    &quot;content&quot;: &quot;Hello Jaswant, nice to meet you. <br>      How can I help you today? Is there a specific question or topic you&#39;d like <br>      to discuss? I&#39;m here to provide information and answer any questions you <br>      might have to the best of my ability&quot;<br>},<br>{<br>    &quot;role&quot;: &quot;user&quot;,<br>    &quot;content&quot;: &quot;I like reading books&quot;<br>}<br>]</pre><p>If the above messages, is given as input the Mistral Instruct Model, it gives the output accordingly which is contextualized as per history.</p><p>Below is the given input. Here I am also extending the prompt, so that Mistral behaves like a remembering assistant.</p><pre>text = &quot;&quot;&quot;You are an assistant that helps people in reminding what they are here for. <br>            Please follow the below rules(1, 2, 3 and 4) for answering the questions:<br>            1. The people will given you information and if asked you will provide the information back to them.<br>            2. Please dont remind the user that you are here to remember information in the conversations.<br>            3. Only provide answer to the required question.<br>            4. Answer the question in less than 10 words.<br>            The input from the user is following:<br>            Hello, I am Jaswant&quot;&quot;&quot;<br><br>messages.append({<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: text<br>})<br><br>output = get_answer(messages)<br>print(output)<br>messages.append({&quot;role&quot;: &quot;assistant&quot;, <br>                 &quot;content&quot;: output})</pre><pre># Output<br>Hello Jaswant. Nice to meet you. Is there specific information you&#39;d like me to help you remember?</pre><pre>text = &quot;I like reading books&quot;<br>messages.append({&quot;role&quot;: &quot;user&quot;,<br>                &quot;content&quot;: text})<br><br>output = get_answer(messages)<br>print(output)<br>messages.append({&quot;role&quot;: &quot;assistant&quot;, <br>                 &quot;content&quot;: output})</pre><pre># Output <br>Understood. You enjoy reading books.</pre><pre>text = &#39;My favorite book is Dogs of War&#39;<br>messages.append({&quot;role&quot;: &quot;user&quot;,<br>                &quot;content&quot;: text})<br><br>output = get_answer(messages)<br>print(output)<br>messages.append({&quot;role&quot;: &quot;assistant&quot;, <br>                 &quot;content&quot;: output})</pre><pre># Output<br>Got it. &quot;Dogs of War&quot; is your favorite book.</pre><pre>text = &#39;What is my name?&#39;<br>messages.append({&quot;role&quot;: &quot;user&quot;,<br>                &quot;content&quot;: text})<br><br>output = get_answer(messages)<br>print(output)<br>messages.append({&quot;role&quot;: &quot;assistant&quot;, <br>                 &quot;content&quot;: output})</pre><pre># Output <br>Jaswant. Your name is Jaswant.</pre><pre>text = &#39;What is my favorite book?&#39;<br>messages.append({&quot;role&quot;: &quot;user&quot;,<br>                &quot;content&quot;: text})<br><br>output = get_answer(messages)<br>print(output)<br>messages.append({&quot;role&quot;: &quot;assistant&quot;, <br>                 &quot;content&quot;: output})</pre><pre># Output<br> &quot;Dogs of War&quot; is your favorite book.</pre><pre>text = &#39;What do I like?&#39;<br>messages.append({&quot;role&quot;: &quot;user&quot;,<br>                &quot;content&quot;: text})<br><br>output = get_answer(messages)<br>print(output)<br>messages.append({&quot;role&quot;: &quot;assistant&quot;, <br>                 &quot;content&quot;: output})</pre><pre># Output<br>You enjoy reading books. Specifically, &quot;Dogs of War&quot; is your favorite book.</pre><p>The above input and output shows that, the Mistral Instruct is able to maintain the history and contextualize its response based on the history.</p><p>What, if we have to deploy the Mistral model in the back-end, and there is a front end html webpage which keeps sending the questions. How do we maintain the history and context then ?</p><h3>Contextualization when LLM is deployed in the back-end</h3><p>I hope everyone who has come till here, has gone through my <a href="https://medium.com/stackademic/streaming-llm-responses-using-fastapi-deb575554397"><em>previous article,</em></a> where we see the deployment of LLM using FastAPI and how to stream the responses from LLM to the front end.</p><p>We will be using the code in the <a href="https://medium.com/stackademic/streaming-llm-responses-using-fastapi-deb575554397"><em>previous article</em></a> which we already deployed the LLM using FastAPI. Please go through it, in order gain an understanding of the deployment.</p><p>When we deploy the model as a back-end service, we are assuming that the services are state-less.</p><p><strong>Stateless Services —</strong> These are the services, where the a request given from the front end will have a response from the back-end. It does not store any state. In our context, this means the front end would send a question to the back-end and the back-end would respond with the answer to the question. Here it is not able to send any history, as they are the previous conversations.</p><h4>So, how to maintain context in stateless services ?</h4><p>The solution is to use a database, where each question and answer of a session is saved.</p><p>In order to recognize a session, the front-end would need to maintain a <strong><em>session_id</em></strong>, and sends <strong><em>session_id</em></strong>, based on which we would maintain and retrieve the history data from the database, and provide it to the LLM.</p><p>Hence, the database should contain the following information:</p><ol><li><strong><em>Session_id </em></strong>— The maintain the session information, so that we can connect the questions and answers</li><li><strong><em>Timestamp</em></strong> — Used to sort the questions and answers in order</li><li><strong><em>Question </em></strong>— User’s question</li><li><strong><em>Answer</em></strong> — Mistral’s answer</li></ol><p>In this case, we are using MongoDb which is NoSQL, and is very fast in real time. You can get a mongo db up and running by some of the following methods:</p><ol><li><a href="https://www.mongodb.com/docs/manual/installation/">Mongo db Installation</a></li><li><a href="https://hub.docker.com/_/mongo">Mongo db Docker Image</a>, <a href="https://www.geeksforgeeks.org/how-to-run-mongodb-as-a-docker-container/">Mongo DB docker setup</a></li></ol><p>For python to connect with Mongo, we need to build a Mongo Connector class, which does the following</p><ol><li>Initializes the client connection to the database</li><li>Saves the record when information is provided</li><li>Retrieves information when a session id is provided.</li></ol><p>The following is the class that does this:</p><pre># %db_utils.py<br><br>import pymongo<br>import datetime<br>import uuid<br><br># Mongo Connector class<br><br>class MongoConnector:<br>    def __init__(self) -&gt; None:<br>        # Initializing the client, using the local url<br>        # Please modify this, based on your mongo provider<br>        client = pymongo.MongoClient(&quot;mongodb://localhost:27017/&quot;)<br>        # We created a database by name LLM<br>        db = client[&quot;llm&quot;]<br>        # We created a collection by name history<br>        self.collection = db[&quot;history&quot;]<br><br>    # Function to inster the record<br>    def insert_record(self, session_id: str, <br>                question: str, answer: str) -&gt; None:<br><br>        # Creating of the record<br>        record = {&quot;session_id&quot;: session_id,<br>                  &quot;timestamp&quot;: datetime.datetime.utcnow(),<br>                  &quot;question&quot;: question,<br>                  &quot;answer&quot;: answer}<br>        <br>        # Inserting the record<br>        res = self.collection.insert_one(record)<br><br>        print(res)<br><br>    def retrieve_history(self, session_id):<br>        # Query MongoDB to retrieve questions and answers <br>        # for a given session_id, sorted by timestamp<br>        cursor = self.collection.find({&#39;session_id&#39;: session_id}).sort(&#39;timestamp&#39;, 1)  # 1 for ascending order, -1 for descending<br><br>        questions_and_answers = []  # List to store questions and answers<br>        <br>        # Creating a tuple of questions and answers and returning the same<br>        for doc in cursor:<br>            question = doc[&#39;question&#39;]<br>            answer = doc[&#39;answer&#39;]<br>            questions_and_answers.append((question, answer))<br><br>        return questions_and_answers</pre><p>The above class is stored in a file by name db_utils.py</p><p>Since, we are using the code given in the <a href="https://medium.com/stackademic/streaming-llm-responses-using-fastapi-deb575554397">earlier article for streaming</a>, we made a minor change in the code, In the earlier code, the generation function is given below.</p><p>We create a file by name fast_llm_history.py, where most the code is from the previous article.</p><p>We make a small change by instantiating the object of the mongo connector</p><pre># Loading the mistral model and tokenizer<br>model, tokenizer = load_model()<br><br># Initializing the queue<br>streamer_queue = Queue()<br><br># Initializing the custom streamer for Streaming responses<br>streamer = CustomStreamer(streamer_queue, tokenizer, True)<br><br># Initializing the mongo connector object<br>mongo_connector = MongoConnector()</pre><pre>def start_generation(query):<br><br>    prompt = &quot;&quot;&quot;<br><br>            # You are assistant that behaves very professionally. <br>            # You will only provide the answer if you know the answer. If you do not know the answer, you will say I dont know. <br><br>            # ###Human: {instruction},<br>            # ###Assistant: &quot;&quot;&quot;.format(instruction=query)<br>    inputs = tokenizer([prompt], return_tensors=&quot;pt&quot;).to(&quot;cuda:0&quot;)<br>    generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=64, temperature=0.1)<br>    thread = Thread(target=model.generate, kwargs=generation_kwargs)<br>    thread.start()</pre><p>In the above function, the target to the thread is the model.generate function, here model is given as a global variable,</p><p>Since we need to take the response of the model.generate function and store it into the mongodb, we have to split the start_generation function into two functions where the second function will call the model.generate, and store the session data. The data retrieval is done in the start_generation function. We also create a static function to remove the INST tags.</p><pre># Static function to remove the INST tags<br>def remove_inst_tags(input_string):<br>    while &#39;[INST]&#39; in input_string:<br>        start_index = input_string.find(&#39;[INST]&#39;)<br>        end_index = input_string.rfind(&#39;[/INST]&#39;) + len(&#39;[/INST]&#39;)<br>        input_string = input_string[:start_index] + input_string[end_index:]<br>    return input_string<br><br># Function that takes the session id and messages as input<br>def generate(session_id, messages):<br>    # Converting the messages to tokens<br>    inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors=&quot;pt&quot;).to(&quot;cuda:0&quot;)<br>    <br>    # Generation of the output<br>    outputs = model.generate(inputs=inputs, streamer=streamer, <br>                         pad_token_id=tokenizer.eos_token_id, <br>                         max_new_tokens=512, <br>                         temperature=0.1, do_sample=True<br>                         )<br><br>    # Decoding the output<br>    decoded_output = tokenizer.decode(outputs[0], skip_special_tokens=True)<br>    <br>    # Removing the inst tags<br>    answer = remove_inst_tags(decoded_output)<br>    print(&#39;\n&#39;, &#39;-&#39;*15, &#39;Displaying Output&#39;, &#39;-&#39;*15, &#39;\n&#39;)<br>    print(answer)<br>    print(&#39;\n&#39;, &#39;-&#39;*15, &#39;End of Display&#39;, &#39;-&#39;*15, &#39;\n&#39;)<br><br>    # The question is last but one message<br>    question = messages[-1][&quot;content&quot;]<br>    # Inserting record into the mongo db<br>    mongo_connector.insert_record(session_id=session_id, <br>                                  question=question, <br>                                  answer=answer)<br><br>    <br># Start generation method, which retrieves the history<br>def start_generation(session_id, query):<br><br>    # Retrieve the history<br>    history = mongo_connector.retrieve_history(session_id)<br>    messages = None<br><br>    # If no history is found, insert the prompt to the first question<br>    if not history:<br>        text = &quot;&quot;&quot;You are an assistant that helps people in reminding what they are here for. <br>                Please follow the below rules(1, 2, 3 and 4) for answering the questions:<br>                1. The people will given you information and if asked you will provide the information back to them.<br>                2. Please dont remind the user that you are here to remember information in the conversations.<br>                3. Only provide answer to the required question.<br>                4. Answer the question in less than 10 words.<br>                The input from the user is following:<br>                {question}&quot;&quot;&quot;.format(question=query)<br><br>        messages = [{&quot;role&quot;: &quot;user&quot;, <br>                    &quot;content&quot;: text}]<br>    # If history is found<br>    else:<br>        messages = []<br>        # Insert he question and answer into the required format into the messages<br>        for previous_question, previous_answer in history:<br>            messages.append({<br>                &quot;role&quot;: &quot;user&quot;,<br>                &quot;content&quot;: previous_question<br>            }) <br>            messages.append({<br>                &quot;role&quot;: &quot;assistant&quot;,<br>                &quot;content&quot;: previous_answer<br>            })<br>        messages.append({<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: query<br>        })<br>    <br>    # Starting the thread with generate as target, <br>    # and session id, messages as kwargs<br>    if messages:<br>        thread = Thread(target=generate, kwargs=dict(session_id=session_id, <br>                                                    messages=messages))<br>        thread.start()</pre><p>The remaining code would contain the response generator function and stream function. The response generator function would remain the same. There is a minor change in the stream function which takes a post request as an input instead of the get request as per the <a href="https://medium.com/stackademic/streaming-llm-responses-using-fastapi-deb575554397">previous article</a>. Also since the post request would contain a session_id and question, we use pydantic BaseModel to create a structure for the request.</p><p>The following are the changes</p><pre># The response generator function which remains unchanged<br>async def response_generator(session_id: str, query: str) -&gt; str:<br><br>    start_generation(session_id, query)<br><br>    while True:<br>        value = streamer_queue.get()<br>        if value == None:<br>            break<br>        yield value<br>        streamer_queue.task_done()<br>        await asyncio.sleep(0.1)<br><br># Session Request Model Class<br>class SessionRequest(BaseModel):<br>    session_id: str<br>    query: str<br><br># Using post request<br>@app.post(&#39;/query-stream/&#39;)<br># This takes SessionRequest as Input<br>async def stream(session_request: SessionRequest):<br>    print(f&#39;Query receieved: {session_request.query}&#39;)<br>    # Raise a HTTP exception if query is not found<br>    if session_request.query is None:<br>        raise HTTPException(400, &quot;Query is missing&quot;)<br>    # Calling the response generator<br>    return StreamingResponse(response_generator(session_request.session_id , <br>                                                session_request.query), <br>                             media_type=&#39;text/event-stream&#39;)</pre><p>The final file would look like below:</p><pre># %fast_llm_history.py<br><br>from fastapi import FastAPI, HTTPException<br>import asyncio<br>from fastapi.responses import StreamingResponse<br>from load_mistral import load_model<br><br>from streamer import CustomStreamer<br>from threading import Thread<br>from db_utils import MongoConnector, remove_inst_tags<br>from queue import Queue<br>from pydantic import BaseModel<br><br>class SessionRequest(BaseModel):<br>    session_id: str<br>    query: str<br><br>app = FastAPI()<br><br>model, tokenizer = load_model()<br>streamer_queue = Queue()<br>streamer = CustomStreamer(streamer_queue, tokenizer, True)<br>mongo_connector = MongoConnector()<br><br>def generate(session_id, messages):<br>    inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors=&quot;pt&quot;).to(&quot;cuda:0&quot;)<br>    <br>    outputs = model.generate(inputs=inputs, streamer=streamer, <br>                         pad_token_id=tokenizer.eos_token_id, <br>                         max_new_tokens=512, <br>                        #  temperature=0.1, do_sample=True<br>                         )<br><br>    decoded_output = tokenizer.decode(outputs[0], skip_special_tokens=True)<br>    answer = remove_inst_tags(decoded_output)<br>    print(&#39;\n&#39;, &#39;-&#39;*15, &#39;Displaying Output&#39;, &#39;-&#39;*15, &#39;\n&#39;)<br>    print(answer)<br>    print(&#39;\n&#39;, &#39;-&#39;*15, &#39;End of Display&#39;, &#39;-&#39;*15, &#39;\n&#39;)<br><br>    question = messages[-1][&quot;content&quot;]<br>    mongo_connector.insert_record(session_id=session_id, question=question, answer=answer)<br><br>    <br><br>def start_generation(session_id, query):<br><br>    history = mongo_connector.retrieve_history(session_id)<br>    messages = None<br><br>    if not history:<br>        text = &quot;&quot;&quot;You are an assistant that helps people in reminding what they are here for. <br>                Please follow the below rules(1, 2, 3 and 4) for answering the questions:<br>                1. The people will given you information and if asked you will provide the information back to them.<br>                2. Please dont remind the user that you are here to remember information in the conversations.<br>                3. Only provide answer to the required question.<br>                4. Answer the question in less than 10 words.<br>                The input from the user is following:<br>                {question}&quot;&quot;&quot;.format(question=query)<br><br>        messages = [{&quot;role&quot;: &quot;user&quot;, <br>                    &quot;content&quot;: text}]<br>    else:<br>        messages = []<br>        for previous_question, previous_answer in history:<br>            messages.append({<br>                &quot;role&quot;: &quot;user&quot;,<br>                &quot;content&quot;: previous_question<br>            }) <br>            messages.append({<br>                &quot;role&quot;: &quot;assistant&quot;,<br>                &quot;content&quot;: previous_answer<br>            })<br>        messages.append({<br>            &quot;role&quot;: &quot;user&quot;,<br>            &quot;content&quot;: query<br>        })<br>    if messages:<br>        thread = Thread(target=generate, kwargs=dict(session_id=session_id, <br>                                                    messages=messages))<br>        thread.start()<br><br><br>async def response_generator(session_id: str, query: str) -&gt; str:<br><br>    start_generation(session_id, query)<br><br>    while True:<br>        value = streamer_queue.get()<br>        if value == None:<br>            break<br>        yield value<br>        streamer_queue.task_done()<br>        await asyncio.sleep(0.1)<br><br>@app.post(&#39;/query-stream/&#39;)<br>async def stream(session_request: SessionRequest):<br>    print(f&#39;Query receieved: {session_request.query}&#39;)<br>    if session_request.query is None:<br>        raise HTTPException(400, &quot;Query is missing&quot;)<br>    return StreamingResponse(response_generator(session_request.session_id , <br>                                                session_request.query), media_type=&#39;text/event-stream&#39;)</pre><p>We can start the server by running the following command</p><pre>uvicorn fast_llm_history:app</pre><p>It takes a while to load, as it has to load the mistral model and the tokenizer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*oF-yjj1tBdFdGtCKbpi4Eg.png" /><figcaption>After loading the application</figcaption></figure><h3>Testing the application</h3><p>Now that we have started the application, let us now test the application. To test the application, we create a python / jupyter notebook, and use the following import statements</p><pre>import requests # Requests library is used to test the API<br>import uuid # uuid is used to generate random session id<br>import time # time to synthetically provide some time between requests</pre><p>We then create a function that takes the session id, question as an input and prints the answer</p><pre>def get_answer(session_id, query):<br>    # url to query<br>    url = &#39;http://127.0.0.1:8000/query-stream/&#39;<br>    # Creating a payload for post reqest<br>    payload = {&quot;session_id&quot;: session_id,<br>            &quot;query&quot;: query}<br>    print(&#39;\n&#39;, &#39;-&#39;*30)<br>    print(f&#39;Question: {query}&#39;)<br>    <br>    print(&quot;Answer: &quot;, end=&quot;&quot;)<br>    # Sending the post request and streaming the responses<br>    with requests.post(url, json=payload, stream=True) as r:<br>        for chunk in r.iter_content(1024): <br>            print(chunk.decode(&#39;utf-8&#39;), end=&quot;&quot;)</pre><p>We use the following block to test the application with our previously mentioned test questions</p><pre># Creating a random session id<br>session_id = str(uuid.uuid4())<br>print(f&#39;Session id: {session_id}&#39;)<br><br># Making a list of questions<br>questions = [&quot;Hello I am Jaswant&quot;,<br>             &quot;I like reading books&quot;,<br>             &quot;My favorite book is The White Tiger&quot;,<br>             &quot;What is my name?&quot;,<br>             &quot;What is my favorite book?&quot;,<br>             &quot;What do I like ?&quot;]<br><br># getting answer for each question<br># also providing some synthetic sleep time<br>for question in questions:<br>    get_answer(session_id, question)<br>    time.sleep(2)<br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fwhwj-J30emhgLn5qQPoFw.png" /><figcaption>Response to the above code</figcaption></figure><p>Finally, we could see that the responses are as expected. The Mistral Instruct model is able to answer the questions based on the history.</p><p>When using the front end, the front end should be maintaining the <em>session_id. </em>If there is a new chat, the <em>session_id</em> should be generated again.</p><h3>Conclusion</h3><p>In this article we have seen, how to contextualize a given question to a locally deployed Mistral Instruct model with the history.</p><p>We have also seen, how it is done in a production scenario using databases, where the LLM is deployed using FastAPI.</p><p>We can use the above learnt principles and modify it for other Chat models or other databases also.</p><p>A similar kind of approach can be used for closed source models using Langchain, but it would require some amount of re work to the code. If you want me to work on it and provide code for the same, please drop a response or an email.</p><p>As usual the code used for this can be found <a href="https://github.com/jaswanth04/llm_response_streaming">here</a>.</p><p>If you have any question or comment on the above article, please drop a response or send me an email at jaswanth04@gmail.com.</p><p>Please consider to follow me, for more such articles and content.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a1759fdd32e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streaming Responses from LLM using Langchain + FastAPI]]></title>
            <link>https://blog.stackademic.com/streaming-responses-from-llm-using-langchain-fastapi-329f588d3b40?source=rss-9377ebaddb70------2</link>
            <guid isPermaLink="false">https://medium.com/p/329f588d3b40</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Jaswant Jonnada]]></dc:creator>
            <pubDate>Mon, 15 Jan 2024 02:47:41 GMT</pubDate>
            <atom:updated>2024-09-26T14:37:43.278Z</atom:updated>
            <content:encoded><![CDATA[<h3>Streaming Responses from LLM Using LangChain + FastAPI</h3><p>Hope everyone has read my <a href="https://medium.com/@jaswanth04/streaming-llm-responses-using-fastapi-deb575554397">previous article</a> about deploying Local or Fine-tuned LLMs in FastAPI and achieve streaming response in the same. However, I have received few requests on how to extend the same concept to closed source models of OpeanAI, Google etc. Hence this article will be an extension of the previous article. Please read that, at least the first part to know more about the basics of streaming in FastAPI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dx0q81adz2WwRukv7HcMOA.png" /><figcaption>Symbolic depiction of Langchain cruising around a computer :)</figcaption></figure><p>In the <a href="https://medium.com/@jaswanth04/streaming-llm-responses-using-fastapi-deb575554397">previous article</a> we have learnt about the following:</p><ol><li>Introduction — What is the problem statement that we are solving by using Streaming ?, What are auto regressive models ?, What is streaming ?</li><li>Basics of FastAPI Streaming — Architecture and Implementation of a simple streaming application using fake data streamer</li><li>We also understood the Producer-Consumer model of sending the tokens into the queue, which is then consumed and streamed using FastAPI</li><li>We also extended the above discussed FastAPI Streaming concept to Locally deployed LLMs, just using Hugging Face generate, streamer functions</li><li>We have also listed the next steps, and how can the current concept be improved.</li></ol><p>In this article we are going to focus on the similar steps using Langchain.</p><p><a href="https://differ.blog/differ-ai">Introducing DifferAI</a></p><h3>Architecture to be used for Langchain</h3><p>As in the <a href="https://medium.com/@jaswanth04/streaming-llm-responses-using-fastapi-deb575554397">previous article</a>, we would still be using a queue, and a serving function. However we need to modify the generate function that would be populating the queue token by token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iZLUi_3Za4beWYuSMieGsA.png" /><figcaption>Architecture of Langchain based token generator</figcaption></figure><h3>Handlers in Langchain</h3><p>Langchain has various sets of handlers. The main handler is the <a href="https://api.python.langchain.com/en/stable/callbacks/langchain_core.callbacks.base.BaseCallbackHandler.html">BaseCallbackHandler</a>. These handlers are similar to an abstract classes which must be inherited by our Custom Handler and some functions needs to be modified as per the requirement.</p><p>The functions that are of interest to us in the present case are the following:</p><ol><li>on_llm_new_token — This function decides on what to do in the case of a new token arrival. As per the existing concept, we should keep the new token in the streamer queue</li><li>on_llm_end — This function decides on what to do in the case of the last token. As per the existing concept we add a stop signal in the queue to stop the streaming process.</li></ol><p>Let us see how the handler looks like. Each line is commented so that you could understand what is happening in the same</p><pre>%handler.py<br># save the below code in a file by name handler.py<br># Importing the necessary packages<br>from langchain.callbacks.base import BaseCallbackHandler<br>from langchain.schema.messages import BaseMessage<br>from langchain.schema import LLMResult<br>from typing import Dict, List, Any<br><br># Creating the custom callback handler class<br>class MyCustomHandler(BaseCallbackHandler):<br>    def __init__(self, queue) -&gt; None:<br>        super().__init__()<br>        # we will be providing the streamer queue as an input<br>        self._queue = queue<br>        # defining the stop signal that needs to be added to the queue in<br>        # case of the last token<br>        self._stop_signal = None<br>        print(&quot;Custom handler Initialized&quot;)<br>    <br>    # On the arrival of the new token, we are adding the new token in the <br>    # queue<br>    def on_llm_new_token(self, token: str, **kwargs) -&gt; None:<br>        self._queue.put(token)<br><br>    # on the start or initialization, we just print or log a starting message<br>    def on_llm_start(<br>        self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any<br>    ) -&gt; None:<br>        &quot;&quot;&quot;Run when LLM starts running.&quot;&quot;&quot;<br>        print(&quot;generation started&quot;)<br><br>    # On receiving the last token, we add the stop signal, which determines<br>    # the end of the generation<br>    def on_llm_end(self, response: LLMResult, **kwargs: Any) -&gt; None:<br>        &quot;&quot;&quot;Run when LLM ends running.&quot;&quot;&quot;<br>        print(&quot;\n\ngeneration concluded&quot;)<br>        self._queue.put(self._stop_signal)</pre><h3>Integrating the handler in main</h3><p>We have seen how to write the custom handler. Now let us see, what should be in the main file which contains the fastapi code</p><p>We need to first create an object of the custom handler and add it to the api. During the time of writing this article, I was using <strong>langchain-0.1.0</strong>.</p><p>During the time of writing this article, <a href="https://python.langchain.com/docs/integrations/platforms/openai">Langchain has a separate package for Open AI usage</a>. The library that I am using is <strong>langchain-openai==0.0.2.post1</strong>.</p><p>In the beginning, we initiate the handler and provide the handler to the LLM.</p><pre>%fast_langchain.py<br><br>#Importing all the required packages<br>from fastapi import FastAPI<br>import asyncio<br>from fastapi.responses import StreamingResponse<br><br>from handlers import MyCustomHandler<br>from threading import Thread<br><br>from dotenv import load_dotenv<br>from queue import Queue<br><br>#Separate package for OpenAI<br>from langchain_openai import ChatOpenAI<br><br>#Importing Message templates<br>from langchain.schema.messages import HumanMessage<br><br># loading the OPENAI_API_KEY<br>load_dotenv()<br><br># Creating a FastAPI app<br>app = FastAPI()<br><br># Creating a Streamer queue<br>streamer_queue = Queue()<br><br># Creating an object of custom handler<br>my_handler = MyCustomHandler(streamer_queue)<br><br># Creating the llm object and providing the reference of the callback<br>llm = ChatOpenAI(streaming=True, callbacks=[my_handler], temperature=0.7)</pre><p>Now is the time to build the generator that populates the queue with the tokens</p><p>Here, we need to do the following</p><ol><li>Write a generate function — The generate function, in this case is the llm.invoke function. This gives the response in the form of an <a href="https://api.python.langchain.com/en/stable/messages/langchain_core.messages.ai.AIMessage.html">AIMessage</a> Template</li><li>Create a Thread — A thread needs to be initiated with the above function as a target. Since the llm.invoke function returns an AIMessage, we wont be able to provide it as a target to the Thread. Therefore, we need to write a wrapper function and provide it as a target to the thread</li><li>Start the Thread — This is a straightforward process</li></ol><h4>Wrapper Function for generation</h4><p>The wrapper function to be used for the generation in this example would have a single line. Since the response is being rendered as a streaming service we dont have much use of returning the response. However, if you are extending this logic to any of your existing applications where you do something extra, like history maintenance, storing the response in a database, please extend this function with the desired logic or functionality.</p><p>Lets look at the generator functions.</p><pre>%fast_langchain.py<br><br># Generate wrapper function as discussed above<br># Please extend this with the required functionality<br># We are not returning anything as llm has already been tagged<br># to the handler which streams the output<br>def generate(query):<br>    llm.invoke([HumanMessage(content=query)])<br><br><br>def start_generation(query):<br>    # Creating a thread with generate function as a target<br>    thread = Thread(target=generate, kwargs={&quot;query&quot;: query})<br>    # Starting the thread<br>    thread.start()</pre><h4>The consumer function</h4><p>This is the function that returns a generator that consumes the words put in the queue. The following is the logic:</p><ol><li>Start the generation process</li><li>Start an infinite loop</li><li>Get the value from the streamer queue</li><li>If value is stop_signal, break the loop, else yield the value</li></ol><pre>%fast_langchain.py<br><br>async def response_generator(query):<br>    # Start the generation process<br>    start_generation(query)<br><br>    # Starting an infinite loop<br>    while True:<br>        # Obtain the value from the streamer queue<br>        value = streamer_queue.get()<br>        # Check for the stop signal, which is None in our case<br>        if value == None:<br>            # If stop signal is found break the loop<br>            break<br>        # Else yield the value<br>        yield value<br>        # statement to signal the queue that task is done<br>        streamer_queue.task_done()<br><br>        # guard to make sure we are not extracting anything from <br>        # empty queue<br>        await asyncio.sleep(0.1)</pre><h4>Create the end point</h4><p>Finally, we need to create the end point, such that it takes query as a get request parameter and sends it to the response generator function.</p><pre>%fast_langchain.py<br><br>@app.get(&#39;/query-stream/&#39;)<br>async def stream(query: str):<br>    print(f&#39;Query receieved: {query}&#39;)<br>    return StreamingResponse(response_generator(query), media_type=&#39;text/event-stream&#39;)</pre><h3>Now that we have finished, lets test out our streamer</h3><p>For this we create a notebook with the following cells</p><pre>import requests</pre><pre># Sending the query in the get request parameter<br>query = &quot;How to print hello world in python&quot;<br>url = f&#39;http://127.0.0.1:8000/query-stream/?query={query}&#39;<br><br>with requests.get(url, stream=True) as r:<br>    for chunk in r.iter_content(1024): <br>        print(chunk.decode(&#39;utf-8&#39;), end=&quot;&quot;)</pre><p>We need to start our server, using the below command in the command line</p><pre>uvicorn fast_langchain:app</pre><p>It would be started similar to below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*8gdzr0QITO6sHTQxWitFRA.png" /><figcaption>Uvicorn server started</figcaption></figure><p>Now, lets run the notebook to see the response</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*mS7iMQ0VoAc57m78bOsiPQ.gif" /><figcaption>Response of the Streaming</figcaption></figure><p>We see that we are able to get the response in a streaming fashion.</p><h3>Where to go from here ?</h3><p>In the above example most of the changes were done in the producer side, with the consumer function being largely similar to what has been done in the <a href="https://medium.com/@jaswanth04/streaming-llm-responses-using-fastapi-deb575554397">previous article</a>.</p><p>We have seen, how to obtain a streaming response using callback handlers in Langchain for OpenAI. We have only seen the case of general query prediction</p><ol><li>If you want to use RAG with Retrieval QA, you can provide the llm to the retrievalQA object which can generate the response. Just instantiate the retrievalQA object in the global context, and modify the generate function accordingly</li><li>Similarly you can use the above logic for agents as well</li><li>You can also look at other functions in the BaseCallbackHandler class, which can provide specific functionalities for Retrival classes and Agent classes. The functions are — on_retriever_start, on_retriever_error, on_retriever_end, on_agent_action, on_agent_finish</li><li>As mentioned in the previous articles, you can improve this code by wide variety of things — adding a frontend, making the requests as POST requests, adding more security, containerization and bunch of other software engineering stuff</li></ol><h3><strong>Conclusion</strong></h3><p>In this article we have seen — basics of handlers, modification of the producer to use the handler, minimal modification of the consumer and next steps for improvement of the application. Such applications can be very happily used in production with some additional changes from security, front end etc.</p><p>The code used in the article is uploaded <a href="https://github.com/jaswanth04/llm_response_streaming">here</a>.</p><p>Please follow for more such articles.</p><p>If you have any questions about the content, or want to discuss more, please leave a response or write to me at jaswanth04@gmail.com.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=329f588d3b40" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/streaming-responses-from-llm-using-langchain-fastapi-329f588d3b40">Streaming Responses from LLM using Langchain + FastAPI</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streaming LLM Responses using FastAPI]]></title>
            <link>https://blog.stackademic.com/streaming-llm-responses-using-fastapi-deb575554397?source=rss-9377ebaddb70------2</link>
            <guid isPermaLink="false">https://medium.com/p/deb575554397</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Jaswant Jonnada]]></dc:creator>
            <pubDate>Sun, 26 Nov 2023 03:14:32 GMT</pubDate>
            <atom:updated>2024-09-25T15:38:18.970Z</atom:updated>
            <content:encoded><![CDATA[<h3>Streaming Locally Deployed LLM Responses Using FastAPI</h3><p>I hope everyone is going through the latest happenings in the world of Large Language Models (LLM). When the first Generative Pre-Trained Model (GPT) has come out, people were very amazed by its generative capabilities. However, this technology went into mainstream when it was nurtured by OpenAI and a product by name <a href="https://chat.openai.com/">ChatGPT</a> was released.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LlhwFgdzKHfNByZRw__ijw.jpeg" /><figcaption>Attempt at trying to create a logo image for this article using Stable Diffusion</figcaption></figure><p>But the model that OpenAI was using was never open to public and many were not aware of the methodology that they were using for the text generation. But, the Open source community was not far behind and they had started to provide many open source models that could be fine tuned for a use case. These models can be used for small and specific tasks by training them on our custom data set.</p><p>However, people were amazed at the speed with which ChatGPT responds, but the open source models would take more that 6 seconds for response, if the GPU used is small. The reason being, GPT uses an auto regressive approach during inference.</p><blockquote><em>💡 </em><strong>If you’re curious to know the foundations of generative AI, check out this guide:</strong></blockquote><p><a href="https://differ.blog/p/foundation-pillars-of-genai-generative-models-latent-space-sampling-and-reconstruction-3b852d">Foundation Pillars of GenAI: Generative Models, Latent Space, Sampling and Reconstruction</a></p><h3>What is auto regressive approach ?</h3><p>Whenever we want to ask a question to the GPT model, we ask it using a prompt. The model would then follow the below process:</p><ol><li>Take the prompt as model input, and predict the immediate next token</li><li>This next token is once again added to the prompt, and another token is predicted</li><li>Similarly, the output of one step is added to the input of a next step, till we receive the end of sentence or STOP token</li><li>All the tokens predicted till now, are decoded and then sent back</li></ol><p>The process of constructing the final sentence through a step by step inference is called as an auto regressive approach.</p><p>If the generation tokens size is 512, then it means that we are performing inference of the model 512 times, which usually takes time when we are doing inference with Open Source models.</p><h3>What is the solution now ?</h3><p>If you have taken a look at the method of generation of Chat GPT of OpenAI, it is a streaming response. This means that, the first word prints and the subsequent words print after the first word.</p><p>We can follow a similar strategy while hosting our custom Open source models as well.</p><p>Just consider a hypothetical scenario, you have used an Open source model like LLama2–7b-chat-hf. You have fine tuned it on your dataset. But, when you want to deploy it in production, you are really worried about the speed of its response, which is taking 2 to 3 seconds on a T4 GPU, whereas Open AI would give the response in less than a second. The solution is that, you should consider building a streaming service, so that as soon as the model predicts, you stream it back to your front end, showing a very less latency in your open source model prediction. The overall prediction time would still remain the same. But, nevertheless you can keep your user engaged by giving them the data that they want.</p><h3>Simple example of streaming in FAST API</h3><p>In this article, we are using Fast API, to host our model. Fast api does have a streaming class, where it can stream the responses of the request it gets.</p><p>If you go back to the basics of Data structure, you would require something like a Queue. The generator would put the data into the Queue, and the server would read data out of the queue, and transmit as a response.</p><p>The architecture for this will be as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*yT6rlG3VfQ6e37Cts0X69A.png" /><figcaption>Architecture for the data streaming application</figcaption></figure><p>Let’s build a fake data streamer now, to understand the underlying principle of streaming in Fast API. We also intialize the queue in the process. It is preferred to use the <a href="https://docs.python.org/3/library/queue.html">Queue</a> instead of <a href="https://docs.python.org/3/library/collections.html#collections.deque">collections deque</a>, as the former provides better synchronization and thread support.</p><pre>from fastapi import FastAPI<br>from queue import Queue<br><br># creating a fast application<br>app = FastAPI()<br><br># initializing the queue<br>streamer_queue = Queue()<br><br># fake data streamer<br>def put_data():<br>  some_i = 20<br>    for i in range(20):<br>      streamer_queue.put(some_i + i)</pre><p>In order to start the generation process, we need to initialize a thread, which runs the put_data function which adds data into the streamer queue.</p><pre># Creation of thread <br>def start_generation():<br>    thread = Thread(target=put_data)<br>    time.sleep(0.5)<br>    thread.start()</pre><p>Now that we have developed our fake generator, we would need a server or a consumer, that would read the data out of the queue whenever available, and send it out.</p><pre># This is an asynchronous function, as it has to wait for<br># the queue to be available<br>async def serve_data():<br>    # Optinal code to start generation - This can be started anywhere in the code<br>    start_generation()<br><br>    while True:<br>        # Stopping the retreival process if queue gets empty<br>        if streamer_queue.empty():<br>            break<br>        # Reading and returning the value from the queue<br>        else:<br>            value = streamer_queue.get()<br>            yield str(value)<br>            streamer_queue.task_done()<br>        # Providing a buffer timer to the generator, so that we do not<br>        # break on a false alarm i.e generator is taking time to generate<br>        # but we are breaking because the queue is empty<br>        # 2 is an arbitrary number that can be changed based on the choice of<br>        # the developer<br>        await asyncio.sleep(2)</pre><p>Now, finally we need to write our endpoint. The endpoint will be calling serve data function and the response of the function will be sent to the front end</p><pre># Using the endpoint by name /query-stream<br>@app.get(&#39;/query-stream/&#39;)<br>async def stream():<br># We use Streaming Response class of Fast API to use the streaming response<br>    return StreamingResponse(serve_data(), media_type=&#39;text/event-stream&#39;)</pre><p>Now, that the entire code is ready, we create a file by name fast_trial.py and load it using the command</p><pre>uvicorn fast_trial:app</pre><p>The server would start up as given in the below image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*LUIN-TlwuEHCGt7PqxzX2A.png" /><figcaption>Starting the fast api server we created</figcaption></figure><p>Now, in order to test our fast api streaming, we create a file by name stream_test.py, and put the following content in it</p><pre># using requests library to check the response<br>import requests<br><br># the stream has started in the local host<br>url = &quot;http://127.0.0.1:8000/query-stream/&quot;<br><br># sending a request and fetching a response which is stored in r<br>with requests.get(url, stream=True) as r:<br>    # printing response of each stream<br>    for chunk in r.iter_content(1024):<br>        print(chunk)</pre><p>After executing the above script, the response received will be in below format</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*2R20ToTWuvC--McZ1vcQgg.gif" /></figure><h3>How do we extend the same concept for LLM ?</h3><p>In the example seen above, we created a fake data streamer, that puts data into the queue, but in case of LLM, we need to find a function that does the work of the data streamer and puts each word into the queue, and stop keeping words into the queue when the stop signal is received.</p><p>We need to update the architecture as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*74OkAM4kNWegAzB7SpxzOw.png" /><figcaption>Architecture for LLM response generator, where the fake data streamer got replaced with LLM Model Response Token Generator</figcaption></figure><p>Fortunately, we have couple of classes implement in Hugging Face which does the above work. One is the <a href="https://github.com/huggingface/transformers/blob/main/src/transformers/generation/streamers.py#L24">BaseStreamer</a> class, and another one is the inherited implementation of the above mentioned BaseStreamer class called as <a href="https://github.com/huggingface/transformers/blob/main/src/transformers/generation/streamers.py#L38">TextStreamer</a>.</p><p>Let us take a look at the code of BaseStreamer class, from HuggingFace source libraries</p><pre>class BaseStreamer:<br>    &quot;&quot;&quot;<br>    Base class from which `.generate()` streamers should inherit.<br>    &quot;&quot;&quot;<br><br>    def put(self, value):<br>        &quot;&quot;&quot;Function that is called by `.generate()` to push new tokens&quot;&quot;&quot;<br>        raise NotImplementedError()<br><br>    def end(self):<br>        &quot;&quot;&quot;Function that is called by `.generate()` to signal the end of generation&quot;&quot;&quot;<br>        raise NotImplementedError()</pre><p>It is defined as an abstract class, which has two methods put and end to be implemented.</p><p>put -&gt; Method that chooses what happens to the new tokens pushed by the model.generate() function</p><p>end -&gt; Method that chooses what to do when the stop signal is pushed by the model.generate() function</p><p>The <a href="https://github.com/huggingface/transformers/blob/main/src/transformers/generation/streamers.py#L38">TextStreamer</a> inherits the BaseStreamer class and implements the put function in the following way:</p><ol><li>Initializes a token cache list, to convert set of tokens into words,</li><li>Each token received by <em>put</em> function converted to a word by the decoder,</li><li>Each word is checked and,</li><li>If the word received ends with a new line, the cache is flushed,</li><li>If the word received is a chinese charecter, it gets assigned to printable text which will printed by the function <em>on_finalized_text,</em></li><li>Else, it will take all the words in cache until a blank space is found and prints to the screen, by calling the function <em>on_finalized_text</em></li></ol><p><a href="https://differ.blog/differ-ai">Introducing DifferAI</a></p><h3>How is the above implementation different from the streaming implementation that we discussed ?</h3><p>The above implementation uses a cache list, but in case of the Fast API response we are using a Queue. So, our implementation, needs to contain a class that takes the Queue as an input, and feeds the words to the queue, in the <em>on_finalized_text </em>function.</p><p>Let’s implement our custom streamer to modify the above function, which inherits the above mentioned TextStreamer class</p><pre># Contents of streamer.py file<br><br># Importing the TextStreamer class from transformers<br>from transformers import TextStreamer<br><br># Defining a custom streamer which inherits the Text Streamer<br>class CustomStreamer(TextStreamer):<br><br>    def __init__(self, queue, tokenizer, skip_prompt, **decode_kwargs) -&gt; None:<br>        super().__init__(tokenizer, skip_prompt, **decode_kwargs)<br>        # Queue taken as input to the class<br>        self._queue = queue<br>        self.stop_signal=None<br>        self.timeout = 1<br>        <br>    def on_finalized_text(self, text: str, stream_end: bool = False):<br>        # Instead of printing the text, we add the text into the queue<br>        self._queue.put(text)<br>        if stream_end:<br>            # Similarly we add the stop signal also in the queue to <br>            # break the stream<br>            self._queue.put(self.stop_signal)</pre><p>Now that we created our custom streamer, we also need to make changes to the fast main file.</p><h4>Load the Model and Tokenizer</h4><p>We can use any open source model or even our fine tuned model. In this example a fine tuned model has been used which was fine tuned using QLoRA. A specific load_model function has been written and used over here. Please use your own function for loading the model and tokenizer.</p><pre>from load_model import load_model<br>model, tokenizer = load_model()</pre><h4>Initialize the streamer</h4><p>The custom streamer that we created needs to be initialized</p><pre>from streamer import CustomStreamer<br>streamer_queue = Queue()<br>streamer = CustomStreamer(streamer_queue, tokenizer, True)</pre><h4>Develop a generation method</h4><p>This is the method which</p><ol><li>takes the query as an input,</li><li>injects the query into a prompt,</li><li>starts a thread with model.generate()</li></ol><pre>def start_generation(query):<br><br>    # Custom prompt template, can be replaced based on the use case<br>    prompt = &quot;&quot;&quot;<br><br>            # You are assistant that behaves very professionally. <br>            # You will only provide the answer if you know the answer. If you do not know the answer, you will say I dont know. <br><br>            # ###Human: {instruction},<br>            # ###Assistant: &quot;&quot;&quot;.format(instruction=query)<br>    # Converting the inputs to tokens for prediction<br>    inputs = tokenizer([prompt], return_tensors=&quot;pt&quot;).to(&quot;cuda:0&quot;)<br>    <br>    # key word arguments that are provided to the model.generate()function<br>    # Includes, inputs, max_tokens, streamer, temparature<br>    generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=64, temperature=0.1)<br>    <br>    # Starting the thread with the stream<br>    thread = Thread(target=model.generate, kwargs=generation_kwargs)<br>    thread.start()</pre><h4>Develop a Response Generator</h4><p>The above method is used to put the LLM response into the queue. We would need a method which needs to be used to retrieve the data from the queue and present it to the front end</p><p>It takes the query as an input, and It does</p><ol><li>Initiate the previous generation process with the query</li><li>Start an infinite loop</li><li>Get an output from the queue</li><li>If output is None (stop_signal), then it breaks</li><li>It yields the value</li><li>sleeps for 0.1 s using asyncio.sleep()</li></ol><pre>async def response_generator(query):<br>    <br>    # Starting the generation process<br>    start_generation(query)<br><br>    # Infinite loop<br>    while True:<br><br>        # Retreiving the value from the queue<br>        value = streamer_queue.get()<br><br>        # Breaks if a stop signal is encountered<br>        if value == None:<br>            break<br><br>        # yields the value<br>        yield value<br><br>        # provides a task_done signal once value yielded<br>        streamer_queue.task_done()<br><br>        # guard to make sure we are not extracting anything from <br>        # empty queue<br>        await asyncio.sleep(0.1)</pre><h4>Modify the end point</h4><p>Finally, we need to modify the end point, such that it takes query as a get request parameter and sends it to the response generator function.</p><pre>@app.get(&#39;/query-stream/&#39;)<br>async def stream(query: str):<br>    print(f&#39;Query receieved: {query}&#39;)<br>    return StreamingResponse(response_generator(query), media_type=&#39;text/event-stream&#39;)</pre><p>Our final code is ready, let us create a file by name fast_llm.py and copy all our code there. The final code looks like below.</p><pre># Contents of fast_llm.py<br><br>from fastapi import FastAPI<br>import asyncio<br>from fastapi.responses import StreamingResponse<br>from load_model import load_model<br><br>from streamer import CustomStreamer<br>from threading import Thread<br><br>from queue import Queue<br><br><br>app = FastAPI()<br><br># Loading the model<br>model, tokenizer = load_model()<br><br># Creating the queue<br>streamer_queue = Queue()<br><br># Creating the streamer<br>streamer = CustomStreamer(streamer_queue, tokenizer, True)<br><br># The generation process<br>def start_generation(query):<br><br>    prompt = &quot;&quot;&quot;<br><br>            # You are assistant that behaves very professionally. <br>            # You will only provide the answer if you know the answer. If you do not know the answer, you will say I dont know. <br><br>            # ###Human: {instruction},<br>            # ###Assistant: &quot;&quot;&quot;.format(instruction=query)<br>    inputs = tokenizer([prompt], return_tensors=&quot;pt&quot;).to(&quot;cuda:0&quot;)<br>    generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=64, temperature=0.1)<br>    thread = Thread(target=model.generate, kwargs=generation_kwargs)<br>    thread.start()<br><br># Generation initiator and response server<br>async def response_generator(query):<br><br>    start_generation(query)<br><br>    while True:<br>        value = streamer_queue.get()<br>        if value == None:<br>            break<br>        yield value<br>        streamer_queue.task_done()<br>        await asyncio.sleep(0.1)<br><br>@app.get(&#39;/query-stream/&#39;)<br>async def stream(query: str):<br>    print(f&#39;Query receieved: {query}&#39;)<br>    return StreamingResponse(response_generator(query), media_type=&#39;text/event-stream&#39;)</pre><h4>Now that we have finished, lets test out our streamer</h4><p>For this we need to create a stream_test.py</p><pre>import requests<br><br># Sending the query in the get request parameter<br><br>query = &quot;Who are you?&quot;<br><br>url = f&quot;http://127.0.0.1:8000/query-stream/?query={query}&quot;<br><br>with requests.get(url, stream=True) as r:<br>    for chunk in r.iter_content(1024):<br>        print(chunk)</pre><p>Now, let us start the above created server, using the command</p><pre>uvicorn fast_llm:app</pre><p>It will take some time to initialize, as we need to load the model as well</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nd2JUrdCBpRXhlgm7_mZ1A.png" /><figcaption>The script has started</figcaption></figure><p>Once we run the stream_test.py file, we get the following response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*MFpJkygj-_axKZcsS2CFuw.gif" /><figcaption>Streaming Response</figcaption></figure><p>We can see that, the entire response looks fast, as it is being streamed. Without streaming, it will give a sense that our custom Local LLM is very slow.</p><h3>What did we achieve ?</h3><p>Till now we have seen, how to achieve the a response streaming of Open Source LLM which has been fine tuned and running locally. We have looked at a method in which, we can provide a feel of reduced latency by streaming each token when the model is being inferenced in an auto regressive manner.</p><p>Of course, you can say that there are tools out there which does all these things for use like VLLM, LangStream etc., why do we need to know these. I would prefer doing things from scratch and understanding things from the ground basics. The point of this tutorial is to show that, we dont need the fancy packages out there, we just need to gather understanding of simple concepts. Here, we used the Hugging face transformers package and FastAPI, which are quite the foundation level packages. Using this understanding, we can build more complex packages by ourselves, and reduce our reliance on fancy packages out there.</p><h4>Where can you go from here?</h4><p>Now that, you have understood the basics of inference streaming of LLM, we can take it a level further, by</p><ol><li>Making it a post request</li><li>Keeping a front end, and polishing the response to be in much presentable format</li><li>Using sessionization, so that queues are not shared when multiple requests come at the same time</li><li>Containarize the application, and push to kubernetes for deployment</li><li>Use databases for storing the requests and response</li><li>Improving the Streamer class, by using a new data structure instead of a Queue</li><li>Improve security to the application</li><li>And a bunch of other software engineering stuff</li></ol><h3>Conclusion</h3><p>Thanks for reading this article. Please try out these techniques. The code presented in this article can be found <a href="https://github.com/jaswanth04/llm_response_streaming">here</a>.</p><p>Please follow for more such articles.</p><p>If you have any questions about the content, or want to discuss more, please leave a response or write to me at jaswanth04@gmail.com.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=deb575554397" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/streaming-llm-responses-using-fastapi-deb575554397">Streaming LLM Responses using FastAPI</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Discrete Variational Auto Encoder Explained !!!]]></title>
            <link>https://jaswanth04.medium.com/discrete-variational-auto-encoder-explained-41493ebe294d?source=rss-9377ebaddb70------2</link>
            <guid isPermaLink="false">https://medium.com/p/41493ebe294d</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[deep-autoencoder]]></category>
            <dc:creator><![CDATA[Jaswant Jonnada]]></dc:creator>
            <pubDate>Sat, 14 Oct 2023 05:32:29 GMT</pubDate>
            <atom:updated>2023-10-14T05:32:29.747Z</atom:updated>
            <content:encoded><![CDATA[<h3>Discrete Variational Auto Encoder Explained !!!</h3><p>Have you ever seen, or interacted with Dall-E or any Stable Diffusion Models which generate mind boggling images based on a given prompt.</p><p>Or have you ever wondered, when a text is generated using ChatGPT, how does a text input be interpreted by a model which accepts only numerical vectors, and how does a numerical vector in the model output is converted into text ?</p><p>The answer to the above question is Embedding, where there is a table called an Embedding table which consists the mapping of a token (a small part of vocabulary — can be a word, root word etc.) and its corresponding vector embedding.</p><p>Just extending the same concept above to generation of an image, we would need to represent an image or a part of an image as a vector that will be an output of encoder and can be reconstructed by a Decoder. For this reason, we need to come up with various methods of representation for an Image.</p><p>The topic Discrete Variational Auto Encoder (DVAE) is one such method that helps us in representing an image as a vector. But, in order to build to the concept of DVAE, we would need to understand the motivation and history of different Image representation methods used in deep learning.</p><p>The topics that we need to know before are — Auto Encoder and Variational Auto Encoder. So let us start understanding them one by one.</p><h3><strong>Auto Encoder</strong></h3><p>Autoencoders are mostly used in Computer vision, where you would want to find a low dimension representation of an image. It is similar to the embeddings in NLP, where a word with a vocab size of V, is represented with a vector of size V in the case of one hot encoding. Sometimes, if the size V is in the order of 10,000 or 100,000 we would go in the route of embeddings to represent a word, which is in the order 300 or 1024 and also takes the entire context into picture.</p><p>Similarly, an Image can also be represented as a collection of pixels, but when an image’s size gets larger, the vector representation also increases. We can represent the image in a low dimension using auto encoders.</p><p>In auto encoders we have two components:</p><ol><li>Encoder: The neural network component that converts Image to a low dimension vector</li><li>Decoder: The neural network component that converts a given low dimension vector to an Image</li></ol><p>We can see an autoencoder below,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K0XNM9FxwDfXkg4qVmMbwg.jpeg" /><figcaption>AutoEncoder</figcaption></figure><p>We will be training both encoder and decoder using the given data. Here, the output Image and the Input Image is supposed to be the same image.</p><p>Hence, the objective function would be a reconstruction loss, which can be mean squared error or smooth L1 Loss. The loss will be calculated between the Image predicted by the network, which is the output Image and actual Image, which is the Input Image. Since, we are essentially reconstructing the Image given as input, we call this as a reconstruction loss.</p><p>The reconstruction loss, used in the subsequent sections also follow the same concept mentioned above.</p><h3><strong>Variational Auto Encoder</strong></h3><p>Training of Auto Encoder kind of setting would require, a lot of data and deep architectures for the Encoder and Decoder. In order to mitigate that, we can use something called as a variational auto encoder, which is an idea that is borrowed from the realm of Graphical Models.</p><p>Here we consider the Low dimension representation as a latent variable. You are given the Input and output which are observed variables. With the help of the observed variables and graphical model given below, we would like to calculate the probabilities <strong>p(z|x)</strong>, where z is the latent variable and x is the observed variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*vpe1njuDOCAc2ExqfBmbLw.jpeg" /><figcaption>Graphical Model; X is observed, Z is hidden variable</figcaption></figure><p>We can obtain the probability <strong>p(z|x)</strong> using the encoder, which is a neural network with parameters θ</p><p>We obtain the probability <strong>p(x|z) </strong>using the decoder, which is also a neural network with parameters ϕ</p><p>When we are training a variational model (find parameters θ and ϕ), we would ideally use the principle of <a href="https://en.wikipedia.org/wiki/Expectation%E2%80%93maximization_algorithm">Expectation Maximization</a> (EM algorithm).</p><p>We need to find the parameters, θ and ϕ, by maximizing the log likelihood, of the joint distribution, <strong>p(x, z) </strong>using EM algorithm. As given by the name, EM algorithm has two steps</p><ol><li>Expectation Step: In this step, we would find the expected value of the log-likelihood of the above given joint distribution</li><li>Maximization Step: In this step, we would find the value of parameters θ and ϕ by maximizing the above found expected value</li></ol><p>Here, the expectation step is tricky, as we need to find the average of variables x and z. Since, z is not observed and we are not able to marginalize z as we don’t know the distribution, we need to use the method of sampling (also called as Monte-Carlo method).</p><p><strong>Why don’t we know the distribution? </strong>We don’t know the distribution as we are expecting the neural network to provide the values of <strong>p(z|x)</strong>.</p><p>For marginalization, we need to perform the following, <br><strong>p(x) = ∫ p(x,z)p(z) ∂z</strong>, because z is a Gaussian distribution since we don’t know the value of <strong>p(x,z)</strong> and <strong>p(z)</strong>, it is impossible to perform the marginalization task.</p><p>So, during the expectation step, we need to perform the monte-carlo method. Now comes the question, on how to represent the monte-carlo method as an objective function in the setting of a neural network, and also combine the expectation and maximization step into a single objective function, so that we can take the advantage of neural networks, and finding the parameters using back propagation.</p><p>So, in order to achieve it, we do couple of things.</p><ol><li>We assume the distributions <strong>p(z|x)</strong> and <strong>p(x|z), </strong>to be Gaussian distribution.</li><li>We use the <a href="https://en.wikipedia.org/wiki/Variational_autoencoder#Reparameterization">reparameterization trick</a>.</li></ol><p><strong>What are we doing here?</strong> Here we, calculated the expected value, using only a single sample. Also as per the formulation of Gaussian distribution, we write the value z = μ(θ) ϵ+ σ(θ),<br>where μ(θ) is the mean, which is a head of an encoder,<br>σ(θ), which is another head of encoder<br>ϵ, is a random variable sample from a Normal Distribution with mean 0 and variance of 1.</p><p>Here z, will be an input to the decoder. We rewrite the joint distribution equation <strong>p(x,z)</strong> by including <strong>q(z)</strong> and come up with a term called as <a href="https://en.wikipedia.org/wiki/Variational_autoencoder#Evidence_lower_bound_(ELBO)">Evidence Lower Bound (ELBO)</a>. Here we introduce an approximate distribution of q(z) which is Gaussian, and try to reduce the <a href="https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence">KL divergence</a> between p(z|x) and q(z). KL divergence, would determine how a distribution is different when compared with another distribution.</p><p>So, for training the Variational AutoEncoder, we have two losses that we need to optimize:<br>1. Reconstruction Loss<br>2. KL divergence</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bcvedde9JMzqdx4gAu4WLw.jpeg" /><figcaption>Variational Auto Encoder</figcaption></figure><h3><strong>Discrete Variational Auto Encoder</strong></h3><p>In the above setting, we have considered the approximate distribution, q(z) as a Gaussian distribution, but in real world, we want to consider it to be more of discrete distribution, where we want to select vector given in a codebook, and find the vector that is near to the value of z.</p><p>But, now we need to find the distribution that would satisfy the reparameterization trick, and also it has to be a discrete distribution. What distribution would satisfy this condition?</p><p>The<a href="https://paperswithcode.com/method/gumbel-softmax#:~:text=Gumbel%2DSoftmax%20is%20a%20continuous,computed%20via%20the%20reparameterization%20trick."><strong> Gumbel softmax distribution</strong></a> satisfies these conditions.</p><p><strong>What is Gumbel Softmax distribution?</strong></p><p>Assume that the distribution z contains k classes, and is represented by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/145/1*kxW0QkvpP8i0H_y_88z8cw.gif" /></figure><p>We need to draw from a Gumbel distribution so that, z can be represented as one hot vector of the above mentioned distribution. In short, we can write the value of z as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*lu1WHor_Qk9yMMMCPKIfAQ.gif" /></figure><p>The Gumbel sample is drawn using the following procedure</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*yDi45r6ty0wxY7g91K5Ytg.gif" /></figure><p>Where, we are drawing from a uniform distribution and create a sample of g by taking a negative log of u, and once again taking a negative log of the result.<br>We then add the value of g to log of π, which will then be used to take argmax, and a one hot value is taken.</p><p>We maintain a codebook, that contains the information of the classes. The one hot vector returned after sampling is then multiplied to the code book and the output vector that is obtained is then considered as sample and sent to the decoder..</p><p>The sampling process would look like below, where the encoder would output the Log probabilities. We get the gumbel samples using the above mentioned gumbel techniques. We retrieve the vector information from the codebook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cd3WNJfo8pj4jDLUyZy_Sg.jpeg" /><figcaption>Discrete Variational Auto Encoder with Gumbel Sampling</figcaption></figure><p>The codebook weights are similar to the embeddings in NLP, which will also be trained during backpropagation.</p><p>Similar to the Variational Autoencoders, we would optimize the weighted combination of KL Divergence and the reconstruction loss. But, unlike the Gaussian distribution, we don’t have a proper closed form distribution for the Gumbel, hence we need to use the KL divergence library of <a href="https://pytorch.org/docs/stable/generated/torch.nn.functional.kl_div.html">pytorch</a> or <a href="https://www.tensorflow.org/api_docs/python/tf/keras/losses/KLDivergence">tensorflow</a>, for calculating the KL Divergence and optimizing for the same.</p><p><strong>How is the above process discrete ?</strong></p><p>The above process is discrete as we are picking out a representation which is already present in the codebook, and not generating a continuous representation as in Variational Auto Encoder. This helps in solving many real world problems, where image information makes sense to be represented in a discrete manner rather than a continuous manner. Here the value of z that is the output of Encoder is discrete.</p><h4>Conclusion</h4><p>In this article, we have seen the concept of Auto Encoders, Variational Auto encoders and Discrete Variation Auto Encoders, which are used for representation of an image. A pytorch implementation of DVAE is present <a href="https://github.com/jaswanth04/DiscreteVAE">here</a>.</p><p>Please leave a comment or a feedback for this article. If you need to know more, please drop a mail to jaswanth04@gmail.com</p><p>I am planning to come up with an article on Vector Quantized Variational Auto Encoder (VQVAE), which is an extension of Discrete Variational Auto Encoder very soon. Please consider following me to get notifications about the same.</p><p>See you soon !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41493ebe294d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Checkbox detection using Basic Computer Vision Tools]]></title>
            <link>https://jaswanth04.medium.com/checkbox-detection-using-basic-computer-vision-tools-6b895a47ca3f?source=rss-9377ebaddb70------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b895a47ca3f</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[opencv-python]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[document-understanding]]></category>
            <category><![CDATA[information-extraction]]></category>
            <dc:creator><![CDATA[Jaswant Jonnada]]></dc:creator>
            <pubDate>Thu, 13 Jul 2023 05:12:37 GMT</pubDate>
            <atom:updated>2023-07-13T05:12:37.737Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Consider visiting a doctor, who after thorough examination, wants you to conduct some tests. The doctor has a check list form, which has boxes where the doctor can mark, and beside those boxes, we have the name of the tests. The form would look like below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rE6MGWRBCLHvPGR6fudz9A.png" /><figcaption>Image for tests. The doctor would be filling the above form, by marking the required boxes for the tests to be done</figcaption></figure><p>Once the doctor has marked, and take photo from a mobile phone, we get an image like below. Now how do we automatically extract the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xj4pWSwv0nA8ERPnU61__A.png" /><figcaption>Image of the marked Test Form (The form is marked at random by us)</figcaption></figure><p>Usually, this is a computer vision problem to be solved. At first glance, you would like to navigate towards deep learning methodology, but let me try to convince you that, we can solve this, in a very basic way with First Principles of Computer Vision, by only using OpenCV. Below, I specify the methodology. At the end, there is also a link to the implementation in Python, using only OpenCV.</p><h3>What do we need to solve this problem?</h3><ol><li>Template Image — This is scanned and unmarked image, as shown above.</li><li>ROI Data — The Region of Interest marked on the template Image as a box, whose co-ordinates represent the corresponding test. This information is stored in json format. You will understand more about this as you read the article (Example — <a href="https://github.com/jaswanth04/Checkbox_Detection/blob/main/test_data/TRF-1_annotation.json">https://github.com/jaswanth04/Checkbox_Detection/blob/main/test_data/TRF-1_annotation.json</a>)</li><li>Query Image — This is the marked image whose picture is clicked by the mobile phone as shown above.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*hmxuRbihkXmLNPdTR56tCg.png" /><figcaption>ROI Data after being annotated on the Template Image</figcaption></figure><h3>Process</h3><ol><li>Align Image — Now that we have the template image and ROI data, we would want the query image to be aligned with the template image. To perform this, we would use the SIFT alignment method, also know as Image Registration. More details about Image Registration, is mentioned in <a href="https://medium.com/@hhroberthdaniel/how-to-speed-up-image-registration-with-opencv-by-100x-70c9cf786b81">this article</a>. Once the Image is aligned, we can use the ROI data from the template in order to extract the checkbox area from the Query Image.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NoAl8dIYDa_bzAx3Ikjj_Q.png" /><figcaption>Alignment of Query Image with the Template Image. After Alignment, we can easily extract the ROI that was marked on</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*RbOyO6o8_ydcFInf9oby0A.png" /><figcaption>The ROI marked on the Query Image Post Alignment</figcaption></figure><p>2. Now that, we have the query image aligned with the template image, we now need to extract the pixels of the marked ROI</p><p>3. For each ROI, we need to check if the extracted pixels contain mark in them or not</p><h3>How to Find if an ROI is marked or not</h3><p>Let us pick out a certain ROIs, and try to see, whether it is marked or not.</p><ol><li>The first processing that we perform is binarization. We can use a Adaptive Threshold Binarizer or Otsu Binarizer</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*A1-5e27ChqIpZ1PusW930Q.png" /><figcaption>Performing Otsu Thresholding and Adaptive Binarizer. Above mentioned key is the text for the corresponding ROI</figcaption></figure><p>2. Let us assume that we have selected the Adaptive Thresholding. We can see some small artifacts or boxes protruding. We can clean the boxes using contours. If the area of the contours are less than a specified threshold, we can consider it to be noise and remove them. When I say remove the noise, it means we are filling the contours with black color.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*OxWakGC3QJPdk3J-np12gQ.png" /><figcaption>Adaptive threshold, post cleaning</figcaption></figure><p>3. Now from the above image, we would want to remove the box. The box can be considered as a combination of horizontal and vertical lines. Let us consider the horizontal lines, first. We use two operations to remove the horizontal lines. We look at the Morphology operator, and hough line transforms. If we use a Morphology Rectangle of (4, 1) we obtain the repair kernel across horizontal lines. For more information of Morphology operations, please go through <a href="https://medium.com/analytics-vidhya/morphological-transformations-of-images-using-opencv-image-processing-part-2-f64b14af2a38">this article</a>. We repair the image with the above Morphology operator, and then find the hough lines. We filter only those lines, where the angle is between 6 and -6 degrees (which say that it is a vertical line). We paint the hough lines black, and we can see the result below, where all the horizontal lines are removed. For more information on Hough Lines, please visit <a href="https://medium.com/@tomasz.kacmajor/hough-lines-transform-explained-645feda072ab">this article</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*iMkAqCHQlhgqqP-uqZyXMg.png" /><figcaption>Removing the Horizontal Lines. Rep Horiz is the horizontal repair kernel after morphology operation. Horiz Lines are Hough Lines marked on the Non Binarized ROI Image. Only Horiz Removed is the image after removing the Hough Lines and Rep Horiz lines from the binarized image</figcaption></figure><p>4. After removing the horizontal line, we need to remove the vertical lines. We follow the same operation as for the horizontal lines. The changes from previous step are - we use a Morphology Rectangle of (1,4) to obtain repair kernel for vertical lines. For hough lines, we filter the lines, where the angle is between 84, and 96 degrees (which determines the vertical lines). We paint the vertical hough lines black to remove them.</p><p>5. As a final cleaning step, we clean any noise that remains (same as step 2), and then we only have the mark</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0jD6Q-8sMkzSTN-ynCR3bg.png" /><figcaption>Rep Vert is the repair vertical kernel . Vert edges are the vertical hough lines annotated on the non-binarized image. Final is the image where the vertical lines are removed (from step 3) and noise also removed. We can see an integer value after the word final, separated with an _. This value is the count of non black pixels in the image</figcaption></figure><p>6. Finally, we take the count of non black pixels. If the pixels are greater than a certain threshold, we consider the ROI to be marked, else it is not marked.</p><h3>Find the hyper parameters</h3><p>In the above given algorithm, we see the following hyper parameters</p><ol><li>Noise cleaning Threshold — We use this to clear the contours less than certain area</li><li>Vertical line selection Threshold — For Hough lines we use angle between the range 84 to 96, to select the vertical line.</li><li>Horizontal line selection Threshold — For Hough lines we use angle between the range -6 to 6, to select the horizontal line</li><li>Threshold of non black pixels, for which ROI will be considered to be marked.</li></ol><p>We can use our traditional machine learning methodology here.</p><ol><li>We collect some data.</li><li>Then we get the data annotated i.e given an image, what are the entities that are marked.</li><li>Divide the data into training data and test data.</li><li>Select the hyper parameters such that the training data error is less, and</li><li>Test those hyper parameters on the test data.</li></ol><h3>What is the metric to for the Evaluation?</h3><p>The best way to evaluate this, is to consider it to be prediction of sets.</p><p>Consider A, to be the actual set which contains the entities that are marked.</p><p>Let P, be the predicted set, which is derived using the above algorithm.</p><p>We can use Hamming Score to measure the error. The error would be the Intersection of A and P, divided by Union of A and P</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*dc0GwjKpc2tAiFGEu-_Pbw.jpeg" /></figure><p>If A and P are the same, the Hamming Score will be equal to 1.</p><h3>Scope for Improvement</h3><p>The following are the limitations of the above algorithm</p><ol><li>We need a template Image</li><li>We need the ROI data to be pre annotated</li><li>We need to select some Hyper Parameters as well.</li></ol><p>The method to remove the above limitations, is to explore the Deep Learning Route.</p><ol><li>We can use Dewarping, for the Image Cleaning and Alignment</li><li>We can use Document Layout Analysis to extract the ROIs. Here the ROI would include the marked check box, and the corresponding data beside it.</li><li>Then we can use OCR to extract the data beside the checkbox, and perform a simple search with database to map the extracted data to the entity required.</li></ol><p>The idea of this article was to provide to basics of Checkbox Detection, and all the above process can be achieved only by using opencv. There is no need to use any other package. Based on the motivation of the reader, they can collect data and create a Deep Learning based pipeline.</p><h3>Implementation</h3><p>In this article, only the theory has been explained. The implementation can be found at <a href="https://github.com/jaswanth04/Checkbox_Detection">https://github.com/jaswanth04/Checkbox_Detection</a></p><p>There are notebooks in the above repo, which show the above step by step process.</p><p>The execution instructions are also given in the Readme of the repo.</p><p>In case of any questions or suggestions, please raise a Issue in the above mentioned repo, or write to me at jaswanth04@gmail.com</p><p><em>See you. Keep Deep Learning.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b895a47ca3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interactive Pixel Count Visualisation using OpenCV and Matplotlib — Python]]></title>
            <link>https://jaswanth04.medium.com/interactive-pixel-count-visualisation-using-opencv-and-matplotlib-python-b110e5c08dc7?source=rss-9377ebaddb70------2</link>
            <guid isPermaLink="false">https://medium.com/p/b110e5c08dc7</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[matplotlib]]></category>
            <category><![CDATA[analysis]]></category>
            <category><![CDATA[opencv-python]]></category>
            <dc:creator><![CDATA[Jaswant Jonnada]]></dc:creator>
            <pubDate>Mon, 10 Jul 2023 11:14:02 GMT</pubDate>
            <atom:updated>2023-07-10T11:14:02.438Z</atom:updated>
            <content:encoded><![CDATA[<h3>Interactive Pixel Count Visualisation of a video using OpenCV and Matplotlib — Python</h3><h3><strong>Introduction</strong></h3><p>Computer Vision is a field which is becoming famous day by day, with a lot of applications. <br>Similarly Python is a language that is being used a lot in the field of Computer Vision, after C++. <br>As a beginning of any analysis of an Image, we usually start by plotting the intensities of the image in a selected color space.</p><h3>Analysis of Images</h3><p>Any computer vision problem would start with an analysis over Color Spaces. Color spaces are nothing but, representation of pixels in different formats. The most famous Color Spaces:</p><ol><li>RGB — Here the pixel intensity is represented as a combination of intensities of (Red, Green and Blue). Example: Orange is represented as (255, 165, 0)</li><li>HSV — Here the pixel intensity is represented as a combination of Hue, Saturation and Value</li><li>CMY — Here the pixel intensity is represented as a combination of secondary colors like Cyan, Magenta and Yellow.</li><li>YCbCr — Here the pixel intensity is represented as a combination of Yellow, Chromium Blue and Chromium Red.</li></ol><p>We can use the image Analysis to solve very quick problems or analysis. For any analysis, visualization is necessary.</p><p>In python, the visualization of these color spaces can be done using Matplotlib. We use OpenCV for analysing images and videos.</p><h3>Steps for creating an interactive analyzer</h3><p>First we read an image, using imread function of opencv, and extract the values of each channel (R, G, B)</p><pre># Import OpenCV<br>import cv2</pre><pre># Read an Image<br>image_name = &quot;path-to-image&quot;<br>img = cv2.imread(image_name)</pre><pre># By default, the image is read in BGR format<br># Converting the image to RGB<br>img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)</pre><pre># Splitting the color channel values into their own vectors<br>(r, g, b) = cv2.split(img)</pre><p>Then we use the calc hist function (that comes as an inbuilt function in opencv) to calculate the histograms in the image</p><p>The following are the parameters for the calc hist function</p><ol><li>Images: We can give a single image or multiple Images. The image needs to be of type uint8 or float32</li><li>Channels : it is also given in square brackets. It is the index of channel for which we calculate histogram. For example, if input is grayscale image, its value is [0]. For color image, you can pass [0], [1] or [2] to calculate histogram of blue, green or red channel respectively.</li><li>Mask : mask image. To find histogram of full image, it is given as “None”. But if you want to find histogram of particular region of image, you have to create a mask image for that and give it as mask. (I will show an example later.)</li><li>HistSize : this represents our BIN count. Need to be given in square brackets. For full scale, we pass [256].</li><li>Ranges : this is our RANGE. Normally, it is [0,256].</li></ol><p>Let’s calculate histograms for all different channels. The reason being, we can use each channel individually for interactive visualization later.</p><pre>histogram_r = cv2.calcHist([r], [0], None, [256], [0, 255])<br>histogram_g = cv2.calcHist([g], [0], None, [256], [0, 255])<br>histogram_b = cv2.calcHist([b], [0], None, [256], [0, 255])</pre><p>Once we calculated the histograms, the next step is to plot them. For plotting we use the most famous plotting library of python, which is matplotlib</p><pre>import matplotlib.pyplot as plt</pre><pre>x_values = range(256)<br>line_width = 3<br>alpha = 0.5</pre><pre># Creating two subplots, to plot image and its intensity<br>fig, ax = plt.subplots(2)</pre><pre>intensity_plot = ax[0]<br>image_plot = ax[1]</pre><pre># Setting the visible axes to be False for the image_plot<br>image_plot.axes.get_xaxis().set_visible(False)<br>image_plot.axes.get_yaxis().set_visible(False)</pre><pre># Setting the x-axis and y-axis limits for intensity plot<br>intensity_plot.set_xlim([0, 255])<br>intensity_plot.set_ylim([0, 5000])</pre><pre># Plotting the histogram in the intensity plot </pre><pre>lineR, = intensity_plot.plot(t, histogram_r, c=&#39;r&#39;, lw=lw, alpha=alpha)<br>lineG, = intensity_plot.plot(t, histogram_g, c=&#39;g&#39;, lw=lw, alpha=alpha)<br>lineB, = intensity_plot.plot(t, histogram_b, c=&#39;b&#39;, lw=lw, alpha=alpha)</pre><pre># Plotting the Image in the Image Plot</pre><pre>im_plot = image_plot.imshow(img)</pre><pre>plt.show()</pre><p>After we run the code written till now, we get the following result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*iSkoiTxx8KPtkQGj8N87pw.png" /><figcaption>Intensity count and Image</figcaption></figure><p>Above, we saw how to visualize a single static image.</p><p>As a next step, lets look at the methods of visualizing all the frames of a given video. For the UI, we can use the same above UI, but we need to add one more slider, so that we can interactively change the frame, where the image of the frame will be shown at the Image plot, and the intensity of the frame will be shown at the intensity plot</p><p>Also, since we would like to make the code much cleaner and reusable, let us implement this Visualizer as a class and call it <strong>PixelCountVisualizer</strong></p><p>Now, to build this class, we need to see what we need in this class, and create methods of the class, based on our need. Based on what this needs to be done in this class, we can use the following methods for our class</p><pre>class PixelCountVisualizer:<br>      def __init__(self, video) -&gt; None:<br>       &quot;&quot;&quot;Initializes the class, a video name is given as input&quot;&quot;&quot;<br>          self._video = video</pre><pre>      def _plot_frame(self) -&gt; None:<br>      &quot;&quot;&quot;Plots each frame on the matplotlib widget&quot;&quot;&quot;<br>          pass</pre><pre>      def _update(self, frame_num) -&gt; None:<br>          &quot;&quot;&quot;Updates the value of the frame, based on the frame number in the graph&quot;&quot;&quot;<br>          pass</pre><pre>      def run(self) -&gt; None:<br>          &quot;&quot;&quot;Should be used to run the plot, once the object is created&quot;&quot;&quot;<br>          pass</pre><p>Now that the barebone class code is ready, lets start populating each method. Let us start with the __init__ method.</p><ol><li>As of now init method intializes the class variable video name.</li><li>We need to initialize the list that stores the r, g and b values for each frame.</li><li>Also we need to create the plots, that would show the image and the intensity as well.</li><li>We also need a list to store all the frames of the video, that can be retrieved when called.</li><li>We need to initialize a count variable, that will be used by the Slider Widget.</li></ol><p>Let’s initialize the list in the init section. So, the init section would look as follows</p><pre>def __init__(self, video) -&gt; None:<br>    &quot;&quot;&quot;Initializes the class, a video name is given as input&quot;&quot;&quot;</pre><pre>    # Set the video variable of the class<br>    self._video = video</pre><pre>    # Initialize the list storing the the pixel values of each frame<br>    self._r_pixel_values = []<br>    self._g_pixel_values = []<br>    self._b_pixel_values = []</pre><pre>    # Initialize the plots<br>    fig, ax = plt.subplots(2)<br>    self._intensity_plot =  ax[0]<br>    self._image_plot = ax[1]</pre><pre>    # Initialize the list to store the frame<br>    self._frames = []<br>    plt.subplots_adjust(bottom = 0.25)</pre><pre>    # Initialize the count variable to be used in the Widget<br>    self._count = 0</pre><p>Let us take a look at the run section now. This section needs to accomplish the following:</p><ol><li>Read the video</li><li>For each frame, calculate the intensity and store the intensity in their corresponding lists, initialized using init method</li><li>Also, increase the count variable by 1 to provide the limit to the slider widget</li><li>Create a slider</li><li>Plot the frames, using the plot_frame method</li></ol><pre>def run(self) -&gt; None:<br>    &quot;&quot;&quot;Public. Should be used to run the plot, once the object is shown&quot;&quot;&quot;</pre><pre>    # Reading the video by openCV<br>    capture = cv2.VideoCapture(self._video)<br>    # Start an infinite loop <br>    while True:</pre><pre>          # Read each frame<br>         (grabbed, frame) = capture.read()<br>         # If no frame read, exit the loop<br>         if not grabbed:<br>            break<br>         <br>         # Read the frame, and convert it to RGB   </pre><pre>         frame = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)<br>         (r, g, b) = cv2.split(img)<br>    </pre><pre>         # Calculate the histograms for each channel<br>         histogram_r = cv2.calcHist([r], [0], None, [256], [0, 255])<br>         histogram_g = cv2.calcHist([g], [0], None, [256], [0, 255])<br>         histogram_b = cv2.calcHist([b], [0], None, [256], [0, 255])<br>         <br>         # Append the frames into the frame list                </pre><pre>         self._frames.append(frame)<br>         <br>         # Append the pixel values for this frame in the list created in the init section<br>         self._r_pixel_values.append(histogram_r)<br>         self._g_pixel_values.append(histogram_g)<br>         self._b_pixel_values.append(histogram_b)</pre><pre>         self._count += 1</pre><pre><br>   # Creating the slider, should be done out of the loop</pre><pre>   pixel_axis = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=&quot;White&quot;)<br>   self._pixel_slider = Slider(pixel_axis, &#39;Frame&#39;,0, self._count, valinit = 0)</pre><pre>   # the pixel slider needs an update function as it should change the plots when the value is moved. <br>   # the update function takes the value provided by the pixel</pre><pre>   self._pixel_slider.on_changed(self._update)</pre><pre>   # Calling the plot frame function</pre><pre>   self._plot_frame()</pre><p>Now let us concentrate on the plot_frame method. This method is used to plot the frame that needs to be displayed on the widget.</p><p>The plot_frame method needs to do the following:</p><ol><li>Set the variables — line width, x-axis values, line width, alpha</li><li>Set the x-axis limits, y-axis limits</li><li>Plot the intensity</li><li>Plot the image</li><li>Show the plot</li></ol><pre>def _plot_frame(self) -&gt; None:<br>    &quot;&quot;&quot;Plots each frame on the matplotlib widget&quot;&quot;&quot;</pre><pre>    # Setting the graph meta data<br>    t = range(256)<br>    line_width = 3<br>    alpha = 0.5</pre><pre>    # Removing the the x and y axis for the image plot<br>    self._image_plot.axes.get_xaxis().set_visible(False)<br>    self._image_plot.axes.get_yaxis().set_visible(False)</pre><pre>    # Setting x and y limits for the intensity ploty<br>    self._intensity_plot.set_xlim([0, 255])<br>    self._intensity_plot.set_ylim([0, 5000])</pre><pre>    # Setting the frames with the first value of the list<br>     histogram_r = self._r_pixel_values[0]<br>     histogram_g = self._g_pixel_values[0]<br>     histogram_b = self._b_pixel_values[0]</pre><pre>    # Plotting the intensites<br>    self._lineR, = intensity_plot.plot(t, histogram_r, c=&#39;r&#39;, lw=lw, alpha=alpha)<br>    self._lineG, = intensity_plot.plot(t, histogram_g, c=&#39;g&#39;, lw=lw, alpha=alpha)<br>    self._lineB, = intensity_plot.plot(t, histogram_b, c=&#39;b&#39;, lw=lw, alpha=alpha)</pre><pre>   # Plotting the image<br>   img = self._frames[0]<br>   self._im_plot = self._image_plot.imshow(img)</pre><pre>   # Showing the plot   <br>   plt.show()</pre><p>All that is remaining is the update function, where we update the Intensity graph and the Image plot based on the value obtained from the slider. This is done in the update method, which takes the frame_num as input. It sets the data on the plots with the intensities and frames that correspond to the frame number selected on the slider. This data is retrieved from the lists that stores the Pixel intensities and the frames.</p><pre>def _update(self, frame_num) -&gt; None:<br>    &quot;&quot;&quot;Updates the value of the frame, based on the frame number in the graph&quot;&quot;&quot;</pre><pre>    # Converting the frame number to integer, as the slider can provide values in float<br>    frame_num = int(frame_num)</pre><pre>    # Modifying the intensity data on the plot<br>    self._lineR.set_ydata(self._r_pixel_values[frame_num])<br>    self._lineG.set_ydata(self._g_pixel_values[frame_num])<br>    self._lineB.set_ydata(self._b_pixel_values[frame_num])</pre><pre>    # Modifying the image on the plot<br>    self._im_plot.set_data(self._frames[frame_num])</pre><p>Now that we have made our class ready. We have to call the class in order to use, it. The class takes only the video path as arguments. Create a main function to call the class</p><pre>def main():<br><br>    video_path = &quot;path_to_video&quot;<br>    <br>    pixel_visualizer = PixelCountVisualizer(video_path)<br>    pixel_visualizer.run()</pre><pre><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Let’s look at the output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*8d6dz0MKUWkr02iG-73iEQ.gif" /><figcaption>Final Output ( Video courtesy by <a href="https://www.videvo.net/">videvo</a>)</figcaption></figure><p>To conclude, using this tool gives a really good interactive visualization mechanism for analyzing the intensity in each frames.</p><p>This analysis can be used in wide variety of use cases:</p><ol><li>Motion analysis</li><li>Spectral Imaging</li><li>Pattern recognition</li><li>Object present in the scene or not</li><li>Sudden motion detection etc</li></ol><p>Above, we saw a very simple implementation of the interactive visualization tool. However, there are many use cases for this visualization:</p><ol><li>Visualizing the intensities in various color spaces (RGB, CMY, HSV, YCbCr)</li><li>Visualizing a list of Images, where the Frame slider would take us through each Image</li><li>Side by side comparison of two videos (which might require implementation of Multi Threading)</li></ol><p>A Complete and Cleaner implementation of PixelCountVisualizer with the above use cases can be found at <a href="https://github.com/jaswanth04/PixelCountVisualizer">https://github.com/jaswanth04/PixelCountVisualizer</a>.</p><p>To know about, how to use the class, please visit — <a href="https://github.com/jaswanth04/PixelCountVisualizer/blob/main/tests/trial.py">https://github.com/jaswanth04/PixelCountVisualizer/blob/main/tests/trial.py</a></p><p>If you have any questions or suggestion related to above package, please write to jaswanth04@gmail.com, or raise an Issue in the above mentioned Github links.</p><p>See you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b110e5c08dc7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>