<?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 Shudipto Trafder on Medium]]></title>
        <description><![CDATA[Stories by Shudipto Trafder on Medium]]></description>
        <link>https://medium.com/@iamsdt?source=rss-24d4f54ea99b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Y-zYpmdxLIxyHNAH_7o86g.png</url>
            <title>Stories by Shudipto Trafder on Medium</title>
            <link>https://medium.com/@iamsdt?source=rss-24d4f54ea99b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 12:31:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iamsdt/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 Summarizing Your Agent’s Memory. Triage It]]></title>
            <link>https://medium.com/@iamsdt/stop-summarizing-your-agents-memory-triage-it-009b20583e57?source=rss-24d4f54ea99b------2</link>
            <guid isPermaLink="false">https://medium.com/p/009b20583e57</guid>
            <category><![CDATA[decision-model]]></category>
            <category><![CDATA[context-engineering]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai-memory]]></category>
            <dc:creator><![CDATA[Shudipto Trafder]]></dc:creator>
            <pubDate>Mon, 09 Nov 2026 13:44:44 GMT</pubDate>
            <atom:updated>2026-11-09T13:44:44.564Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A small decision model decides, turn by turn, what an LLM agent keeps, compresses or forgets.</em></p><blockquote><strong><em>Prompt caching is out of scope here.</em></strong><em> Editing or removing an earlier message changes the prompt from that point on, so content after the edit cannot reuse the cache. Unchanged prefixes, for example the system prompt and tools, can still be reused. Because triage removes the oldest turns, most of the conversation after the system prompt is affected. The exact impact depends on each provider’s caching implementation, and a separate write-up will cover it.</em></blockquote><h3>The problem</h3><p>Every turn and every tool call adds to an agent’s context. That context is sent to the model on each call, so it drives the cost and latency of every call that follows. It also fills with material that no longer matters: old logs, abandoned directions, pleasantries. The noise sits next to the facts the agent needs.</p><p>The default answer is one big summary. When the context passes a limit, you ask an LLM to summarize everything so far and replace the history with the result. That is an all-or-nothing rewrite. It is lossy, it happens in a single irreversible step, and you cannot see why a given detail survived or vanished. It also spends your most expensive model on housekeeping.</p><p>One distinction up front. This is context management: what the model carries into its next call. It is not memory management, which is what an agent retains and retrieves across tasks or sessions. It complements memory systems such as Mem0 or Zep rather than replacing them, and could become a foundation for one.</p><h3>The core idea: triage, not summarize</h3><p><a href="https://github.com/Iamsdt/context-triage">context-triage</a>, built on <a href="https://10xgraph.com/">10xGraph</a>, replaces the single rewrite with a separate decision for each unit of work. A unit is one turn: a user message and everything that answered it. (The Python package inside is still named unforget, its working name.) Each old turn gets one of three actions:</p><ul><li><strong>keep</strong>: leave the turn as it is.</li><li><strong>compress</strong>: replace it with a 1 to 3 sentence note.</li><li><strong>drop</strong>: remove it. This is for greetings, thanks and small talk. Short messages are not automatically disposable: decisions, approvals, corrections and constraints (“Yes, use PostgreSQL”, “Don’t use AWS”) must survive even when they are a few words.</li></ul><p><strong>Illustrative example</strong> (invented for explanation, not output from a run):</p><ul><li>Turn 1: “Hi, how are you?” → drop</li><li>Turn 2: “We are building a recruitment platform on Django and PostgreSQL.” → keep</li><li>Turn 3: a 200-line API log → compress to a one-sentence note, such as “Log showed repeated timeouts on one endpoint.”</li><li>Turn 4: “Thanks!” → drop</li></ul><p>After triage, the working context holds the Django and PostgreSQL turn verbatim, the one-sentence note, and the newest turns. The full conversation stays in persistent history.</p><p>A fourth action, archive, existed in the first version and is covered below as a planned return. The current code does not include it.</p><p>The design rests on a few principles.</p><p><strong>Separate deciding from writing.</strong> A cheap decision model, Cloudflare Clef, decides. It does not write text. For each question it returns a probability for every option plus a confidence. A small writer model, claude-haiku-5–5, then writes notes, and only for the turns marked compress. The main model is never asked to summarize itself.</p><p><strong>Log every decision with its confidence.</strong> Every decision can be recorded with Clef’s suggestion and its model-reported confidence score. That gives you an audit trail of what was removed and how sure the model said it was. It also gives you a gate: if the top option falls below a threshold (0.7 here), the suggestion is ignored and the turn is kept. Be careful what the number means. A 0.95 does not mean the decision is right 95% of the time. The scores are not calibrated against a labelled set. The 0.7 gate is a fail-safe, not an accuracy guarantee.</p><p><strong>Keep three views of one conversation.</strong></p><ul><li><em>Persistent history</em>: the thread’s messages, stored by the checkpointer and never edited.</li><li><em>Active model context</em>: state.context, the only thing triage edits.</li><li><em>User-facing history</em>: in this setup the playground chat renders the stored thread messages, so the user still sees everything.</li></ul><p>Take a medical assistant. A user asks for a poem and the bot refuses: “I only handle medical questions.” Several turns later the context is over budget, and Clef may decide that exchange is chatter with nothing worth reusing. The model stops carrying it, and the user can still scroll up and read it. Note the difference between data retention and model accessibility. The data is retained, but the model cannot read removed turns back.</p><p><strong>Work in whole turns.</strong> Each turn is an atomic unit. That keeps tool calls with their results and avoids leaving half-finished tool interactions in the context. Provider-specific ordering rules still have to be respected. The newest turns are never candidates, so the work in progress is safe.</p><p><strong>Fail safe.</strong> If the decision model fails, the writer fails, or credentials are missing, the context is left unchanged and the reason is recorded. A failed trim costs you tokens, not correctness.</p><p><strong>Measure, do not estimate.</strong> The trigger is the token usage the provider reported for the last reply, not a character count. The check runs only when that number exceeds the budget.</p><p><strong>Write the policy in plain language.</strong> What counts as keep, compress or drop is not a trained classifier. It is the policy dict handed to the decision model:</p><pre>ACTION_CRITERIA = {<br>    &quot;keep&quot;: &quot;Needed verbatim: the current work depends on its exact wording, code or numbers.&quot;,<br>    &quot;compress&quot;: (<br>        &quot;Useful but verbose, such as tool output, logs or listings, or it states preferences &quot;<br>        &quot;or decisions: a 1 to 3 sentence note would keep what matters.&quot;<br>    ),<br>    &quot;drop&quot;: &quot;Greetings, thanks, small talk or chatter with nothing worth reusing.&quot;,<br>}</pre><p>Your team can read this, argue about it and change it without retraining anything. The policy routes preferences and decisions to compress, not drop. Whether the decision model honours that is untested.</p><p>Each turn is clipped to 800 characters (head and tail) before Clef sees it, and this is a named risk. A long requirement whose key constraint sits in the middle can be judged on its edges and dropped. That matters most for code, configs and technical specs. A possible fix is structure-aware extraction before classification, so the decision model sees the parts that carry the constraints.</p><h3>Where it sits in the architecture</h3><p>context-triage is a pluggable context manager in 10xGraph. The flow, in order:</p><ol><li>The run ends and the answer has already been delivered to the user.</li><li>The manager reads the reported token usage of the latest reply. At or under budget, nothing happens.</li><li>Over budget, it groups the history into turns and offers the oldest candidates to Clef, all but the newest turns, in one call with one question per turn.</li><li>Any suggestion below the confidence threshold becomes keep.</li><li>The turns marked compress go to the writer in one batched call.</li><li>Compressed and dropped turns leave the working set, the notes are kept as a short block of context, and each decision is logged.</li></ol><p>The answer has already streamed by the time this runs, so the user does not wait on it.</p><p>The cost shape is a plain sum:</p><p><strong>total cost = classification + compression + cache impact</strong></p><ul><li><strong>Classification</strong> depends on the turns offered per check, the tokens per offered turn, and how often checks fire. Clef is priced at $0.24 per million input tokens, with no output charge.</li><li><strong>Compression</strong> is the writer’s input and output tokens for the turns marked compress.</li><li><strong>Cache impact</strong> is the reuse lost after the context changes.</li></ul><p>The net benefit depends on how many future model calls run on the smaller context. We make no savings claims.</p><h3>Archive: planned, not shipped</h3><p>The first version had a fourth action, archive, plus a recall tool. We removed both to keep the core loop easy to read. Bringing them back is the next step, because they answer the biggest weakness of the three-action version: once a turn is dropped or compressed, the model cannot get the detail back.</p><p>In that version an archived turn left the working set, the full turn was stored verbatim in thread state with a short label, and the context kept an index of labels. When the agent called recall with an item’s number, the turn came back as a tool result and the archive itself was never modified.</p><p>Why this matters to a leader:</p><ul><li><strong>It turns a one-way door into a two-way door.</strong> Where the policy is unsure whether a turn will matter again, it can archive instead of drop.</li><li><strong>It makes the policy safer to tune.</strong> A wrong call becomes one extra tool call instead of a lost fact, so tighter budgets carry less risk of silent loss.</li></ul><p>A recall costs a tool call, with its latency and tokens, and the text re-enters the context when used. There is also a trust boundary. Recalled content is historical data, not fresh instructions. It can contain user instructions, tool output, external documents or prompt-injection attempts, so it must be returned as data, with that boundary made clear to the model.</p><h3>What the one live run showed</h3><p>We have one live run so far, a smoke test on 2026–11–01. It is the only evidence we have.</p><ul><li><strong>Token budget:</strong> 500</li><li><strong>Messages sent:</strong> “Hi”, “what is 1 + 1”, “what is mars”</li><li><strong>Reported context size:</strong> 1183 tokens</li><li><strong>Decision on “Hi”:</strong> drop at 0.73 (an earlier check at 0.546 was below the gate, so it was kept)</li><li><strong>Decision on “what is 1 + 1”:</strong> drop at 0.955</li><li><strong>Model context afterwards:</strong> 2 messages</li><li><strong>Compressed:</strong> none</li></ul><p>What it shows:</p><ul><li>The decision model classified simple turns.</li><li>The gate held back a 0.546 decision.</li><li>Drop shrank the working set to 2 messages.</li><li>The full history stayed visible in the chat.</li></ul><p>What it does not show:</p><ul><li>Correct decisions on complex conversations.</li><li>Preserved facts.</li><li>Compression quality.</li><li>Better task completion.</li><li>Real cost savings.</li></ul><p>The compress path has not run live yet. We report no benchmarks or accuracy numbers.</p><h3>The architectural lesson: provider-signed state</h3><p>When we first removed turns from a conversation with extended thinking, the next request failed with a live 400: “Invalid signature in thinking block.” Claude signs each thinking block against the whole prefix before it. Remove earlier turns and the blocks you kept no longer match the prefix they were signed against.</p><p>The lesson is general. Provider-signed state is bound to its history, so any system that edits context, whether by trimming, summarizing or triage, has to plan for it.</p><p>Our fix is blunt: after any change, strip every signed or redacted thinking block from the remaining messages, not just the first invalid one. The cost is that the model loses its earlier reasoning blocks. This strip route is what context-triage does through 10xGraph.</p><p>There is another route, which we verified in a separate small script on the direct Claude API with claude-sonnet-5–5 (not part of this project). In 10xGraph you pass these as extra Agent kwargs:</p><pre>thinking={&quot;type&quot;: &quot;adaptive&quot;, &quot;block_binding&quot;: {&quot;prefix_mismatch_behavior&quot;: &quot;drop_block&quot;}},<br>extra_headers={&quot;anthropic-beta&quot;: &quot;thinking-binding-controls-2026-08-01&quot;},</pre><p>With drop_block, the request proceeds instead of erroring. It does not preserve the invalidated reasoning: the API discards the thinking blocks whose prefix no longer matches. Because triage removes the oldest turns, in practice most of the earlier reasoning is discarded. It is a beta, and we only verified it on the direct Claude API. The binding check is enforced by default for accounts created on or after 2026-08-31, and setting the field opts a request in.</p><h3>How it compares</h3><ul><li><strong>One-shot summaries</strong>, such as the auto-compact in Claude Code, rewrite the whole history in one pass.</li><li><strong>Observation masking</strong> hides old tool output with a fixed rule. It is cheap but does not look at content.</li><li><strong>LLM-ranked condensers</strong>, such as OpenHands’ attention condenser, keep the top N events and drop the rest, with no reasons.</li><li><strong>Memory stores</strong>, such as Mem0 and Zep, keep facts outside the live context.</li></ul><p>context-triage is a context-management layer that can sit next to a memory store. It makes a separate decision per turn with a cheap model that is not your main model, needs no training, and logs its confidence scores. We do not claim to be first, and we have not measured it against any of these.</p><h3>What a tech lead should weigh</h3><p>Each of these is a decision point, not a footnote.</p><ul><li><strong>Irreversibility for the model.</strong> In the current code, compressed notes lose detail and dropped turns are gone from the model’s context for good. The thread history still holds everything, but the model cannot read it back. Until archive returns, decide whether your use case can live with this.</li><li><strong>Compression quality.</strong> The fail-safe covers a writer that fails, not one that succeeds with a wrong note: a changed number, a reversed decision, a missing identifier. A validation step for structured details (identifiers, dates, numbers, config values, explicit decisions) is an open item.</li><li><strong>Starvation in long threads.</strong> Each check offers the oldest candidate turns first, at most 64 per call. Kept turns are offered again on every over-budget reply. If the oldest 64 are all kept, newer turns beyond them are never evaluated. This is a known limitation of the current code. Possible fixes: a rotating window, recording when a turn was last evaluated, or re-evaluating a kept turn only when something changes.</li><li><strong>Trimming happens only at the end of a run.</strong> One long, tool-heavy run can grow past the budget until it finishes.</li><li><strong>A writer failure skips the whole trim</strong>, including decisions Clef already made. That is the safe choice; a flaky writer means no trim on those checks.</li><li><strong>A second vendor in the stack.</strong> Cloudflare is an extra account, an extra credential and an extra dependency. Compress still costs writer-model tokens.</li><li><strong>Thinking blocks are stripped</strong> after a trim unless you adopt the beta route above.</li><li><strong>Prompt caching.</strong> Editing old context may cancel any gain. We have not modelled it.</li></ul><h3>Questions to answer on your own workload</h3><ul><li>How often does the decision model choose well, judged by someone who knows the task?</li><li>What is lost in the compress notes, and does the agent ever need it back?</li><li>What is the net cost once prompt caching is counted?</li><li>How does task quality change, compared with doing nothing and with a plain summary?</li></ul><h3>The idea worth taking away</h3><p>The architecture separates three responsibilities that a single summary call mixes together:</p><ul><li><strong>Decision</strong>: what deserves space in the context.</li><li><strong>Transformation</strong>: compress what stays useful.</li><li><strong>Retention</strong>: keep the original independent of the model’s active context.</li></ul><p>This separation is the part worth taking away even if you never use Clef. You can swap the decision model, change the writer, or add an archive without touching the other two.</p><p>What we will measure next:</p><ul><li>The compress path in a live run, which has not happened yet.</li><li>Compression validation for identifiers, dates, numbers, config values and explicit decisions.</li><li>A fix for the 64-turn starvation problem.</li><li>Clef’s choice quality on real conversations.</li><li>Real cost against a plain summary.</li><li>Archive and recall: bringing them back, and measuring how often the agent actually recalls what was archived.</li><li>The caching cost, in the follow-up write-up.</li></ul><p>The code and setup instructions are on GitHub: <a href="https://github.com/Iamsdt/context-triage">github.com/Iamsdt/context-triage</a>.</p><p>context-triage is built on <a href="https://10xgraph.com/">10xGraph</a>, a framework for building production AI agents.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=009b20583e57" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agent memory: 7 types, and 2 of them aren’t memory]]></title>
            <link>https://medium.com/@iamsdt/agent-memory-7-types-and-2-of-them-arent-memory-ab60384c8d7a?source=rss-24d4f54ea99b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab60384c8d7a</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Shudipto Trafder]]></dc:creator>
            <pubDate>Tue, 23 Jun 2026 04:52:11 GMT</pubDate>
            <atom:updated>2026-06-23T04:52:11.430Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vfffzVuIsldb6thB" /><figcaption>Photo by <a href="https://unsplash.com/@googledeepmind?utm_source=medium&amp;utm_medium=referral">Google DeepMind</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Your agent doesn’t have a memory problem. It has seven of them, and most teams have built two.</p><p>Start from the thing everyone skips past: the model itself remembers nothing. An LLM is a pure function. Same input, same output, no state carried between calls. Whatever feels like memory when you talk to ChatGPT is a layer wrapped around the model, re-sending the relevant history on every single request. The model is not remembering your last message. Something else is handing it back to the model every turn, and paying for the tokens each time.</p><p>That layer is where almost all the engineering lives, and almost all of it collapses into two patterns: a conversation history that keeps growing until you truncate it, and a vector database you call RAG. Those are two of seven distinct things an agent can remember. The catch is that they’re the two that don’t make the agent any smarter over time. The type that does, the one that turns yesterday’s mistakes into tomorrow’s rules, is the least-built component in the entire stack.</p><p>This is part one of three. Here I’ll lay out the seven types and argue about which ones actually earn the name. The taxonomy isn’t mine: it comes from cognitive science by way of the CoALA paper (Sumers et al., Princeton 2023) and Tulving’s 1972 split between episodic and semantic memory. What follows is the engineer’s version, with opinions about what to build and what to ignore.</p><h4><strong>The only axis that matters: how long it lives</strong></h4><p>Forget the seven labels for a second. There’s one organising question, and it’s temporal. Does this memory live inside the context window for a single turn, or does it persist outside the model across sessions?</p><p>Short-term is the context window. It’s fast, it’s right there, and it evaporates when the session ends. Long-term is everything you write to an external store and read back later. Two of the seven straddle the middle: their store is long-lived, but what they hand the model is used for exactly one turn and then thrown away. One type doesn’t sit in any store at all; it’s frozen into the model’s weights.</p><p>Here’s the full set, then I’ll argue about it.</p><p><strong>The seven types of agent memory</strong></p><ol><li><strong>Working</strong> (short-term) — everything in the context window right now</li><li><strong>Semantic</strong> (long-term) — facts, preferences, domain knowledge: the <em>know-what</em></li><li><strong>Episodic</strong> (long-term) — logged past events: what worked, what failed</li><li><strong>Procedural</strong> (long-term) — skills, workflows, tool patterns: the <em>know-how</em></li><li><strong>Retrieval</strong> (short + long) — knowledge pulled in by similarity search (RAG)</li><li><strong>Parametric</strong> (long-term) — knowledge baked into the model’s weights</li><li><strong>Prospective</strong> (short + long) — future intentions, scheduled to fire later</li></ol><p>Read past the table, and you’ll notice two of these don’t behave like memory at all. That’s the interesting part.</p><h4><strong>1. Working memory: where you pay the bill</strong></h4><p>Working memory is the context window: system prompt, conversation history, tool outputs, retrieved chunks, and the model’s own running reasoning. It’s the only memory the model can directly see. Every other type on this list exists to load itself into here at the right moment.</p><p>Three facts about it decide your whole architecture. It’s bounded, so you evict or summarise at the limit. It vanishes at session end. And you repay for it every turn because the entire window is resent on each call.</p><p>That last one is where the money goes, and it’s just math. A 50-turn conversation that keeps full history re-sends turn 1 fifty times. The early context isn’t expensive once; it’s expensive once per remaining turn. This is why “just use a bigger context window” is a credit card, not a solution. It works until the bill arrives, and the bill scales with the square of the conversation length.</p><p>There’s no magic in the code, just a list that goes back in full every turn:</p><pre># The whole window is re-sent on every turn. That is the bill.<br>history.append(user_msg)<br>reply = llm.invoke([system_prompt, *history])<br>history.append(reply)</pre><p>Frameworks paper over this with persisted state. A LangGraph checkpointer, for example, saves the thread so the history survives a restart. Persistence is not the same as paying less, though: the window still ships in full on every call. What you actually control is what goes into that list, which is why eviction and summarisation are the real levers.</p><p>Working memory is the convergence point for everything else here. Get it wrong, and no clever retrieval scheme downstream will save you.</p><h4><strong>2, 3, 4: the three long-term stores worth separating</strong></h4><p>These three are the heart of the system, and the useful move is to keep them distinct, because they answer different questions.</p><p><strong>Semantic memory</strong> is the <em>know-what</em>: stable facts and preferences, decoupled from when you learned them. A user is on the Enterprise plan and prefers email over phone. A client is an NRI with a moderate risk profile who won’t touch structured products. You apply that in every conversation without having to re-derive it. You build it from a structured store for the clean fields plus a vector store for the fuzzy recall, and you update profiles incrementally.</p><p>The failure mode here isn’t retrieval. It’s truth. At one user, stale facts are an annoyance. At enterprise scale, with multiple agents writing to the same profile, the hard problem is source-of-truth conflict: two agents hold contradictory versions of the same fact, and nothing arbitrates. That’s a data-governance problem wearing a memory costume, and it’s the thing that actually bites in production.</p><p><strong>Episodic memory</strong> is the log of specific past events: full runs, the decision the agent made, and whether it worked. A fraud agent records each case (the pattern it saw, what it recommended, and whether it turned out to be real fraud or a false positive), then pulls the close matches when a similar signature shows up. This is case-based reasoning. It’s how an agent stops repeating the same mistake.</p><p><strong>Procedural memory</strong> is the <em>know-how</em>: the workflows, tool-use patterns, and rules for how to do things. A claims agent’s flow is procedural: validate policy, assess the damage photos, check fraud signals, compute the payout band, route for approval above a threshold. Some of this lives in a tuned system prompt acting as the meta-controller, and some lives in an external store of decision rules. For rules, a structured key lookup beats fuzzy search every time. You don’t want “approval threshold” retrieved by cosine similarity; you want it looked up exactly.</p><pre># Rules are an exact lookup, not a similarity hit.<br>PAYOUT_BANDS = {&quot;auto&quot;: 50_000, &quot;home&quot;: 200_000}<br>threshold = PAYOUT_BANDS[claim.type]        # correct every time<br><br># not this, where &quot;close&quot; quietly becomes &quot;wrong&quot;:<br>threshold = vectors.search(f&quot;{claim.type} approval threshold&quot;)[0]</pre><p>The clean split, and the reason to keep them apart: procedural says <em>how;</em> semantic says <em>what the policy is</em>, episodic says <em>what happened</em>. Collapse them into one “memory” blob and you lose the ability to update one without corrupting the others</p><h4><strong>The one nobody builds</strong></h4><p>Here’s the part worth circling. The link between episodic and semantic memory is where learning actually happens. An agent hits the same situation a dozen times, you abstract the pattern into a rule, and you promote that rule from the episode log into semantic memory. After that, the agent doesn’t reason from twelve analogies; it applies one fact.</p><p>The loop itself is small to write, which is what makes skipping it so telling:</p><pre>similar = episodes.find(case.signature, k=20)<br>if len(similar) &gt;= 12 and they_agree(similar):<br>    rule = abstract(similar)        # &quot;auto claims with signal Y are usually false positives&quot;<br>    semantic.upsert(rule)           # promote the pattern into a durable fact<br>    episodes.mark_consolidated(similar)</pre><p>You don’t have to hand-roll all of it. LangMem and Mem0 both extract and consolidate memories from past runs instead of leaving you a raw log, and Letta (formerly MemGPT) lets the agent rewrite its own memory between turns. The tooling is catching up to the idea. Most teams still haven’t wired it in.</p><p>That loop, consolidation, is the most valuable stage in the whole system and the least implemented. Almost everyone logs episodes. Almost nobody closes the loop back into durable rules. It’s the difference between an agent with a diary and an agent that learns, and it’s the subject of part two.</p><h4><strong>5. Retrieval is not a memory type</strong></h4><p>This is where I’ll take the unpopular position. RAG isn’t a kind of memory. It’s a delivery mechanism.</p><p>The mechanics are familiar: embed the query, run a similarity search over a vector store, inject the top-k chunks into the context, and let the model answer grounded in them. A compliance bot keeps RBI and SEBI rules in a vector store and pulls only the few passages a KYC question needs. Useful, yes. But notice what’s stored there: semantic facts and episodic events. Retrieval is how those get from the store into working memory. It’s the pipe, not the water.</p><p>This matters because conflating the two is exactly why so many agents are “just a vector DB” and stop there. Once you see retrieval as plumbing, the real questions surface: what’s worth storing, how do you keep it consistent, and when is similarity the wrong access pattern entirely? It usually is for rules and exact lookups, where similarity will happily hand you the wrong threshold because it reads close to the right one.</p><p>And while we’re here: similarity is not relevance. The chunk that scores highest against your query embedding is the one that’s closest in vector space, which is not the same as the one that answers the question. The gap between those two is where most “the RAG is hallucinating” bug reports actually come from.</p><h4><strong>6. Parametric memory: the knowledge the model is</strong></h4><p>Parametric memory is everything baked into the weights at training time: grammar, arithmetic, broad world knowledge, the fact that Paris is the capital of France. The model doesn’t consult this. It <em>*is*</em> this. No retrieval step, always available, instant.</p><p>Which is exactly why it’s a trap for anything that changes. The weights are frozen between training runs. They’re opaque, they can be confidently wrong, and they know nothing past the cutoff. So the design boundary is sharp: general reasoning and language go to parametric, and anything volatile, proprietary, or recent goes to an external store.</p><p>Concretely: knowing what “loan-to-value” means is parametric, and you should trust the model for it. The current repo rate, or this specific bank’s product rules, must come from a store you control. Bake in the stuff that doesn’t move. Retrieve the stuff that does. Confusing the two is how an agent ends up quoting last year’s interest rate with total confidence.</p><h4><strong>7. Prospective memory: the one you can’t fake with a vector DB</strong></h4><p>The last type is the one that’s architecturally different from everything above. Prospective memory is remembering to act later: intentions the agent formed but hasn’t run yet. “Send the portfolio review on the 1st of every month.” “When this client’s SIP fails, alert the relationship manager.” “Review this FD maturity in September,” decided back in March.</p><p>You cannot build this with similarity search, and that’s the whole point. There’s no query to embed. It’s a task queue, a scheduler, and goal trackers that fire on a trigger, either a clock or an event. If your agent needs to do something next Monday, no amount of retrieval tuning gets you there. You need a thing that wakes up on Monday.</p><pre># A scheduler, not a vector store.<br>scheduler.add_job(send_portfolio_review, &quot;cron&quot;, day=1, args=[client.id])<br>scheduler.add_job(review_fd_maturity, &quot;date&quot;, run_date=&quot;2026-09-01&quot;, args=[fd.id])<br>events.on(&quot;sip_failed&quot;, lambda e: alert_rm(e.client_id))</pre><p>APScheduler covers the in-process case. Reach for Celery or Temporal when the intention has to survive a crash. Either way the trigger is a clock or an event, never a query.</p><p>This is the type that separates a chatbot from an agent with a horizon. Skip it, and your agent can only ever react to the message in front of it. Build it, and the agent can schedule its own future, which is most of what “agentic” actually means.</p><h4><strong>The bottom line: what to actually build</strong></h4><p>If you’re starting an agent and want to know where to spend, here’s the order I’d put it in.</p><p>Start with working memory and treat it as a budget, not a convenience. It’s the one cost that compounds, so settle your eviction and summarisation strategy before you build anything clever on top. Everything else loads in here, and you pay for it per turn.</p><p>Keep semantic, episodic, and procedural in separate stores: one for facts, one for events, one for rules and workflows. The day you can update what the agent knows without touching what it did, you’ve built something you can maintain.</p><p>Treat retrieval as plumbing. It serves the three stores above, nothing more. If your memory system is only a vector DB, you’ve built the pipe and forgotten the water.</p><p>Draw the parametric line hard. General reasoning comes from the weights; everything volatile comes from a store you own. Never let a frozen model be your source of truth for anything that has a date on it.</p><p>Add prospective memory the day your agent needs a future. A scheduler, not a vector store. It’s the cheapest type to describe, and the one most agents are missing.</p><p>And if you only do one of these well, do the consolidation loop: the promotion of repeated episodes into durable rules. Logging what happened is table stakes. Turning it into something the agent applies next time is the part almost nobody finishes, and it’s the whole reason to build memory instead of just a bigger prompt.</p><p>That handoff- how the stores read, write, and promote knowledge between each other- is the difference between an agent that answers and one that gets better at its job. Most agents shipping today are a context window and a vector DB with a good README. The seven-store version is more work, and it’s the version that learns. How those stores talk to each other is part two.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab60384c8d7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your LLM Is Lying to You Right Now — And It Always Will ]]></title>
            <link>https://medium.com/@iamsdt/your-llm-is-lying-to-you-right-now-and-it-always-will-9c0561cf7815?source=rss-24d4f54ea99b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c0561cf7815</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-hallucination]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <dc:creator><![CDATA[Shudipto Trafder]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 13:01:02 GMT</pubDate>
            <atom:updated>2026-04-20T13:01:02.642Z</atom:updated>
            <content:encoded><![CDATA[<h3>The uncomfortable truth every AI builder needs to hear before shipping to production</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*83EIe_ia0CQ_gqYA" /></figure><p><em>Photo by </em><a href="https://unsplash.com/@googledeepmind"><em>Google DeepMind</em></a><em> on Unsplash</em></p><p>Every production LLM app has a hidden error budget.</p><p>Not latency. Not uptime. Not token cost.</p><p><strong>Hallucination.</strong></p><p>Most teams treat hallucination like a temporary defect — improve the prompt, add RAG, switch to a larger model, fine-tune on better data, and eventually the problem disappears.</p><p>But the uncomfortable argument in the 2024 paper <strong>“LLMs Will Always Hallucinate, and We Need to Live With This”</strong> by Sourav Banerjee, Ayushi Agarwal, and Saloni Singla is sharper than that: hallucination is not only a product bug.</p><p><strong>It is a structural property of language models.</strong></p><p>That doesn’t mean LLMs are useless. It means we need to stop asking the wrong question.</p><blockquote><em>❌ </em>How do we eliminate hallucination?</blockquote><blockquote><em>✅ </em>Where does it happen, how often, how severe is it, and what controls reduce the blast radius?</blockquote><p>That shift matters for every LLM-based system — RAG apps, agents, internal knowledge bases, healthcare workflows, finance assistants, legal tools, and hiring platforms.</p><h3>😬 The Paper’s Uncomfortable Claim</h3><p>The paper’s core claim is simple:</p><p><strong>LLMs can reduce hallucination, but they cannot guarantee zero hallucination.</strong></p><p>The authors call this <strong>structural hallucination</strong> — hallucination that arises from the mathematical and logical structure of the system, not merely from a bad prompt or a messy dataset.</p><p>Their argument walks through the full LLM pipeline:</p><p>Stage Why hallucination can enter Training data No dataset can contain all current and future truth Retrieval Even if a fact exists, the system may not retrieve the right one Intent classification User intent is ambiguous; no model interprets every prompt perfectly Generation Token generation is probabilistic — the model can produce unsupported claims Fact-checking A verifier can reduce errors, but verifiers themselves can fail</p><p>This is the part many builders miss: <strong>hallucination is not only the moment where the model “makes something up.”</strong> It is the outcome of uncertainty accumulating across the whole system.</p><p>We already see it in production every day:</p><ul><li>🔍 The retriever returns the wrong chunk</li><li>📄 The model cites the right document but copies the wrong number</li><li>⏰ The prompt asks for “latest” information, but the knowledge source is stale</li><li>🤷 The user asks an ambiguous question, and the model confidently picks the wrong interpretation</li><li>🤖 The agent calls the wrong tool or over-explains a result it didn’t actually verify</li></ul><p>RAG, tool use, and model upgrades help. They do not create certainty.</p><h3>🏗️ Hallucination Is a Reliability Problem</h3><p>Software engineers already understand this pattern.</p><p>Distributed systems fail. Networks timeout. Databases return stale reads. We don’t respond by saying “never use databases.” We respond by designing <strong>reliability controls</strong>: retries, idempotency, observability, circuit breakers, tests, fallbacks, human escalation.</p><p>LLM systems need the same mindset.</p><p>The wrong mental model:</p><blockquote>“This model is intelligent, therefore it should always know.”</blockquote><p>The right mental model:</p><blockquote>“This system produces useful language under uncertainty — so we need measurement, guardrails, and recovery paths.”</blockquote><p>This is especially important when connecting models to tools: retrieval systems, code execution, calendars, CRMs, medical records, candidate profiles, financial data.</p><p>⚠️ <strong>An LLM that only chats can hallucinate a wrong sentence.</strong> <strong>An LLM connected to tools can hallucinate a wrong action.</strong></p><h3>🗂️ What Counts as Hallucination?</h3><p>For product evaluation, here’s the definition I use:</p><blockquote>A hallucination is any model output that is unsupported, contradicted, fabricated, or invalid relative to the available truth source, user request, or system state.</blockquote><p>That’s broader than “factually false.” It includes several distinct failure modes:</p><p>Type Example Why it matters <strong>Factual</strong> “The paper was published in 2022” (it was 2024) Wrong real-world claim <strong>Source-grounding</strong> Answer says something not in retrieved context Common in RAG apps <strong>Citation</strong> Cites a document that doesn’t support the sentence Creates false trust <strong>Numeric</strong> Reports “$19/month” instead of “$29/month” Small number, large business impact <strong>Tool</strong> Says “I sent the email” when no tool call succeeded Dangerous in agentic systems <strong>Reasoning</strong> Correct final answer, invalid intermediate steps Misleads auditors <strong>Policy</strong> Invents a company rule or medical guideline High-severity domain risk</p><p>This is why generic model leaderboards aren’t enough. A model can top benchmarks and still fail badly inside your specific workflow.</p><h3>🚫 Why “Just Add RAG” Doesn’t Solve It</h3><p>RAG is one of the best practical tools for reducing hallucination. It gives the model external context instead of relying on parametric memory.</p><p>But RAG <strong>changes</strong> the hallucination problem — it doesn’t remove it.</p><p>A RAG pipeline can fail at four places:</p><p><strong>1. Indexing failure</strong> — the right document was never added, was chunked badly, or became outdated</p><p><strong>2. Retrieval failure</strong> — the right context exists but doesn’t appear in the top-k results</p><p><strong>3. Reading failure</strong> — the right context appears, but the model ignores or misreads it</p><p><strong>4. Synthesis failure</strong> — the model combines true statements into a false or unsupported conclusion</p><p>Whether you use a cloud model or a self-hosted model, you still need evaluation. Infrastructure decisions are only one part of production AI reliability.</p><h3>📏 How to Measure Hallucination</h3><p>The key is to measure hallucination at the <strong>claim level</strong>, not only at the response level.</p><p>A response can contain ten claims. Nine may be correct, one may be fabricated — and that one may be the only claim the user acts on.</p><h3>1. Claim-Level Faithfulness</h3><p>Break the answer into atomic claims, then check each against a trusted source.</p><pre>Faithfulness = supported_claims / total_claims<br>Hallucination_rate = unsupported_or_contradicted_claims / total_claims</pre><p><strong>Example:</strong></p><p>Atomic claim Source support Label The Pro plan costs $29/month ✅ Supported Pass The Pro plan includes unlimited seats ❌ Contradicted Fail The plan launched in 2021 ⚠️ Not in source Fail</p><pre>Faithfulness = 1 / 3 = 0.33<br>Claim hallucination rate = 2 / 3 = 0.67</pre><p>This is the most important metric for RAG systems. Frameworks like RAGAS use a similar approach.</p><h3>2. Response-Level Hallucination Rate</h3><p>Sometimes you need a simpler pass/fail:</p><pre>Response hallucination rate = hallucinated_responses / total_responses</pre><p>A response counts as hallucinated if it contains at least one unsupported, contradicted, or fabricated critical claim.</p><p>Useful for dashboards and release gates — but it hides severity. A tiny unsupported adjective and a wrong medical dosage shouldn’t have the same product meaning.</p><p><strong>Use response-level rate for monitoring, claim-level and severity-weighted metrics for decisions.</strong></p><h3>3. Groundedness for RAG</h3><p>For RAG systems, track these separately:</p><p>Metric Question it answers Context recall Did retrieval find the evidence needed to answer? Context precision Were retrieved chunks actually relevant? Faithfulness / groundedness Are answer claims supported by retrieved context? Answer relevancy Did the answer address the user’s actual question? Citation precision Do citations support the exact claims they’re attached to?</p><p>This separation matters because a hallucinated answer can come from different causes:</p><ul><li>Low context recall → <strong>retrieval failed</strong></li><li>High recall but low faithfulness → <strong>generation failed</strong></li><li>High faithfulness but low relevancy → <strong>model answered the wrong question</strong></li></ul><p>Each failure needs a different fix.</p><h3>4. Consistency Sampling</h3><p>SelfCheckGPT introduced a simple but powerful idea:</p><blockquote>If a model knows a fact, multiple sampled answers tend to agree. If it’s hallucinating, they diverge.</blockquote><p>The workflow:</p><ol><li>Ask the same question multiple times with non-zero temperature</li><li>Extract claims from each answer</li><li>Compare whether claims agree or contradict each other</li><li>Flag unstable claims for verification</li></ol><p>This doesn’t prove truth — many answers can agree and still be wrong. But inconsistency is a useful warning signal.</p><h3>5. Severity-Weighted Hallucination 🚨</h3><p>Not all hallucinations are equal.</p><p>Severity Meaning Example <strong>P0</strong> Could cause harm, legal exposure, financial loss, or irreversible action Wrong dosage, wrong legal deadline <strong>P1</strong> Materially changes a user decision Wrong price, wrong eligibility rule <strong>P2</strong> User-visible factual error with limited damage Wrong date in a summary <strong>P3</strong> Minor unsupported flourish “This is widely popular” without evidence</p><pre>Severity_score =<br>  (P0_count × 100 + P1_count × 20 + P2_count × 5 + P3_count × 1)<br>  / total_responses</pre><p>A system with 8% harmless P3 errors may be fine for brainstorming.</p><p>A system with 0.5% P0 errors is unacceptable for healthcare, legal, or finance.</p><h3>📊 A Practical Hallucination Evaluation Sheet</h3><p>Track this table per model version, prompt version, retriever version, and dataset version:</p><p>Metric Formula Good for Claim faithfulness supported / total claims RAG and factual generation Unsupported claim rate unsupported / total claims Open-ended answers Contradiction rate contradicted / total claims Source-sensitive workflows Response hallucination rate failed / total responses Release dashboards Citation precision valid citations / total citations Document Q&amp;A Context recall questions with evidence retrieved / total Retriever quality Answer correctness correct / total answers QA and support bots Abstention accuracy correct refusals / questions requiring refusal Safety Tool action validity valid tool calls / total tool calls Agents Severity score weighted hallucinations / total responses Product risk</p><p>This turns hallucination from a vague complaint into an engineering metric.</p><h3>🛠️ The Evaluation Pipeline</h3><ol><li><strong>Collect real prompts</strong> from production, sales demos, internal testing, and edge cases</li><li><strong>Create gold references</strong> using trusted documents, databases, or expert-written answers</li><li><strong>Run the same prompts</strong> across model versions, prompt versions, retrievers, and temperatures</li><li><strong>Extract atomic claims</strong> from each answer</li><li><strong>Label each claim</strong> as supported, contradicted, unsupported, irrelevant, or unverifiable</li><li><strong>Assign severity</strong> to each failed claim</li><li><strong>Track metrics over time</strong> in CI or an eval dashboard</li><li><strong>Block releases</strong> when P0/P1 errors increase — even if average score improves</li></ol><p>For a small team, start with <strong>100 high-value questions</strong>.</p><p>For a serious production system, maintain <strong>500–2,000 test cases</strong> across:</p><ul><li>✅ Normal user questions</li><li>❓ Ambiguous questions</li><li>🧨 Adversarial prompts</li><li>📅 Fresh or time-sensitive facts</li><li>🔢 Numeric and policy-heavy questions</li><li>🔗 Multi-hop questions</li><li>🤐 Questions where the correct answer is <em>“I don’t know”</em></li></ul><p><strong>That last category is critical.</strong> A model that never admits uncertainty will look helpful during demos and dangerous during deployment.</p><h3>🎯 What Good Targets Look Like</h3><p>Targets depend on the domain.</p><p>For an <strong>internal document Q&amp;A bot</strong>, I’d start here:</p><p>Metric Target Claim faithfulness ≥ 0.90 Citation precision ≥ 0.90 Context recall ≥ 0.85 P0 hallucinations <strong>0</strong> P1 hallucinations &lt; 1%</p><p>For <strong>healthcare, legal, finance, compliance, or hiring</strong>:</p><ul><li>No autonomous high-impact decisions</li><li>Mandatory source display</li><li>Human review for P0/P1 workflows</li><li>Tool calls logged and auditable</li><li>The model must be allowed to abstain</li></ul><p>This is the difference between using LLMs as <strong>assistants</strong> and pretending they are <strong>authorities</strong>.</p><h3>🔧 How to Reduce Hallucination After Measuring It</h3><p>Once you know <em>where</em> hallucination happens, the mitigation becomes clearer.</p><p><strong>If retrieval fails →</strong> Improve chunking, add metadata filters, use hybrid search, add reranking, monitor context recall</p><p><strong>If generation ignores evidence →</strong> Force answers to cite source spans, add “answer only from provided context” constraints, use structured output, reduce temperature for factual tasks</p><p><strong>If numbers drift →</strong> Extract numbers with deterministic code, use tools for calculation, validate units/dates/prices/IDs, prefer database reads over model memory</p><p><strong>If citations are fake →</strong> Generate citations from retrieved document IDs (not free-form model text), check each citation against the claim</p><p><strong>If the domain is high-stakes →</strong> Add human approval, log every model input/context/output/tool call, separate drafting from decision-making</p><p>This connects directly to the paper’s main implication: <strong>hallucination is not removed by one clever trick. It is managed through layered controls.</strong></p><h3>🏁 The Bottom Line</h3><p>The paper isn’t saying “don’t use LLMs.”</p><p>It’s saying something more useful:</p><blockquote><strong><em>Don’t build LLM systems on the fantasy of perfect truthfulness.</em></strong></blockquote><p>LLMs will always have some non-zero probability of hallucination. Uncertainty enters through training data, retrieval, intent interpretation, generation, and verification. That’s not a reason to abandon them — it’s a reason to <strong>engineer around them</strong>.</p><p>The production question isn’t:</p><blockquote>Can this model hallucinate?</blockquote><p>It can.</p><p>The real questions are:</p><blockquote><strong><em>What is the hallucination rate?</em></strong><em> </em><strong><em>Which claims are unsupported?</em></strong><em> </em><strong><em>Which failures are severe?</em></strong><em> </em><strong><em>Which part of the system caused them?</em></strong><em> </em><strong><em>What guardrail catches them before the user acts?</em></strong></blockquote><p>That’s how we move from LLM demos to reliable AI products.</p><p>We don’t need hallucination-free models to build useful systems.</p><p><strong>We need measured, monitored, source-grounded systems that know when to answer, when to cite, when to call a tool — and when to say: <em>“I don’t know.”</em></strong></p><h3>References</h3><ul><li>Sourav Banerjee, Ayushi Agarwal, Saloni Singla — <a href="https://arxiv.org/abs/2409.05746">“LLMs Will Always Hallucinate, and We Need to Live With This”</a>, arXiv, September 2024</li><li>Junyi Li et al. — <a href="https://aclanthology.org/2023.emnlp-main.397/">“HaluEval: A Large-Scale Hallucination Evaluation Benchmark”</a>, EMNLP 2023</li><li>Stephanie Lin, Jacob Hilton, Owain Evans — <a href="https://openai.com/index/truthfulqa/">“TruthfulQA: Measuring How Models Mimic Human Falsehoods”</a>, 2021</li><li>Potsawee Manakul et al. — <a href="https://arxiv.org/abs/2303.08896">“SelfCheckGPT: Zero-Resource Black-Box Hallucination Detection”</a>, EMNLP 2023</li><li>RAGAS — <a href="https://docs.ragas.io/en/v0.3.3/concepts/metrics/available_metrics/faithfulness/">“Faithfulness metric documentation”</a></li><li>Sebastian Farquhar et al. — <a href="https://www.nature.com/articles/s41586-024-07421-0">“Detecting hallucinations using semantic entropy”</a>, Nature 2024</li></ul><p><em>If this helped you think more clearly about production AI reliability, consider sharing it with your team. Building honest systems starts with honest expectations.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c0561cf7815" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TOON for LLMs: A Comparative Performance Analysis against JSON]]></title>
            <link>https://medium.com/@iamsdt/toon-for-llms-a-comparative-performance-analysis-against-json-a3f8745658ec?source=rss-24d4f54ea99b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3f8745658ec</guid>
            <category><![CDATA[toon]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[gemini]]></category>
            <dc:creator><![CDATA[Shudipto Trafder]]></dc:creator>
            <pubDate>Sat, 20 Dec 2025 16:37:13 GMT</pubDate>
            <atom:updated>2025-12-20T16:37:13.032Z</atom:updated>
            <content:encoded><![CDATA[<p>Every API call you make with JSON is costing you more than you think.</p><p>I ran real-world extractions using Gemini 2.5 Flash, and the results were startling: <strong>JSON consistently used 30–40% more output tokens</strong> than TOON format. In one test, JSON consumed 471 output tokens while TOON used just 227 — <strong>a 51% reduction</strong>.</p><p>But here’s where it gets interesting: TOON initially failed 70% of the time.</p><p>After optimization, I achieved 100% parsing success <em>and</em> discovered something counterintuitive — it uses more prompt tokens, with TOON actually saves you money overall. When I tested structured outputs with Pydantic models, JSON required 389 output tokens versus TOON’s simpler encoding.</p><p><strong>The hidden goldmine?</strong> Tool/function calling. That’s where TOON’s compact format shines brightest, slashing token costs in agentic workflows where responses become the next prompt.</p><p>This isn’t theoretical. I’m sharing the actual prompts, parsing errors, token counts, and code that took TOON from a 70% failure rate to production-ready. Whether TOON beats JSON depends on your use case — and I have the data to prove exactly when.</p><p>Let’s break down the numbers.</p><h3>Experiment #1: The Initial TOON Failure (70% Success Rate)</h3><p>I started with what seemed like a straightforward test: extracting structured job description data using TOON instead of JSON.</p><p><strong>The Setup:</strong></p><p>My prompt was simple — ask Gemini 2.5 Flash to extract role, skills, experience, location, and responsibilities from a job posting. For the output format, I did what seemed logical: <strong>I showed TOON’s encoded structure using the actual output format</strong> (essentially a drop-in replacement approach).</p><pre>Extract Role, Primary Skills, Secondary Skills,<br>Minimum Experience, Maximum Experience,<br>Location, Employment Type, Summary, and Responsibilities<br><br>Job Description:<br>```<br>&lt;JD Text&gt;<br>```</pre><p>Output in TOON format:</p><pre>Role: &quot;&quot;<br>&quot;Primary Skills&quot;[2]: Python,JavaScript<br>&quot;Secondary Skills&quot;[2]: Responsibility,Communication<br>&quot;Minimum Experience&quot;: &quot;&quot;<br>&quot;Maximum Experience&quot;: &quot;&quot;<br>Location: &quot;&quot;<br>&quot;Employment Type&quot;: &quot;&quot;<br>Summary: &quot;&quot;<br>Responsibilities[2]: Task A,Task B</pre><p><strong>Here&#39;s what I suspected would work:</strong> By showing the encoded format with empty strings and generic placeholders, the model would understand the structure.</p><ul><li>Reality check: 70% failure rate.</li><li>The errors were telling:</li></ul><pre>Error parsing TOON format for JD#2: Expected 10 values, but got 16 <br>Error parsing TOON format for JD#5: Missing colon after key</pre><p>The model was confused about arrays. Sometimes it outputs</p><p><em>Skills: Python, JavaScript, React</em> as a flat string. Other times, it attempted brackets but malformed the syntax.</p><p><strong>The hypothesis:</strong> Maybe showing encoded/empty examples was the problem. The model needed to see <strong>real data patterns</strong>, especially for arrays.</p><p><strong>Token Usage (Failed Attempts, 70% Success Rate)</strong>:</p><ul><li>Prompt: 729 tokens</li><li>Output: 227 tokens</li><li>Success Rate: ~30% initially, improved to 70% after adding two real examples with populated arrays</li></ul><p><strong>Json Token Usages:</strong></p><ul><li>Prompt: 723 tokens</li><li>Output: 471tokens</li></ul><p><strong>Key Insight:</strong></p><ul><li>TOON&#39;s compact syntax is unforgiving. JSON has redundancy (<em>{&quot;key&quot;: &quot;value&quot;}</em>) that helps models self-correct. TOON&#39;s <em>Key: value</em> format offers no such safety net. <strong>The model needed concrete examples, not abstract templates.</strong></li></ul><p>But 70% wasn&#39;t good enough for production. Time to fix this properly.</p><h3>Experiment #2: Achieving 100% Parsing Success (And the Token Trade-off)</h3><p>I needed to fix the 70% success rate. The solution? <strong>Stop being minimalist with examples.</strong></p><p>Instead of showing encoded/empty structures, I gave the model a <strong>complete, realistic example</strong> with proper TOON formatting — especially for arrays.</p><p><strong>The Revised Prompt:</strong></p><pre>Extract Role, Primary Skills, Secondary Skills,<br>Minimum Experience, Maximum Experience,<br>Location, Employment Type, Summary, and Responsibilities<br><br>Job Description:<br>```<br>&lt;JD Text&gt;<br>```<br><br>Output in TOON format. Example structure:<br>```<br>Role: &quot;Senior Data Scientist&quot;<br>Primary_Skills:<br> [0]: &quot;Python&quot;<br> [1]: &quot;Machine Learning&quot;<br> [2]: &quot;Statistical Analysis&quot;<br>Secondary_Skills:<br> [0]: &quot;Big Data&quot;<br> [1]: &quot;Cloud Platforms&quot;<br>Minimum_Experience: &quot;5 years&quot;<br>Maximum_Experience: &quot;10 years&quot;<br>Location: &quot;New York, NY or Remote&quot;<br>Employment_Type: &quot;Full-time&quot;<br>Summary: &quot;Lead data science initiatives&quot;<br>Responsibilities:<br> [0]: &quot;Design ML models&quot;<br> [1]: &quot;Analyze datasets&quot;<br><br>```<br><br>Now provide the extraction in TOON format. Keep the format exactly<br>as shown above.</pre><p><strong>Result</strong>: <strong>100% parsing.</strong> No more malformed arrays. No more missing colons.</p><p>But here&#39;s the catch—<strong>the prompt got heavier</strong>.</p><h4>The Token Comparison: TOON vs JSON</h4><p>Let me show you the actual numbers across the same 10 job descriptions:</p><p><strong>JSON Approach: </strong>Token Usage</p><ul><li>Prompt tokens: 723</li><li>Output tokens: 471</li><li>Success rate: 100% (JSON is forgiving)</li></ul><h4>TOON Approach (Initial — 70% success)</h4><p><strong>Token Usage:</strong></p><ul><li><strong>Prompt tokens: 729</strong></li><li><strong>Output tokens: 227</strong> ✅ <strong>(51.8% reduction vs JSON)</strong></li><li><strong>Total: 956 tokens</strong> (saves 238 tokens per request)</li><li><strong>Success rate: 70%</strong> ❌</li></ul><h4>TOON Approach (Optimized — 100% success)</h4><p><strong>Token Usage:</strong></p><ul><li><strong>Prompt tokens: 802</strong> ❌ <strong>(+11% vs JSON)</strong></li><li><strong>Output tokens: 455</strong> ✅ <strong>(3.4% reduction vs JSON)</strong></li><li><strong>Success rate: 100%</strong> ✅</li></ul><h4>The Uncomfortable Truth</h4><p><strong>For basic extraction tasks, optimized TOON costs MORE than JSON.</strong></p><p>Yes, the output is slightly more compact (455 vs 471 tokens), but the verbose prompting needed to achieve 100% reliability completely erases any savings. In fact, you’re paying <strong>5% more per request</strong>.</p><p><strong>So why am I still testing TOON?</strong></p><p>Because this experiment revealed something crucial: <strong>the baseline comparison is misleading.</strong> Real-world LLM applications don’t just extract data once — they use structured outputs for:</p><ol><li><strong>Pydantic model validation</strong> (native SDK support)</li><li><strong>Tool/function calling</strong> (where output becomes input)</li><li><strong>Multi-turn agentic workflows</strong> (repeated serialization)</li></ol><p>That’s where the math changes completely. Let me show you.</p><h3>Experiment #3: Pydantic Models — Where the SDK Does the Heavy Lifting</h3><p>Here’s where things get interesting. Modern LLM SDKs have <strong>first-class support for structured outputs</strong> using Pydantic models. Instead of prompt engineering, you define a schema and let the SDK handle formatting.</p><p><strong>The key difference:</strong> You don’t need to explain the output format in your prompt — the SDK extracts it from your Pydantic model automatically.</p><h3>The Setup: Google’s GenAI SDK</h3><p>I used the same job extraction task, but this time with a Pydantic model:</p><pre>response = client.models.generate_content(<br> model=&quot;gemini-2.5-flash&quot;,<br> contents=prompt,<br> config={<br>  &quot;response_mime_type&quot;: &quot;application/json&quot;,<br>  &quot;response_schema&quot;: JobModel,<br> },<br>)</pre><p><strong>Notice what’s missing:</strong> No output format instructions. No examples. No “Output as JSON with these exact keys.”</p><p>The SDK injects the schema behind the scenes.</p><h4>Token Comparison: Pydantic JSON vs Manual TOON</h4><h4>Pydantic + JSON (SDK-Managed)</h4><p><strong>Token Usage:</strong></p><ul><li><strong>Prompt tokens: 647</strong> ✅ <strong>(19.3% less than optimized TOON)</strong></li><li><strong>Output tokens: 389</strong> ✅ <strong>(14.5% less than optimized TOON)</strong></li><li><strong>Success rate: 100%</strong> ✅</li><li><strong>Parsing: Native</strong> (SDK returns typed Python objects)</li></ul><h4>Manual TOON (From Experiment #2)</h4><p><strong>Token Usage:</strong></p><ul><li><strong>Prompt tokens: 802</strong> ❌</li><li><strong>Output tokens: 455</strong> ❌</li><li><strong>Success rate: 100%</strong> ✅</li><li><strong>Parsing: Custom</strong> (you write the parser)</li></ul><h4>The Brutal Takeaway</h4><p>For structured extraction with strong SDK support, <strong>Pydantic really shines</strong>. Native Pydantic integration delivers:</p><ul><li>✅ Cleaner prompts (<strong>~155 fewer prompt tokens</strong>)</li><li>✅ Smaller outputs (<strong>~66 fewer output tokens</strong>)</li><li>✅ No custom parsing logic</li><li>✅ Built-in type validation</li><li>✅ Parsed objects returned directly, ready to use</li><li>✅ A much smoother developer experience</li></ul><p>Because of this, I’ll increasingly rely on <strong>Pydantic and native parsing support</strong> for structured extraction. It’s simply more reliable and maintainable than handling parsing and validation manually.</p><p>That said, there’s one scenario where JSON’s verbosity becomes a genuine liability: <strong>tool calling in agentic workflows</strong>.<br> <strong>That’s where TOON finally proves its worth.</strong></p><h3>Experiment #4: Tool Calling — Where TOON Finally Wins</h3><p>This is where everything clicked.</p><p>In agentic workflows, your LLM doesn’t just extract data once — it <strong>calls tools, receives results, and uses those results to reason further.</strong> The tool’s response becomes part of the next prompt. And if that response is bloated with JSON syntax, you’re paying for it twice: once as output, once as input.</p><p><strong>The insight:</strong> Tool results are pure token waste. The model doesn’t need {&quot;key&quot;: &quot;value&quot;} ceremony—it needs the data, efficiently encoded.</p><h4>The Setup: Weather Agent with Function Calling</h4><p>I built a simple agent that calls a get_current_weather function. The user asks for weather, the model calls the tool, the function returns data, and the model synthesizes a response.</p><p><strong>The critical moment:</strong> What format should get_current_weather return?</p><h4>Version A: JSON Tool Response</h4><pre>data = {<br>        &quot;location&quot;: location,<br>        &quot;current&quot;: {<br>            &quot;temperature&quot;: &quot;72 F&quot;,<br>            &quot;condition&quot;: &quot;sunny&quot;,<br>        },<br>        &quot;forecast&quot;: forecast,<br>    }<br>    <br>    return json.dumps(data)  # Returns JSON string</pre><h4>Version B: TOON Tool Response</h4><pre>data = {<br>        &quot;location&quot;: location,<br>        &quot;current&quot;: {<br>            &quot;temperature&quot;: &quot;72 F&quot;,<br>            &quot;condition&quot;: &quot;sunny&quot;,<br>        },<br>        &quot;forecast&quot;: forecast,<br>    }<br>    <br>    return encode(data)  # Returns TOON-encoded string</pre><p>Main code</p><pre>response = client.models.generate_content(<br>    model=&quot;gemini-2.5-flash&quot;,<br>    contents=&quot;What is the weather like in New York? Share next 15 days forecast as well.&quot;,<br>    config=types.GenerateContentConfig(<br>        tools=[get_current_weather],<br>    ),<br>)</pre><h4>Result <strong>Token Usage:</strong></h4><ul><li><strong>Initial prompt tokens: 152</strong> (user message + tool definition)</li><li><strong>Tool response tokens (becomes input): 480</strong> ✅ <strong>(24% reduction)</strong></li><li><strong>Model’s final output: 384</strong> (slightly longer, but reasonable)</li><li><strong>Total tokens: 1,016</strong> ✅ <strong>(11.5% reduction overall)</strong></li></ul><h4>Why TOON Wins in Agentic Workflows</h4><p>Here’s the math that matters:</p><p><strong>Single Tool Call</strong></p><ul><li><strong>JSON approach:</strong> 632 tokens for tool result</li><li><strong>TOON approach:</strong> 480 tokens for tool result</li><li><strong>Savings: 152 tokens per tool call (24%)</strong></li></ul><h4>Multi-Turn Agent (5 tool calls)</h4><ul><li><strong>JSON approach:</strong> 632 × 5 = <strong>3,160 tokens</strong> in tool results</li><li><strong>TOON approach:</strong> 480 × 5 = <strong>2,400 tokens</strong> in tool results</li><li><strong>Savings: 760 tokens (24%)</strong></li></ul><h4>The Compounding Effect</h4><p><strong>Why this matters more than single extractions:</strong></p><ol><li><strong>Tool results are pure input tokens</strong> — You pay for them every single time</li><li><strong>Verbosity multiplies</strong> — JSON’s {}: , Syntax adds 20-30% overhead for nested data</li><li><strong>No parsing penalty</strong> — The model consumes TOON just as easily (we verified this in follow-up tests)</li><li><strong>Scales with agent complexity</strong> — More tools = more savings</li></ol><p>The difference? <strong>Where the efficiency matters.</strong></p><h3>The Bottom Line</h3><p>After this test runs across four different scenarios, here’s what the data tells us:</p><p><strong>TOON loses at single extractions.</strong> Whether you’re doing manual prompting or using Pydantic models, JSON with SDK support is cleaner, cheaper, and more reliable. The 17.6% token savings from native schema integration beats TOON’s manual approach every time.</p><p><strong>But TOON wins where it counts for agents:</strong> tool calling workflows.</p><p>When your LLM’s output becomes the next prompt — when data cycles between model and functions repeatedly — TOON’s 24% reduction per tool call transforms from interesting to impactful. An agent making 20 tool calls saves 3,040 tokens per session.</p><p><strong>The decision matrix is simple:</strong></p><p>Building a chatbot that extracts structured data? <strong>Use JSON + Pydantic.</strong><br> Building an agent that calls tools 10+ times per session? <strong>Test TOON.</strong><br> Building anything else? <strong>Profile first, optimize later.</strong></p><h3>Try It Yourself</h3><p>I’ve open-sourced all the experiments, prompts, and token measurements: <a href="https://gist.github.com/Iamsdt/d0e036d400556f567a21b2a7f3113dfd"><strong>View complete code and results on GitHub Gist</strong></a></p><p>The repository includes:</p><ul><li>✅ All four experiment setups with actual prompts</li><li>✅ Token usage logs for every test case</li><li>✅ Side-by-side comparison scripts</li><li>✅ The job descriptions I used for testing</li></ul><p><strong>TOON isn’t magic — it’s math.</strong> And the math only works when token efficiency genuinely matters. For most applications, JSON’s ecosystem advantages outweigh the savings. But for token-heavy agentic workflows? TOON might just pay for itself.</p><p>Now you have the data to decide.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3f8745658ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[InjectQ: The Modern Python Dependency Injection Library]]></title>
            <link>https://medium.com/@iamsdt/injectq-the-modern-python-dependency-injection-library-8f6ad6cdb600?source=rss-24d4f54ea99b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f6ad6cdb600</guid>
            <category><![CDATA[taskiq]]></category>
            <category><![CDATA[id]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[fastapi]]></category>
            <dc:creator><![CDATA[Shudipto Trafder]]></dc:creator>
            <pubDate>Wed, 03 Dec 2025 10:03:34 GMT</pubDate>
            <atom:updated>2025-12-03T10:03:34.107Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>The Pain of Python Apps (And How InjectQ Fixes It)</strong></p><p>Ever built a Python app that started simple but turned into a complex web of dependencies? Where changing one component breaks everything? Where does testing become cumbersome?</p><p>You’re not alone. Most Python developers encounter the challenge of <strong>tight coupling, hard-to-test code, and dependency management issues</strong>.</p><p>Traditional DI libraries? Often verbose. Complex to set up. Not optimised for modern async Python.</p><p><strong>Enter InjectQ</strong> — a lightweight, powerful dependency injection library that feels intuitive. It’s as simple as a dictionary, yet as capable as enterprise frameworks, designed for contemporary Python development.</p><p>Ready to transform your code? Let’s explore.</p><p><strong>5-Minute Setup: Get InjectQ Running Now</strong></p><pre>pip install injectq</pre><p><strong>Your First App</strong></p><pre>from injectq import InjectQ, inject, singleton<br><br>container = InjectQ.get_instance()<br><br>@singleton<br>class Database:<br>    def __init__(self):<br>        print(&quot;DB connected!&quot;)<br><br>@singleton<br>class UserService:<br>    def __init__(self, db: Database):<br>        self.db = db<br><br>    def get_user(self, id: int):<br>        return {&quot;id&quot;: id, &quot;name&quot;: &quot;Alice&quot;}<br><br>@inject<br>def main(service: UserService):<br>    user = service.get_user(1)<br>    print(user)<br><br>main()  # Dependencies injected automatically.</pre><p><strong>Output:</strong></p><pre>DB connected!<br>{&#39;id&#39;: 1, &#39;name&#39;: &#39;Alice&#39;}</pre><p>That’s it. No manual wiring. No boilerplate. Just clean, testable code.</p><p><strong>Why InjectQ Excels: The Key Features</strong></p><p><strong>1. Dict-Simple Interface</strong></p><p>InjectQ’s dictionary-like interface makes dependency management intuitive and straightforward. You can register simple values, classes, or instances effortlessly using familiar syntax, then access them instantly with automatic dependency resolution and instantiation. This approach is perfect for quick prototyping, configuration management, and applications where simplicity is key.</p><pre>injectq = InjectQ.get_instance()<br>injectq[str] = &quot;Hello World&quot;<br>injectq[Database] = Database<br><br>message = injectq[str]  # Instant access<br>db = injectq[Database]  # Auto-instantiated</pre><p><strong>2. <em>@inject</em> Magic</strong></p><p>The <em>@inject</em> decorator transforms how you write functions by enabling automatic dependency injection. Simply decorate any function — sync or async — and InjectQ will resolve dependencies based on type hints, eliminating the need for manual parameter passing. This feature works seamlessly across class methods, static methods, and standalone functions, making your code cleaner and more maintainable.</p><pre>@inject<br>def process_user(user_id: int, service: UserService):<br>    return service.get_user(user_id)<br><br># Call without args - InjectQ handles it<br>result = process_user(123)</pre><p><strong>3. Lazy Injection with Inject[T]</strong></p><p>For scenarios requiring conditional or optional dependencies, InjectQ offers lazy injection through the <em>Inject[T]</em> marker. This creates a proxy that defers resolution until first access, reducing startup time and improving performance. It integrates seamlessly with default parameters, allowing you to mix injected and manual arguments without complexity.</p><pre>from injectq import Inject<br><br>def handle_request(data: dict, service: UserService = Inject[UserService]):<br>    # service resolves only when used<br>    return service.get_user(data[&#39;id&#39;])</pre><p><strong>4. Factory Powerhouse</strong></p><p>InjectQ’s factory support enables complex object creation with runtime parameters, combining the best of dependency injection and manual arguments. Bind factory functions that receive auto-injected dependencies alongside custom parameters, perfect for dynamic scenarios like per-user handlers or request-specific objects. The <em>invoke()</em> method makes calling these factories intuitive and powerful.</p><pre>def create_handler(db: Database, user_id: str):<br>    return UserHandler(db, user_id)<br><br>container.bind_factory(&quot;handler&quot;, create_factory)<br><br># Mix auto-injected + manual args<br>handler = container.invoke(&quot;handler&quot;, user_id=&quot;alice&quot;)</pre><p><strong>5. Scope Control</strong></p><p>Control object lifecycles precisely with InjectQ’s scope decorators. @singleton ensures one instance for the entire application, ideal for shared resources like database pools. <em>@scoped(“request”)</em> provides isolation per context, such as HTTP requests, while <em>@transient</em> creates new instances every time. This granular control ensures proper resource management and prevents unintended sharing.</p><pre>@singleton  # One instance forever<br>class DatabasePool: pass<br><br>@scoped(&quot;request&quot;)  # One per request<br>class RequestContext: pass<br><br>@transient  # New every time<br>class Validator: pass</pre><p><strong>6. Async-First Design</strong></p><p>Built for modern Python, InjectQ embraces async/await patterns natively. From async factories and scopes to resolution methods, everything works seamlessly with coroutines. This design optimizes for high-performance async applications, providing the same intuitive experience whether you’re working with synchronous or asynchronous code.</p><pre>@inject<br>async def async_task(service: AsyncService):<br>    return await service.process()<br><br>result = await async_task()  # Seamless async injection</pre><h4><strong>Framework Integrations: Plug-and-Play</strong></h4><p><strong>FastAPI</strong></p><p>InjectQ integrates seamlessly with FastAPI, enabling type-safe dependency injection in your API routes. Use the <em>InjectFastAPI</em> marker to inject services directly into endpoint functions, with automatic request-scoped isolation for clean, testable web applications.</p><pre>from injectq.integrations.fastapi import InjectFastAPI, setup_fastapi<br><br>app = FastAPI()<br>container = InjectQ.get_instance()<br>setup_fastapi(container, app)<br><br>@app.get(&quot;/users/{id}&quot;)<br>async def get_user(id: str, service: Annotated[UserService, InjectFastAPI(UserService)]):<br>    return service.get_user(id)</pre><p><strong>Taskiq (Background Jobs)</strong></p><p>For background task processing, InjectQ pairs perfectly with Taskiq. Inject dependencies into your task functions using the <em>InjectTaskiq</em> marker, ensuring consistent service access across async job execution.</p><pre>from injectq.integrations.taskiq import InjectTaskiq, setup_taskiq<br><br>broker = InMemoryBroker()<br>setup_taskiq(container, broker)<br><br>@broker.task<br>async def process_job(order_id: int, service: Annotated[OrderService, InjectTaskiq(OrderService)]):<br>    return service.process(order_id)</pre><p><strong>Performance That Impresses</strong></p><p>InjectQ is <strong>fast</strong>. Exceptionally fast.</p><ul><li><strong>Resolution</strong>: 1 microsecond (even for deep dependency trees)</li><li><strong>Web requests</strong>: 142 microseconds for 10 services</li><li><strong>Throughput</strong>: 7,000+ requests/second just for DI</li></ul><p>Thread-safe by default. No locks needed in your code. Check the Benchmark <a href="https://github.com/10xHub/injectq/blob/main/reports/BENCHMARK_REPORT.md">Report</a>.</p><p><strong>Why Developers Choose InjectQ</strong></p><ul><li><strong>Simple</strong>: Dict-like API for quick starts</li><li><strong>Powerful</strong>: Hybrid factories, scopes, async support</li><li><strong>Type-Safe</strong>: Full mypy support</li><li><strong>Modern</strong>: Async-first, thread-safe</li><li><strong>Fast</strong>: Sub-microsecond operations</li><li><strong>Integrated</strong>: FastAPI, Taskiq ready</li></ul><p>Whether you’re building a script or enterprise app, InjectQ scales with you.</p><p><strong>Get Started Today</strong></p><pre>pip install injectq</pre><p>Dive into the docs: <a href="https://10xhub.github.io/injectq/">10xhub.github.io/injectq</a></p><p>Star the repo: <a href="https://github.com/10xHub/injectq">InjectQ</a></p><p>Ready to write cleaner, faster Python code? InjectQ awaits.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f6ad6cdb600" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Tensorboard in Google Colab with PyTorch]]></title>
            <link>https://medium.com/@iamsdt/using-tensorboard-in-google-colab-with-pytorch-458f9bb95212?source=rss-24d4f54ea99b------2</link>
            <guid isPermaLink="false">https://medium.com/p/458f9bb95212</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[tensorboard]]></category>
            <category><![CDATA[google-colab]]></category>
            <dc:creator><![CDATA[Shudipto Trafder]]></dc:creator>
            <pubDate>Thu, 08 Aug 2019 06:46:59 GMT</pubDate>
            <atom:updated>2020-03-04T13:28:15.891Z</atom:updated>
            <content:encoded><![CDATA[<p>TensorBoard a visualization toolkit for machine learning.</p><figure><img alt="TensorBoard @ Google" src="https://cdn-images-1.medium.com/max/800/1*1e6feu4blFUBJTQCQ9XM9Q.gif" /><figcaption>TensorBoard (Credit: official TensorFlow site)</figcaption></figure><p>By using TensorBoard</p><ul><li>Track and visualize loss and accuracy with graph</li><li>Visualize model graph</li><li>View histogram of tensor and tack changes<br>And so on</li></ul><p>This article is not about tensorboard tutorial. It is about how to use tensorboard in google colab including available methods.</p><p>If you want to learn more about Tensorboard See this video <a href="https://www.youtube.com/watch?v=eBbEDRsCmv4">Hands-on TensorBoard (TensorFlow Dev Summit 2017)</a></p><h3>Now PyTorch</h3><p>Though TensorBoard is a visualization library for TensorFlow and it is useful in understanding training runs, tensors, and graphs. But we can still use it for PyTorch. Before official support, there have some 3rd party libraries available such <a href="https://github.com/lanpa/tensorboardX.">tensorboardX</a>.<br>But Now TensorBoard supports <strong>officially</strong>…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5hbPgIVpj3r33Ucf" /><figcaption>Photo by <a href="https://unsplash.com/@erwanhesry?utm_source=medium&amp;utm_medium=referral">Erwan Hesry</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This is available under <strong>torch.utils.tensorboard</strong> package</p><p>If you want to know more check the d<a href="https://pytorch.org/docs/stable/tensorboard.html">ocumentation of tensorboard for PyTorch</a></p><h3>Use in Google Colab</h3><p>If you want to use tensorboard in google colab, there are so many available methods. But here is just only top 2</p><ul><li>TensorBoard notebook extension</li><li>ngrok</li></ul><p>you can also use this 3rd party library <a href="https://github.com/taomanwai/tensorboardcolab">TensorbardColab</a></p><p>Let&#39;s dig in those methods</p><h3>TensorBoard notebook extension</h3><p>Install TensorBoard notebook extension</p><pre>!pip install -q tf-nightly-2.0-preview<br>%load_ext tensorboard #Load extension</pre><p>Now create a directory for logs</p><pre>import os<br>logs_base_dir = &quot;runs&quot;<br>os.makedirs(logs_base_dir, exist_ok=True)</pre><p>We are ready to go. when you want to launch tensorboard use this command</p><pre>%tensorboard --logdir {logs_base_dir}</pre><p>Before launching write some write something on tensorboard by using SummaryWriter. For instance model graph and images, and dummy scaler value</p><pre>from torch.utils.tensorboard import SummaryWriter<br># load data from loader<br>images, labels = next(iter(train_loader))</pre><pre>tb = SummaryWriter()<br>tb.add_images(&quot;Image&quot;, images)<br>tb.add_graph(model, images)<br>for i in range(1, 20):<br>    tb.add_scalar(&quot;Tag&quot;, 10/i, i)</pre><pre>tb.close()</pre><p>Now use the magic command to launch Tensorboard</p><pre>%tensorboard --logdir {logs_base_dir}</pre><p>And the output looks like this</p><figure><img alt="Tensorboard output" src="https://cdn-images-1.medium.com/max/1024/1*MeKnhCNRffIInTkAtyRNWA.png" /></figure><p>Now switch the tab and play with tensorboard</p><p>This is a pretty easy method, but the problem of this method is the tensorboard will open inside the cell output. In my point of view, I don’t like this type of output option. I feel like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*C0Crubgx3PfWzx7-" /><figcaption>Credit: goodhousekeeping.com</figcaption></figure><p>If you feel like me, then jump into the second method, but this time it will generate a link, by using that link you can browse tensorboard</p><h3>Ngrok</h3><p>Start by downloading ngrok and unzip</p><pre>!wget <a href="https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip">https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip</a><br>!unzip ngrok-stable-linux-amd64.zip</pre><p>Let’s assume the TensorBoard log path is “<strong>runs</strong>” and fire up the TensorBoard in the background</p><pre>import os<br>LOG_DIR = &#39;runs&#39;<br>os.makedirs(LOG_DIR, exist_ok=True)<br>get_ipython().system_raw(<br>    &#39;tensorboard --logdir {} --host 0.0.0.0 --port 6006 &amp;&#39;<br>    .format(LOG_DIR))</pre><p>run ngrok to tunnel TensorBoard port 6006</p><pre>get_ipython().system_raw(&#39;./ngrok http 6006 &amp;&#39;)</pre><p>On the last step, generate a public URL by using that URL we can access the colab TensorBoard web page</p><pre>! curl -s http://localhost:4040/api/tunnels | python3 -c \<br>    &quot;import sys, json; print(json.load(sys.stdin)[&#39;tunnels&#39;][0][&#39;public_url&#39;])&quot;</pre><p>we will get output like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*xmh0OH0oW0yJbAF5A8tCTA.png" /></figure><p>Use this link to lunch Tensorboard, and the webpage looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hC0xZKZ9X6gMyFBOPoFvsA.png" /></figure><p>we didn&#39;t write any data yet. Write something on tensorboard by using SummaryWriter. For instance model graph and images, and dummy scaler value (Like previous one)</p><pre>from torch.utils.tensorboard import SummaryWriter<br># load data from loader<br>images, labels = next(iter(train_loader))</pre><pre>tb = SummaryWriter()<br>tb.add_images(&quot;Image&quot;, images)<br>tb.add_graph(model, images)<br>for i in range(1, 20):<br>    tb.add_scalar(&quot;Tag&quot;, 10/i, i)</pre><pre>tb.close()</pre><p>Refresh the TensorBoard web page (default refresh rate 30s). And TensorBoard web page is ready with data. See screenshots</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ovbsRNpkZVBy962_-OajdQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*9xP_0SpKkleGG9mmEZZb4g.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j7rk4OfN70rNknCqVcwx1w.jpeg" /></figure><p>Finally, we can achieve our goals</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_ueCJU5L0Trfi4oU" /><figcaption>Photo by <a href="https://unsplash.com/@matt_j?utm_source=medium&amp;utm_medium=referral">Matthieu Joannon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Now play with tensorboard</p><p>Here is <a href="https://colab.research.google.com/drive/19vLJVMty9cFlIlcvjAqhFw_umATygXwo">notebook </a>for all the code</p><p>Thanks for reading…</p><p>Happy coding 😍</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=458f9bb95212" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Observing network state with live data]]></title>
            <link>https://medium.com/@iamsdt/observing-network-state-with-live-data-90167a8ba04d?source=rss-24d4f54ea99b------2</link>
            <guid isPermaLink="false">https://medium.com/p/90167a8ba04d</guid>
            <category><![CDATA[network-state]]></category>
            <category><![CDATA[livedata]]></category>
            <category><![CDATA[connectivitymanager]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Shudipto Trafder]]></dc:creator>
            <pubDate>Wed, 15 May 2019 17:27:48 GMT</pubDate>
            <atom:updated>2019-05-15T17:28:58.443Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine your activity needs to know when a user is connected with the network or when it has gone.</p><h4>Little Background</h4><p>In<strong> </strong>the previous, we use broadcast manager, when the network state is changed it triggers a broadcast, we catch that in our app and our app is informed about the network state. This is a very popular method. But now it is a deprecated process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*hFcq9V0WR1OxMrw3phs6mg.jpeg" /><figcaption>Credit: rawpixel.com</figcaption></figure><p>Probably you have the experience to work with live data, a library of the android jetpack. Actually, live data is observable data holder class. It’s life cycle aware, that’s the key difference with the regular observer.</p><h4><strong>Workflow:</strong></h4><blockquote><em>Create an object of LiveData</em></blockquote><blockquote><em>Build a network request</em></blockquote><blockquote><em>and register the callback with Connectivity Manager</em></blockquote><p>Let’s start</p><p>Create an object of LiveData, and override the OnActive() method. Our live data will only contain a Boolean value, that means it will indicate the network is connected or not. you can also use enum class so you will get more information, like Available, Unavailable, LOST.</p><pre><em>object </em>NetworkLiveData : LiveData&lt;Boolean&gt;() {<br><br>    override <em>fun </em>onActive() {<br>        <em>super</em>.onActive()<br>    }<br>}</pre><p>We want to initialize this object in the application class, so we need a variable of the application class, create this as late initialize variable, we will initialize this variable latter, and we also need a network request variable also declare this late initialize variable and don’t forget to make those variable as private, we don’t allow access from outside</p><pre><em>private lateinit var </em>application: Application<br><br><em>private lateinit var </em>networkRequest: NetworkRequest</pre><p>Now create init() method, we will call this method in the time of initializing of this live data object. In this method, we will save the reference of application into our local application variable. And also build the network request. In our case, we want to observe only Cellular and WiFi network but you can also add Bluetooth Ethernet, VPN and so on.</p><pre><em>fun </em>init(application: Application) {<br>    <em>this</em>.application = application<br>    networkRequest = NetworkRequest.Builder()<br>        .addTransportType(NetworkCapabilities.<em>TRANSPORT_CELLULAR</em>)<br>        .addTransportType(NetworkCapabilities.<em>TRANSPORT_WIFI</em>)<br>        .build()<br>}</pre><p>The initialization part is finished, now the main part, at first from system services get the connectivity manager and register network callback, simple. We will do all of the code in a new method called <strong>getDetails() </strong>and call this method in the override method <strong>OnActive()</strong></p><pre><em>val </em>cm = application.getSystemService(Context.<em>CONNECTIVITY_SERVICE</em>) <em>as </em>ConnectivityManager</pre><p>Now register the network request call back with connectivity manager, to implement the callback we have to override 3 methods.</p><p><strong>OnAvailable()</strong> -&gt; call when network is connected, so set the value true</p><p><strong>OnUnavailable()</strong> -&gt; call when network is unavailable, so set the value false</p><p><strong>OnLost()</strong> -&gt; call when network is lost, so set the value false</p><pre><em>private fun </em>getDetails() {<br>    <em>val </em>cm = application.getSystemService(Context.<em>CONNECTIVITY_SERVICE</em>) <em>as </em>ConnectivityManager<br>    cm.registerNetworkCallback(networkRequest, <em>object </em>: ConnectivityManager.NetworkCallback() {<br>        <em>override fun </em>onAvailable(network: Network?) {<br>            <em>super</em>.onAvailable(network)<br>            postValue(<em>true</em>)<br>        }<br><br>        <em>override fun </em>onUnavailable() {<br>            <em>super</em>.onUnavailable()<br>            postValue(<em>false</em>)<br>        }<br><br>        <em>override fun </em>onLost(network: Network?) {<br>            <em>super</em>.onLost(network)<br>            postValue(<em>false</em>)<br>        }<br>    })<br>}</pre><h4>Don’t forget to call this class in OnActive() method</h4><pre><em>override fun </em>onActive() {<br>    <em>super</em>.onActive()<br>    getDetails()<br>}</pre><p>Complete 👊</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*5fFA8riBLIeiofiuhwCEoA.jpeg" /><figcaption>Credit:<a href="https://www.pexels.com/@ninauhlikova">Nina Uhlíková</a></figcaption></figure><h3>Bonus:</h3><p>Imagine your activity don’t require the network state every time, but want to check before doing some task. So let’s fulfill this wish too</p><p>Simple first get the connectivity manager and then get the active network information from the connectivity manager and check the active network</p><pre><em>fun </em>isNetworkAvaiable(): Boolean {<br>    <em>val </em>cm = application.getSystemService(<br>             Context.<em>CONNECTIVITY_SERVICE</em>) <em>as </em>ConnectivityManager<br>    <em>val </em>activeNetwork = cm.<em>activeNetworkInfo<br>    return </em>activeNetwork != <em>null </em>&amp;&amp; activeNetwork.<em>isConnected<br></em>}</pre><p>Everything finished. Time for use</p><h3>Testing :</h3><p>Call this line in your application class</p><pre>NetworkLiveData.init(<em>this</em>)</pre><p>And observe the live data in your activity class</p><pre>NetworkLiveData.observe(<em>this</em>, Observer <strong>{<br>    </strong><em>if </em>(<strong>it</strong>) {<br>        <em>//connected<br>    </em>} <em>else </em>{<br>        <em>//connection gone<br>    </em>}<br><strong>}</strong>)</pre><p>And if you just want to check the network is available or not, use this code</p><pre><em>if </em>(NetworkLiveData.isNetworkAvaiable()){<br>   // do somthing   <br>}</pre><p>That’s it. Hope it will help to observe the network state.</p><p>Happy coding 😐</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90167a8ba04d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[List, Recyclerview and Paging Library part 1]]></title>
            <link>https://medium.com/@iamsdt/list-recyclerview-and-paging-library-part-1-ca8cecc4aba4?source=rss-24d4f54ea99b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca8cecc4aba4</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[paging-library]]></category>
            <dc:creator><![CDATA[Shudipto Trafder]]></dc:creator>
            <pubDate>Fri, 01 Feb 2019 17:58:42 GMT</pubDate>
            <atom:updated>2019-04-20T12:08:41.481Z</atom:updated>
            <content:encoded><![CDATA[<h3>List, Recyclerview and Paging Library</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H3WP0hD76Rul-Ia43AYXtQ.png" /><figcaption>Image of List in Android. ImageSource: © Material.io</figcaption></figure><p>The list is pretty common in every Android App. So take a look at how you may implement list in your app. In previous, you may use ListView but after the RecyclerView is popular you probably use RecyclerView. RecyclerView is memory efficient and also has some bunch of new feature. Let’s implement it</p><p>If are using Android Archture Component, you may use LiveData, ViewModel, and Room. From the Data Accessing Object(DAO) class, we access data.</p><pre>@get:Query(&quot;Select * From StackEntity&quot;)<br>val data: LiveData&lt;List&lt;StackEntity&gt;&gt;</pre><p>By this code, we tell the room to send all the data of StackEnity (StackOverflow API) and this is live data, that means it’s lifecycle aware data and it will notify if any change occurs in the database. Now move on ViewModel</p><pre>fun getData(dao: StackEntityDao) = dao.data</pre><p>So we load data in the ViewModel, so this data will survive configuration change. Now move to the activity code</p><pre>lateinit var viewModel: MyViewModel<br>lateinit var adapter: MyAdapter</pre><p>Let’s take a look at Adapter class,</p><pre>class MyAdapter : ListAdapter&lt;StackEntity, MyAdapter.MyViewHolder&gt;(diffs){</pre><p>If you are not familiar with List Adapter, then drive into it. The base class of ListAdapter is RecyclerView.Adapter. Basically, ListAdapter computes the difference between the new list and the previous list in a background thread, and update the UI. When you submit a list it will compute the difference between this list to the previous list in a background thread, and update the UI, only the changed part with a nice animation.</p><p>To initialize this adapter we need a callback, here two methods. First one checks the item are same identically and second one cheek the content are equally or not.</p><pre>val diffs = object : DiffUtil.ItemCallback&lt;StackEntity&gt;() {<br>    override fun areItemsTheSame(oldItem: StackEntity, newItem: StackEntity) =<br>        oldItem.id == newItem.id</pre><pre>override fun areContentsTheSame(oldItem: StackEntity, newItem: StackEntity) =<br>        oldItem == newItem</pre><pre>}</pre><p>So we can decide where we need to rebind the view. And once you have that you can pass this object. And to get the item in <strong>onBindViewHolder</strong> method you have to call the <strong>getItem</strong> method.</p><pre>val model = getItem(position)</pre><p>Back on the Activity class, submit the list to the adapter.</p><pre>vm.getData(dao).observe(this, Observer <strong>{<br>    </strong>adapter.submitList(it)<br><strong>}</strong>)</pre><p>So this is the basic way of implementing a list.</p><h4>What is the problem?</h4><p>Maybe this question arises in your mind what is the problem in this approach. The problem is you are loading all the data from the database, but only a few are needed to draw the UI. Imagine you have 5000 entries in your database. But only 10 entries is required to draw UI, so why you are loading all of your data?</p><h4>Solution</h4><p>The solution is pretty simple, you can use PagingLibary.</p><p>Let’s talk about its component. The most important component of the paging library is PageList.PageList is a list which implements with pages and loads data asynchronously. In the behind, the class called DataSource class provide data as page list needs and update the list.</p><p>Let’s implement PagingLibaray. Add any of those in <strong>build.gradle</strong></p><pre>//for androidx<br>implementation &quot;androidx.paging:paging-runtime:2.1.0&quot;<br>//if you are using kotlin and androidx, add this<br>implementation &quot;androidx.paging:paging-runtime-ktx:2.1.0&quot;<br>//for pre-Androidx<br>implementation &quot;android.arch.paging:runtime:$paging_version&quot;</pre><p>After syncing the project, we have to change the Dao class. In the previous we ask the dao, to give live data with the stack entity list. But this time we ask our dao to give us live data with page list. It creates an issue, because you imagine the paging in one way, and others in a different way. It’s may depend with app need, so page list need to config. that’s we ask to give a <strong>DataSource.Factory, </strong>that’s keyed off of integer because we using positions.</p><pre>@get:Query(&quot;Select * From StackEntity&quot;)<br>val data: DataSource.Factory&lt;Int, StackEntity&gt;</pre><p>Now back to the ViewModel class. So get the data source factory by using dao, and use this LivePagedListBuilder class to produce the Live Data. The minimum amount of data we need to pass is page size, in our case, it is 30.</p><pre>fun getData(dao: StackEntityDao): LiveData&lt;PagedList&lt;StackEntity&gt;&gt; {<br>    val factory = dao.getAllData()<br>    return LivePagedListBuilder&lt;Int, StackEntity&gt;(factory, 30)<br>        .build()<br>}</pre><p>you can also set a further configuration of the page list. just create a configuration object and do more.</p><pre>fun getData(dao: StackEntityDao): LiveData&lt;PagedList&lt;StackEntity&gt;&gt; {<br>    val factory = dao.getAllData()<br>    <br>    val config = PagedList.Config.Builder()<br>        .setPageSize(30)<br>        .setInitialLoadSizeHint(50)<br>        .setPrefetchDistance(20)<br>        .setEnablePlaceholders(false)<br>        .build()</pre><pre>return LivePagedListBuilder&lt;Int, StackEntity&gt;(factory, config)<br>        .build()<br>}</pre><p>so page size is as usual, but to do more you can add initial load size, which is 3 times of page size by default. you also set prefetch distance which is the same as page size by default. you can also control the place holder, by default it is true.</p><p><strong>Place Holder</strong></p><p>If you enable place holder your adapter will know about the total data size of your database. when the user scrolls the list, and in the down user see the unloaded items, which is null in the adapter. when these items are loaded it will display with a nice animation. If you don’t enable the place holder, you may notice the scrollbar of RecyclerView is larger in size first. But when the user scrolls the list and runs out of data, once the page loads the scroll bar jump in and smaller in size than previous.</p><p>Now move the adapter class, In the previous we use ListAdapter, but we have to use the PageListAdapter. every this is the same as previous, we don’t have to change the callback. The only change is this time the item can be null in onBindViewHolder.</p><pre>val model: StackEntity? = getItem(position)</pre><p>so make these entities as nullable, and make use your adapter can handle nullable object. Back to the Activity Class.</p><pre>vm.getData(dao).observe(this, <em>Observer </em><strong>{<br>    </strong>adapter.submitList(<strong>it</strong>)<br><strong>}</strong>)</pre><p>this time get data method provides live data with page list, and our adapter also takes page list, so submit the list.</p><p>This is a pretty simple way to use the Paging Library. But I this part</p><h3>Remote Source</h3><p>In the previous section, we load all the data from a database. But now we will load all the data from a remote source. To retrieve data from a remote source, you need an API, in this case, I use StackOverflow API. I also use Retrofit for networking. I am not showing this part.</p><p>We need to build a data source, in the previous we use <strong>PositionalDataSource </strong>but this time we will use <strong>PageKeyedDataSource.</strong></p><pre>class NetworkDataSource : PageKeyedDataSource&lt;Int, StackEntity&gt;() {</pre><p>So our key is an integer. We have to override 3 methods, named</p><pre>loadInitial() -&gt; load the initial data, called on onCreate<br>loadAfter() -&gt; load next page, called on user scroll down<br>loadBefore() -&gt; load previous page, called on user scroll up</pre><p>First load initial data and first page start with 1.</p><pre>override fun loadInitial(params: LoadInitialParams&lt;Int&gt;, callback: LoadInitialCallback&lt;Int, StackEntity&gt;) {<br>    --- code here<br>    //retrofit call and onResponse method<br>      if (response.body() != null) {<br>          val list = response.body()?.items ?: <em>emptyList</em>()<br>          callback.onResult(list, null, FIRST_PAGE + 1)</pre><p>Load next page, but this time we have a key saved in the <strong>LoadParams</strong>. To get the key just call the <strong>params.key. </strong>After the response is successful, check next page is available or not. If the next page available increase the key and save the key. If the next page is not available, then you are on the last page, so the next page key will be null.</p><pre>override fun loadAfter(params: LoadParams&lt;Int&gt;, callback: LoadCallback&lt;Int, StackEntity&gt;) {<br>      val next_key = params.key<br>      --- code here<br>      //retrofit call and onResponse method<br>        response.body()?.<em>let </em><strong>{<br>              //check is next page avaiable<br>               </strong>val key: Int? = if (<strong>it</strong>.has_more) params.key + 1<br>                     else null</pre><pre>val list = response.body()?.items ?: <em>emptyList</em>()<br>                callback.onResult(list, key)</pre><p>Now load the data from the previous page of the current page. After the response is successful, check the previous page is available or not. If the previous page is greater than 1 then it’s available and decrease the key and save the key. If the previous page is not available, then you are on the first page, so the previous page key will be null.</p><pre>override fun loadAfter(params: LoadParams&lt;Int&gt;, callback: LoadCallback&lt;Int, StackEntity&gt;) {<br>      val next_key = params.key<br>      --- code here<br>      //retrofit call and onResponse method<br>        response.body()?.<em>let </em><strong>{<br>              //check is next page avaiable<br>               </strong>val key: Int? =if (params.key &gt; 1) params.key - 1<br>                     else null</pre><pre>val list = response.body()?.items ?: <em>emptyList</em>()<br>                callback.onResult(list, key)</pre><p>That’s is the data source class, you can also take a look at this class on Git for complete code, <a href="https://github.com/Iamsdt/JetpackDemo/blob/master/paging/src/main/java/com/iamsdt/paging/network/NetworkDataSource.kt">NetworkDataSource.kt</a></p><p>Create a data source factory</p><pre>class NetworkDataSourceFactory : DataSource.Factory&lt;Int, StackEntity&gt;() {<br>    override fun create(): DataSource&lt;Int, StackEntity&gt; = NetworkDataSource()<br>}</pre><p>replace the data source in the view model getData() method and yes you can also remove the dao parameter.</p><pre>fun getData(): LiveData&lt;PagedList&lt;StackEntity&gt;&gt; {<br>    val factory = NetworkDataSourceFactory()<br>    <br>    val config = PagedList.Config.Builder()<br>        .setPageSize(30)<br>        .setInitialLoadSizeHint(50)<br>        .setPrefetchDistance(20)<br>        .setEnablePlaceholders(false)<br>        .build()</pre><pre>return LivePagedListBuilder&lt;Int, StackEntity&gt;(factory, config)<br>        .build()<br>}</pre><p>and submit the list to the adapter</p><pre>vm.getData().observe(this, <em>Observer </em><strong>{<br>    </strong>adapter.submitList(<strong>it</strong>)<br><strong>}</strong>)</pre><p>Check all of the code in <a href="https://github.com/Iamsdt/JetpackDemo/tree/master/paging/src/main/java/com/iamsdt/paging/network"><strong>GitHub</strong></a>.</p><p>In this section, we don’t have any catch. If we lost the internet connection, we will also lose the data. (a portion of data kept until you left the app).</p><h4>Database + Network</h4><p>In this approach, the data will be stored in a local database. This is pretty similar to the first section, database section. The only addition is that you have to add a boundary callback when you build the live data.</p><p>Let’s create</p><pre>private fun getBoundary(dao: StackEntityDao) = object : PagedList.BoundaryCallback&lt;StackEntity&gt;() {</pre><p>First, we will override the <strong>onZeroItemsLoaded()</strong> method, called when the database returns zero items from the initial load.</p><pre>override fun onZeroItemsLoaded() {<br>    super.onZeroItemsLoaded()<br>    call(first_key, dao) //call the remote server for data<br>}</pre><p>The second method, we will override, name <strong>onItemAtEndLoaded()</strong>, called when the item at the end of the PagedList has been loaded.</p><pre>override fun onItemAtEndLoaded(itemAtEnd: StackEntity) {<br>    super.onItemAtEndLoaded(itemAtEnd)<br>    call(nextPage_key, dao) //call the remote server for data<br>}</pre><p>That’s it the boundary call back. now add this boundary callback to the view model getData() method.</p><pre>fun data(dao: StackEntityDao): LiveData&lt;PagedList&lt;StackEntity&gt;&gt; {</pre><pre>    val factory = dao.getAllData()</pre><pre>    val config = PagedList.Config.Builder()<br>        .setEnablePlaceholders(false)<br>        .setPageSize(50)<br>        .build()</pre><pre>    val boundary = getBoundary(dao)</pre><pre>    return LivePagedListBuilder&lt;Int, StackEntity&gt;(factory, config)<br>        .setBoundaryCallback(boundary)<br>        .build()<br>}</pre><p>submit the list to the adapter</p><pre>vm.getData(dao).observe(this, <em>Observer </em><strong>{<br>    </strong>adapter.submitList(<strong>it</strong>)<br><strong>}</strong>)</pre><p>That’s all of the paging.</p><h4>Code:</h4><p>you can get this code in the this <a href="https://github.com/Iamsdt/JetpackDemo/tree/master/paging/src/main/java/com/iamsdt/paging"><strong>git</strong></a></p><p>In this article, I tried to cover about paging with different data sources. Hope this article helps you. Thanks for reading.</p><p>Happy coding 😍</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca8cecc4aba4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>