<?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 Darshan sanjay lahamage on Medium]]></title>
        <description><![CDATA[Stories by Darshan sanjay lahamage on Medium]]></description>
        <link>https://medium.com/@lahamagedarshan61?source=rss-b26a1f5dc806------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*6o6qR-S3CDNwXmn3</url>
            <title>Stories by Darshan sanjay lahamage on Medium</title>
            <link>https://medium.com/@lahamagedarshan61?source=rss-b26a1f5dc806------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 21:10:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lahamagedarshan61/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[cache_it: open-source tools to measure and fix prompt caching in agent harnesses — Part 2]]></title>
            <link>https://medium.com/@lahamagedarshan61/cache-it-open-source-tools-to-measure-and-fix-prompt-caching-in-agent-harnesses-part-2-5a150fb2501a?source=rss-b26a1f5dc806------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a150fb2501a</guid>
            <category><![CDATA[cache-design]]></category>
            <category><![CDATA[ai-harness-cache]]></category>
            <category><![CDATA[agentic-ai-architecture]]></category>
            <category><![CDATA[agentic-ai-cache-design]]></category>
            <dc:creator><![CDATA[Darshan sanjay lahamage]]></dc:creator>
            <pubDate>Fri, 04 Dec 2026 13:38:53 GMT</pubDate>
            <atom:updated>2026-12-04T15:03:05.104Z</atom:updated>
            <content:encoded><![CDATA[<p>The <a href="https://medium.com/@lahamagedarshan61/cache-system-for-agent-harnesses-where-it-breaks-and-how-to-design-for-it-09a1af04ebcd?sharedUserId=lahamagedarshan61">previous post</a> explained how prompt caching works inside an agent harness and the ten ways a harness loses it. This post is about the tools I built to measure and fix those losses: <strong>cache_it</strong>, an open-source project at <a href="https://github.com/darshanlahamage/cache_it">github.com/darshanlahamage/cache_it</a> .</p><p>In one sentence: <strong>cache_it tells you how much your harness pays for caching, why each cache miss happened, and whether your fixes made the agent worse.</strong></p><blockquote><strong><em>Who this is for:</em></strong><em> teams running an agent harness who want to know where their cache money goes, and anyone who wants a tested reference for the design ideas in the first post.</em></blockquote><h3>Why it exists</h3><p>I kept seeing the same cycle on the harness I work on. The bill goes up. Someone adds logging. Days later the cause turns up: a timestamp in a prompt, a tool list rebuilt in a different order, a session restored with slightly different JSON. It gets fixed, and a few weeks later a different change does the same thing.</p><p>Three things were missing:</p><ul><li><strong>A shared way to measure.</strong> Teams compare hit rates that mean different things, and almost nobody checks whether a caching change made the agent worse.</li><li><strong>Attribution.</strong> Knowing that the cache missed is easy. Knowing which change caused it is the hard part.</li><li><strong>Small, reusable fixes</strong> that do not require adopting a framework or putting a proxy in front of the model.</li></ul><h3>In this post</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*64DU-rdarxLxInAHbkowdw.png" /></figure><h3>Part 1. Architecture</h3><h3>1.1 Four pieces, each usable alone</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1OrC4sNiGwBJcZMFisuIoQ.png" /></figure><p><em>Figure 1. The support matrix feeds both packages. cachebench scores your harness, with or without stableprefix.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bfIgTgdIQlRt_GBLZwfCPQ.png" /></figure><h3>1.2 The repository</h3><pre>cache_it/<br>  docs/design-guide.md      the guide<br>  support-matrix/           matrix.json, schema, probes/<br>  cachebench/               benchmark package, METHOD.md, 22 scenarios<br>  stableprefix/             library package, one module per fix<br>  examples/toy_harness/     a reference harness with four caching strategies</pre><h3>1.3 Principles</h3><ul><li><strong>Low dependency.</strong> stableprefix uses only the Python standard library; database backends are optional extras. cachebench needs PyYAML and nothing else.</li><li><strong>Never in the request path.</strong> Neither package sends requests or wraps your client. You keep your SDK, your request format and your agent loop.</li><li><strong>Correctness before cache.</strong> Every feature has a fallback that is always correct, usually a rebuild, so a missing provider feature can never break the agent.</li><li><strong>Measured, not claimed.</strong> stableprefix is scored by cachebench like any other harness, and its defaults come from those runs.</li></ul><h3>Part 2. cachebench, step by step</h3><p>cachebench answers one question: <strong>does this caching strategy save money without making the agent worse?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*If1FpD8SUR0-VzrNgWIjjQ.png" /></figure><p><em>Figure 2. A scenario drives your unchanged harness through an adapter. Every request is logged, and the log is scored on cost and quality.</em></p><p>A run has five steps:</p><ol><li><strong>Load a scenario:</strong> a scripted session of user turns and events.</li><li><strong>Drive your harness</strong> through a thin adapter. The harness runs its real agent loop.</li><li><strong>Record every request</strong> with its usage and a hash of each part of the request.</li><li><strong>Score</strong> the log: a cost scorecard and a quality scorecard.</li><li><strong>Compare</strong> with a baseline run and give a verdict.</li></ol><h3>2.1 Scenarios: sessions with events</h3><p>A steady conversation tells you little, because misses come from events. A scenario is a YAML file of turns and events, and each event declares which parts of the request it is allowed to change:</p><pre>id: tools.remove<br>category: capability<br>steps:<br>  - turn: &quot;Open src/app.py and explain what the main function does.&quot;<br>    expect: {tools_used_any_of: [read_file]}<br>  - event: {type: tool_removed, tool: write_file}<br>    expected_changes: {allowed: [history, turn]}<br>  - turn: &quot;Add a docstring to the main function in src/app.py.&quot;<br>    expect:<br>      must_not_call: [write_file]<br>      outcome: {file_unchanged: src/app.py}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A3pujAFVkmgfhiUlDKnDnA.png" /></figure><p>There are 22 scenarios, at least one per source:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QQW-GR6cmd2z0TiPS0dsWw.png" /></figure><h3>2.2 Connecting your harness</h3><p>The adapter has three methods and wraps your real loop:</p><pre>class MyHarnessAdapter:<br>    def start_session(self, setup) -&gt; str:<br>        # build a session from setup.scenario (tools, system prompt, options)<br>        ...<br><br>    def apply_event(self, session_id, event) -&gt; None:<br>        # do what your product does when this happens<br>        ...<br><br>    def run_turn(self, session_id, user_message):<br>        # your normal agent loop; after each model call:<br>        #   setup.recorder.record(request, response, session_id=..., route=region)<br>        ...</pre><h3>2.3 What gets recorded</h3><p>For every request, cachebench stores the normalized usage (Anthropic, Bedrock, OpenAI, Gemini and DeepSeek field names all map to one shape) and a hash of each section: the model, each tool by name, the system prompt, the request settings, and each message. Comparing hashes between two consecutive requests shows exactly which part changed.</p><h3>2.4 How a miss is classified</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sukeqk14h4yv4i_eWtlRLA.png" /></figure><p><em>Figure 3. Every miss gets one cause and a cost. Content misses also name the first changed section, down to a single tool.</em></p><p>The same rules run in the benchmark and in stableprefix’s production tracker, so offline and production numbers agree.</p><h3>2.5 Scores and verdict</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*5XkbFzC4Je_fBsEjh-NTqg.png" /></figure><p>Each scenario runs with your strategy and with a <strong>baseline</strong> of the same harness that rebuilds on every change, which is correct by construction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*oUiOMnr9kvAMaEOKfiJ6ow.png" /></figure><p>The report adds a table per source, so a harness that is excellent on tools and poor on routing shows exactly that.</p><h3>2.6 Offline or against a real provider</h3><p>The repository includes a <strong>simulated provider</strong> that reproduces Anthropic-style prefix caching (breakpoints, lookback, lifetimes refreshed on read, minimum size, request settings in the prefix, native tool changes, one cache per region) and a <strong>scripted model</strong> in place of the LLM. The whole benchmark runs in seconds with no API key, which is what CI uses. For real numbers, run the same adapter against a real provider with the real clock.</p><h3>2.7 In CI and production</h3><ul><li>cachebench check compares a new run with the previous release and fails on higher cost, lower quality, or <strong>a new source of misses</strong>.</li><li>cachebench drift reads production logs and flags a sustained drop in cache read share.</li></ul><h3>Part 3. stableprefix, part by part</h3><p>stableprefix makes one promise: <strong>the same session state produces the same request bytes; content is ordered by how often it changes; new content goes at the end; and the start of the request changes only when it must, or when it is free.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fl40pkk4o6ft7ERFJZ3HQw.png" /></figure><p><em>Figure 4. Each part handles one group of sources and works on its own. None of them sends requests.</em></p><p>Every provider-specific decision (does this surface support native tool removal, what does a 1-hour write cost on this model, how far does the lookback reach) is read from the support matrix, never hard-coded.</p><h3>3.1 Layout planner</h3><p><strong>Solves:</strong> layout, sharing across tenants, breakpoint placement, per-turn context.</p><pre>from stableprefix import LayoutPlanner, LayoutConfig, Segment, turn_message<br><br>planner = LayoutPlanner(LayoutConfig.for_target(target))     # one per session<br>store.append(sid, [turn_message(&quot;What changed?&quot;, [(&quot;date&quot;, &quot;2026-11-30&quot;)])])<br>request = planner.build(<br>    model=&quot;claude-opus-5-5&quot;, tools=tools, messages=store.load(sid),<br>    segments=[Segment(&quot;rules&quot;, SHARED, &quot;global&quot;),<br>              Segment(&quot;tenant&quot;, acme_policies, &quot;tenant&quot;),<br>              Segment(&quot;session&quot;, project_notes, &quot;session&quot;)],<br>).request</pre><ul><li>Emits segments in global, tenant, session order, with a breakpoint after each group.</li><li>Adds an anchor breakpoint where the previous request ended when a turn adds many blocks.</li><li>Skips breakpoints below the model’s minimum size and refuses an invalid lifetime order.</li></ul><h3>3.2 Settings guard</h3><p><strong>Solves:</strong> request settings that silently invalidate. ParamGuard pins a session&#39;s settings and reports, or refuses, changes to tool_choice, thinking, effort, output format and the rest, each with the cache level it invalidates on that provider.</p><h3>3.3 Context manager</h3><p><strong>Solves:</strong> trimming that rewrites history every turn. Two watermarks, oldest tool results cleared first with a fixed placeholder, early trimming when the cache is already cold, and a break-even helper.</p><pre>ctx = ContextManager(ContextPolicy(high_watermark=120_000, low_watermark=60_000))<br>decision = ctx.decide(message_tokens(history), cache_cold=cold)<br>if decision.action == &quot;trim&quot;:<br>    history, removed, enough = ctx.apply(history, decision)</pre><h3>3.4 Capability ledger</h3><p><strong>Solves:</strong> tools, MCP servers, skills and subagents changing mid-session. You record events; the ledger plans the next request in the cheapest form that is correct on your target.</p><pre>ledger = CapabilityLedger(target)<br>ledger.add_tools(mcp_tools)<br>ledger.remove_tool(&quot;run_sql&quot;, reason=&quot;permission&quot;)<br>plan = ledger.plan_next_request()<br># plan.tools, plan.native_blocks, plan.notes, plan.allowed_tools, plan.rebuild</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vadXnQGVUBIxB6ULhOOb-Q.png" /></figure><p><em>Figure 5. The ledger falls back from native changes to masking, to notes (additions only), to a rebuild. Correctness never depends on a provider feature.</em></p><h3>3.5 Session store</h3><p><strong>Solves:</strong> inexact rebuilds. Stores rendered blocks with a hash chain, verifies on load, writes durable first, and makes appends idempotent. Backends: memory, files, Redis, Firestore, Postgres.</p><h3>3.6 Warmth</h3><p><strong>Solves:</strong> expiry and cold fan-out. TTLAdvisor picks 5-minute or 1-hour caching from real pauses, keepalive_worth says whether a refresh pays, and fanout runs one request until its first token before starting the rest.</p><h3>3.7 Routing</h3><p><strong>Solves:</strong> one session spread across caches. pick_endpoint uses rendezvous hashing so a session sticks to one region and moves back after an outage; cache_key and sharded_key give stable routing keys.</p><h3>3.8 Layout check and cache tracker</h3><p><strong>Solve:</strong> visibility. The check runs before a request is sent and flags volatile values, unsorted tools, setting changes, history rewrites and prefixes below the minimum. The tracker normalizes usage after the response, classifies each miss with the same rules as cachebench, and reports its cost.</p><pre>check.run(request, previous=tracker.last_request(sid), target=target)<br>record = tracker.observe(request, response, session_id=sid, route=region)<br>if record.miss and record.miss.cause != &quot;planned&quot;:<br>    log.warning(&quot;cache miss&quot;, source=record.miss.source, section=record.miss.section,<br>                cost=record.miss.extra_cost)</pre><h3>3.9 How to adopt it</h3><ol><li><strong>Start with the tracker and the check.</strong> They change nothing about how you build requests, and immediately answer “why did the bill go up”.</li><li><strong>Add the session store</strong> if you ever rebuild sessions from storage. Rebuild drift is common and invisible.</li><li><strong>Add the layout planner</strong> and move per-turn context into the turn.</li><li><strong>Add the ledger</strong> if users or agents change tools mid-session.</li><li><strong>Add warmth and routing</strong> once pauses and regions show up in your miss causes.</li></ol><h3>Part 4. How it helps in practice</h3><p>cache_it is meant to be used at four moments in a harness’s life. Each one answers a question teams usually answer by guessing.</p><h3>4.1 Before you ship a change</h3><p>A new tool, a prompt edit, a model upgrade or a new subagent can quietly break the cache. Run cachebench check in CI. It compares the new build with the last release and fails if cost goes up or task success goes down, and it names the source that caused it.</p><h3>4.2 When the bill jumps in production</h3><p>The tracker logs every miss with its cause and the first part of the request that changed. Instead of “cache hit rate dropped”, you get “content miss, system prompt, tenant section”. That points to the change, usually within minutes.</p><h3>4.3 When you design a new feature</h3><p>Before adding mid-session MCP connections, subagents or compaction, run the matching scenario against your harness. You see what the feature does to the cache before it reaches users, and you can pick the stableprefix part that handles it.</p><h3>4.4 When you tune for your traffic</h3><p>The lifetime advisor reads real pauses between requests and tells you whether 5-minute or 1-hour caching is cheaper for your users. The routing helper keeps each session on one endpoint, so a load balancer does not spread it across cold caches.</p><h3>What you do not need to do</h3><ul><li>Rewrite your harness. The tracker and the check change nothing about how requests are built.</li><li>Adopt everything. Each part works alone, so you can fix one source at a time.</li><li>Run a proxy or a new service. It is a library inside your process.</li></ul><h3>Part 5. Design decisions</h3><p>Each of these choices rules something out. Here is what, and why.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lO8bhzXOPLomHj0mJgablA.png" /></figure><h3>Part 6. Limits, roadmap, and trying it</h3><h3>6.1 What it does not do yet</h3><p>The project is alpha (v0.2, 76 tests, Python 3.10 to 3.13).</p><ul><li><strong>No published real-provider results.</strong> Everything in Part 4 comes from the simulator. This is the biggest gap.</li><li><strong>The support matrix is partly unverified.</strong> The probes exist but have not run across every surface. Some entries say “unknown” on purpose.</li><li><strong>The layout planner builds Anthropic requests.</strong> For OpenAI, the ordering rules apply, but the planner does not yet emit Responses API requests or set prompt_cache_key.</li><li><strong>No semantic cache,</strong> by design. A useful addition would be a scenario that measures a semantic cache’s false-hit rate against its savings.</li></ul><h3>6.2 Roadmap</h3><ol><li>Real-provider runs of the reference harness on Anthropic and Vertex</li><li>Probe results for every surface in the matrix</li><li>OpenAI support in the layout planner</li><li>Gemini explicit-cache helpers</li><li>Policy defaults tuned per model from benchmark runs</li></ol><h3>6.3 Try it in two minutes</h3><pre>git clone https://github.com/darshanlahamage/cache_it &amp;&amp; cd cache_it<br>pip install -e ./stableprefix -e ./cachebench</pre><pre>cachebench run --adapter examples.toy_harness.harness:factory \<br>  --scenarios cachebench/scenarios --variants baseline naive stableprefix \<br>  --runs 3 --clock sim --target anthropic/anthropic-api/claude-opus-5-5 --out runs/<br>cachebench score runs/ --out runs/</pre><p>No API key needed. Open runs/report.md and compare it with Part 4.</p><h3>6.4 How to help</h3><p>The most useful contributions right now are evidence, not code:</p><ul><li><strong>Run cachebench on your own harness,</strong> even one scenario against a real provider, and share the report.</li><li><strong>Run the probes</strong> for a surface you use and send the results.</li><li><strong>Write a scenario</strong> that reproduces a cache problem you hit in production.</li></ul><p>If your harness loses its cache in a way this project does not cover, open an issue. That is exactly the kind of case the benchmark exists to capture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a150fb2501a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caching for agent harnesses: where it breaks and how to design for it — Part 1]]></title>
            <link>https://medium.com/@lahamagedarshan61/cache-system-for-agent-harnesses-where-it-breaks-and-how-to-design-for-it-09a1af04ebcd?source=rss-b26a1f5dc806------2</link>
            <guid isPermaLink="false">https://medium.com/p/09a1af04ebcd</guid>
            <category><![CDATA[agent-harness-engineering]]></category>
            <category><![CDATA[agentic-ai-architecture]]></category>
            <category><![CDATA[cache-design]]></category>
            <category><![CDATA[agentic-harness]]></category>
            <category><![CDATA[agentic-ai-cache-system]]></category>
            <dc:creator><![CDATA[Darshan sanjay lahamage]]></dc:creator>
            <pubDate>Mon, 30 Nov 2026 19:18:06 GMT</pubDate>
            <atom:updated>2026-12-01T07:39:04.788Z</atom:updated>
            <content:encoded><![CDATA[<p>Most engineers know what a cache is. Far fewer know what actually happens to their tokens when an agent harness talks to a model provider: which bytes get cached, where the cache entry is written, why the next request reads it, and why a harmless-looking line of code makes the whole thing fall apart.</p><p>This guide walks through that from the bottom up. We start with what a single agent request looks like, follow it through the provider’s cache request by request, and then use that picture to explain every way a harness loses its cache, how to design around each one, and how to measure the result.</p><blockquote><strong><em>Who this is for:</em></strong><em> engineers building or running agent harnesses (coding agents, support agents, research agents, internal copilots) on Anthropic, OpenAI, Gemini or a self-hosted model.</em></blockquote><h3>What you will learn</h3><ul><li>How an agent conversation turns into a sequence of requests, and why each request contains the previous one</li><li>How provider prompt caching matches, writes and reads, down to breakpoints and the lookback window</li><li>The ten ways a harness breaks its cache, with the trap behind each</li><li>A design for the request, the session store, tool changes, trimming, uploads, lifetimes and routing</li><li>How to tell “cheaper” from “cheaper and broken”</li><li>What to measure, and how to keep it from regressing</li></ul><h3>The map</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Aik4KyNjtpuCXNVzBu67g.png" /></figure><p>The examples use Anthropic’s API because it exposes the most controls. Where OpenAI or Gemini differ, the difference is called out.</p><h3>Part 1. Anatomy: what an agent sends on every step</h3><h4>1.1 The three sections of a request</h4><p>Every call to the model is one self-contained request. The model keeps no memory between calls, so the harness sends everything the model needs, every time. On Anthropic’s Messages API that request has three sections, always in this order:</p><pre>{<br>  &quot;model&quot;: &quot;claude-opus-5-5&quot;,<br>  &quot;tools&quot;: [                                   // ~3,000 tokens<br>    {&quot;name&quot;: &quot;read_file&quot;,   &quot;description&quot;: &quot;...&quot;, &quot;input_schema&quot;: {...}},<br>    {&quot;name&quot;: &quot;search_docs&quot;, &quot;description&quot;: &quot;...&quot;, &quot;input_schema&quot;: {...}}<br>  ],<br>  &quot;system&quot;: [                                  // ~8,000 tokens<br>    {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;You are a coding assistant. Rules: ...&quot;}<br>  ],<br>  &quot;messages&quot;: [                                // grows every step<br>    {&quot;role&quot;: &quot;user&quot;,      &quot;content&quot;: &quot;Find the bug in app.py&quot;},<br>    {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: [{&quot;type&quot;: &quot;tool_use&quot;, &quot;name&quot;: &quot;read_file&quot;, ...}]},<br>    {&quot;role&quot;: &quot;user&quot;,      &quot;content&quot;: [{&quot;type&quot;: &quot;tool_result&quot;, &quot;content&quot;: &quot;...file...&quot;}]},<br>    {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: &quot;The bug is on line 42...&quot;},<br>    {&quot;role&quot;: &quot;user&quot;,      &quot;content&quot;: &quot;Fix it and run the tests&quot;}<br>  ]<br>}</pre><p>Laid out as the provider reads it, from left to right:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7qndir-4zvOQpREv33B7Lw.png" /></figure><p><em>Figure 1. Tools, then system, then messages. The numbered markers are cache breakpoints, explained in Part 2.</em></p><ul><li><strong>Tools</strong> hold the name, description and JSON schema of every tool the model may call. In agents with MCP servers this section alone can reach tens of thousands of tokens.</li><li><strong>System</strong> holds instructions, policies, and often per-user or per-project context.</li><li><strong>Messages</strong> hold the conversation: user turns, assistant replies, and the tool_use and tool_result blocks of every tool call so far.</li></ul><h4>1.2 One user turn is many requests</h4><p>A chatbot makes one request per user message. An agent makes several, because every tool call is a round trip:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_FrRtziPzuSMDODT9bMVPQ.png" /></figure><p><em>Figure 2. The agent loop. Request 2 is request 1 plus two new blocks.</em></p><ol><li>The user asks something.</li><li>The harness sends request 1: tools, system, history, the question.</li><li>The model answers with a tool_use block instead of text.</li><li>The harness runs the tool.</li><li>The harness sends request 2: <strong>everything from request 1</strong>, plus the tool_use block and the tool_result.</li><li>The loop repeats until the model answers in text.</li></ol><h3>Part 2. Mechanics: how the provider cache works</h3><h4>2.1 The one rule: exact prefix match</h4><p>A provider prompt cache is not a key-value store of answers. It stores the model’s internal state (the attention key/value tensors) for the <strong>first N tokens</strong> of a request. A later request can reuse that state only if its first N tokens are <strong>byte-for-byte identical</strong>.</p><ul><li>Matching starts at the very first byte and moves forward in the fixed order: tools, system, messages.</li><li>The first byte that differs ends the match. Everything after it is computed again.</li><li>Meaning does not matter. A reordered JSON key, an extra space or a new timestamp is a different prefix.</li></ul><blockquote><strong><em>Key idea:</em></strong><em> a change at position N costs you everything from N to the end. Where a change happens matters more than how big it is.</em></blockquote><h4>2.2 Breakpoints: where cache entries are written</h4><p>On Anthropic you mark where the cache should store state with a cache_control marker on a content block. That position is a <strong>breakpoint</strong>:</p><pre>&quot;system&quot;: [<br>  {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;You are a coding assistant...&quot;,<br>   &quot;cache_control&quot;: {&quot;type&quot;: &quot;ephemeral&quot;}}          // breakpoint 1<br>],<br>&quot;messages&quot;: [<br>  ...,<br>  {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: [<br>    {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;Fix it and run the tests&quot;,<br>     &quot;cache_control&quot;: {&quot;type&quot;: &quot;ephemeral&quot;}}        // breakpoint 2<br>  ]}<br>]</pre><p>For each breakpoint, the provider does two things:</p><ol><li><strong>Read:</strong> look for an existing entry whose prefix matches this request, at this position or earlier.</li><li><strong>Write:</strong> if the prefix up to this position is not stored yet, store it.</li></ol><p>You get up to four breakpoints per request. Anthropic also offers automatic caching, which places a breakpoint on the last cacheable block for you. OpenAI and Gemini cache automatically without markers.</p><h4>2.3 A walkthrough, request by request</h4><p>Here is what happens over four requests of one session, with breakpoints after the system prompt and on the last message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G6zwtsrQ6z8B8feoIAlLbw.png" /></figure><p><em>Figure 2. Green is read from cache, amber is written, red is rewritten after a break. Costs are in base input-token units, computed from the token counts shown at Anthropic 5-minute prices.</em></p><ul><li><strong>Request 1</strong> finds nothing. It writes the whole prefix at 1.25x: more expensive than sending it uncached.</li><li><strong>Request 2</strong> (after a tool call) matches all of request 1, reads it at 0.1x, and writes only the 1,500 new tokens.</li><li><strong>Request 3</strong> does the same. Its cost is now a sixth of the uncached price.</li><li><strong>Request 4</strong> follows an MCP server connecting. The tool list at the very top changed, so nothing matches, and all 13,900 tokens are written again. That one request costs more than three times as much as requests 2 and 3 together.</li></ul><h4>2.4 The lookback window</h4><p>A breakpoint does not search the whole request for an old entry. It looks back a limited distance: <strong>20 positions</strong> on Anthropic. (On the Claude API a run of consecutive tool_use blocks counts as one position, and so does a run of tool_resultblocks.)</p><p>In normal agent loops each request adds two or three blocks, so this never matters. It matters when one turn adds many blocks at once: a document pasted as separate parts, a batch of attachments, many parallel tool results on a surface that counts each one. The fix is a second breakpoint on the block where the previous request ended, where an entry is known to exist.</p><h4>2.5 Lifetime</h4><p>Entries do not live forever. On Anthropic the default entry lives <strong>5 minutes after its last use</strong>, and every read resets the clock. A 1-hour option costs more to write. If the gap between two requests is longer than the lifetime, the next request starts cold. Part 6 shows how to choose between them.</p><h4>2.6 Prices, and why a broken cache is worse than none</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9OYE4QXZcEeIzewNiDB9fg.png" /></figure><p>A write pays for itself after one read on the 5-minute cache, or two on the 1-hour cache. The flip side: if something near the top changes on every request, every request pays the write premium and never collects a read. That costs about 25% <strong>more</strong> than turning caching off.</p><h4>2.7 Other rules that bite</h4><ul><li><strong>Minimum size.</strong> A prefix below the model’s minimum (from about one thousand to a few thousand tokens, depending on the model) is not cached. No error is returned.</li><li><strong>Isolation.</strong> Entries are shared only within one organization (and one workspace on the Claude API), and only for the same model. Different regions or deployments should be treated as separate caches.</li><li><strong>Settings are part of the key.</strong> Some request parameters invalidate parts of the cache even when no text changed. Part 4 covers which.</li></ul><h4>2.8 How OpenAI and Gemini differ</h4><p>OpenAI caches automatically above 1,024 tokens, charges no write premium, and routes by an optional prompt_cache_key. Gemini caches automatically on recent models and also offers explicit caches billed for storage per hour. The matching rule is the same everywhere: exact prefix.</p><h3>Part 3. Breakage: the ten ways a harness loses its cache</h3><p>With the mechanics in place, every cache miss has one of two explanations: <strong>the bytes changed</strong>, or <strong>the bytes were fine but the entry was gone or out of reach</strong>. In a real harness those two explanations come from ten different sources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TXLjLCNIkY2lgMt_kUqoIA.png" /></figure><p><em>Figure 3. Top: causes that change a part of the request. Bottom: causes of a miss when the bytes are identical.</em></p><h3>The traps, one by one</h3><p>Each of these is a reasonable line of code that nobody would flag in review.</p><p><strong>Trap 1. The timestamp in the system prompt</strong></p><ul><li><em>Looks like:</em> &quot;Current time: 2026-11-30 10:42&quot; at the end of the system prompt, so the agent knows the date.</li><li><em>Why it breaks:</em> the system prompt changes on every request, so the system prompt and the entire conversation after it are rewritten every time.</li><li><em>Fix:</em> send the date in the new user turn, at day granularity unless minutes really matter.</li></ul><p><strong>Trap 2. Same content, different bytes</strong></p><ul><li><em>Looks like:</em> tools collected from a dict or a set; JSON dumped without sorted keys; floats formatted by locale; tool results re-rendered from raw data.</li><li><em>Why it breaks:</em> the content is the same, the bytes are not, and the cache only sees bytes.</li><li><em>Fix:</em> sort tools by name, serialize with sorted keys and fixed separators, normalize text, and render each block once.</li></ul><p><strong>Trap 3. Memory in the system prompt</strong></p><ul><li><em>Looks like:</em> &quot;User preferences: units = metric&quot; inside the system prompt, rewritten when the user changes a setting.</li><li><em>Why it breaks:</em> every update rewrites the system prompt and the whole conversation.</li><li><em>Fix:</em> put changes in the turn where they happen.</li></ul><p><strong>Trap 4. A setting flipped for one step</strong></p><ul><li><em>Looks like:</em> tool_choice forced to one tool for a slash command, or a bigger thinking budget for a hard question, then switched back.</li><li><em>Why it breaks:</em> these settings are part of the cache key. Each switch, and each switch back, rewrites the conversation.</li><li><em>Fix:</em> fix settings per session, express one-offs as text, or run them as a side call.</li></ul><p><strong>Trap 5. The tenant name on line one</strong></p><ul><li><em>Looks like:</em> &quot;You are the support assistant for Acme.&quot; followed by 8,000 tokens of instructions shared by every customer.</li><li><em>Why it breaks:</em> no two tenants share a byte, so every new session writes the full prompt.</li><li><em>Fix:</em> shared text first, tenant text after it.</li></ul><p><strong>Trap 6. Rewriting the tool list</strong></p><ul><li><em>Looks like:</em> an MCP server connects and the harness rebuilds tools; a skill list or subagent list embedded in a tool description.</li><li><em>Why it breaks:</em> tools are the first thing in the request. Any change invalidates everything.</li><li><em>Fix:</em> native mid-conversation tool changes, masking, notes for additions, or a planned rebuild.</li></ul><p><strong>Trap 7. The inexact rebuild</strong></p><ul><li><em>Looks like:</em> the hot session in Redis is evicted, and the harness rebuilds the conversation from an event log in Firestore or Postgres.</li><li><em>Why it breaks:</em> the rebuilt request differs from the original by a byte or two, and nobody notices.</li><li><em>Fix:</em> store the rendered blocks you sent, with a hash chain, and verify before sending.</li></ul><p><strong>Trap 8. The sliding window</strong></p><ul><li><em>Looks like:</em> “if the context is over budget, drop the oldest message”.</li><li><em>Why it breaks:</em> once the budget is reached, the start of history changes on every request.</li><li><em>Fix:</em> trim in batches between two watermarks.</li></ul><p><strong>Trap 9. The default lifetime</strong></p><ul><li><em>Looks like:</em> every request uses the 5-minute cache, while users read for ten minutes and test suites run for eight.</li><li><em>Why it breaks:</em> entries expire between requests.</li><li><em>Fix:</em> pick the lifetime from the pauses you actually see.</li></ul><p><strong>Trap 10. Spreading one session across caches</strong></p><ul><li><em>Looks like:</em> round-robin load balancing across regions or accounts; ten subagents started at the same moment; a document pasted as 30 blocks.</li><li><em>Why it breaks:</em> the entry exists, but somewhere else, not yet, or out of reach.</li><li><em>Fix:</em> route by session, warm one request before fanning out, add an anchor breakpoint.</li></ul><blockquote><strong><em>Key idea:</em></strong><em> no single fix covers this list. A harness that handles tool changes perfectly but keeps memory in its system prompt still misses on every memory update.</em></blockquote><h3>Part 4. Design: the request</h3><p>Most cache problems are solved before any clever mechanism, simply by deciding where each piece of content lives.</p><h4>4.1 Order content by how often it changes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_H31UUPeEpYKcowu8e7eJw.png" /></figure><p><em>Figure 4. From most stable on the left to most volatile on the right, with breakpoints between tiers.</em></p><p>With this order, an ordinary step changes nothing but the end. Tiers 1 to 4 are read from cache and only the new turn is processed.</p><h4>4.2 Split the system prompt by who shares it</h4><p>Tier 2 and 3 text often mixes content shared by everyone with content for one customer and content for one session. Order it by how widely it is shared:</p><pre>[ shared instructions: same for every tenant ]   &lt;- breakpoint<br>[ tenant policies: same for one customer     ]   &lt;- breakpoint<br>[ session context: same for one conversation ]   &lt;- breakpoint</pre><p>A new session for a new customer then reads the shared part from cache and writes only its own sections. Sharing never crosses an isolation scope (one organization or workspace), so this does not mix customers’ data.</p><h4>4.3 Put per-turn context in the turn</h4><p>Some content really changes during a session: the date, saved memory, retrieved snippets, the current mode, open files. Send it inside the new user message, in a fixed format:</p><pre>&lt;context&gt;<br>&lt;date&gt;2026-11-30&lt;/date&gt;<br>&lt;memory&gt;preferred_units = imperial&lt;/memory&gt;<br>&lt;/context&gt;<br>What is the boiling point of water at 2,000 m?</pre><p>Two rules make this work:</p><ol><li><strong>Store the message exactly as sent.</strong> Next turn, this message is history. If you stored only the user’s text, history no longer matches and the cache misses.</li><li><strong>Send only what changed.</strong> Values fixed for the whole session belong in tier 3.</li></ol><p>This usually improves quality too. The model sees the newest value last, next to the question, instead of an old value in the system prompt contradicted later in the conversation.</p><h4>4.4 Treat request settings as part of the prompt</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fmpgs_65b7v6WwUYg-FvMg.png" /></figure><p>When a step needs a different setting, prefer these, in order:</p><ol><li><strong>Decide once per session</strong> or per agent type.</li><li><strong>Say it in text</strong> in the new turn: “Use the search tool for this step.” It is a hint, not a guarantee, so measure it on your model.</li><li><strong>Run a side call</strong> with the different settings, outside the main conversation.</li><li><strong>Use a cache-safe provider mechanism</strong> where one exists. Anthropic documents that an effort change sent as a system message inside the conversation keeps the cache on models that support it.</li></ol><h4>4.5 Place breakpoints with a recipe</h4><p>With four slots, place them in this order of priority:</p><ol><li><strong>Last message.</strong> Caches the whole conversation. Never skip this one.</li><li><strong>End of the system prompt.</strong> Survives conversation rewrites such as compaction.</li><li><strong>Anchor at the previous request’s end,</strong> only when this request added many blocks (more than half the lookback window).</li><li><strong>End of the shared and tenant groups,</strong> for multi-tenant sharing.</li></ol><p>Skip any breakpoint whose prefix is below the model’s minimum size: it caches nothing and wastes a slot. When you mix lifetimes, 1-hour breakpoints must come before 5-minute ones.</p><h4>4.6 Normalize at every level</h4><p>The cache sees bytes, so the same meaning must always produce the same bytes. That takes normalization at three levels.</p><p><strong>Level 1: serialization.</strong> The same structure, rendered identically.</p><ul><li>Sort tools by name, not by discovery order.</li><li>Serialize schemas and tool inputs with sorted keys and fixed separators.</li><li>Render each block <strong>once</strong> and reuse the stored bytes. Never re-render history.</li></ul><p><strong>Level 2: content.</strong> Tool output that varies without meaning anything.</p><ul><li>Strip or round values that change on every call but do not matter to the task: request IDs, latencies, “fetched at” timestamps.</li><li>Give unordered results a stable order (search hits by score then ID, file listings by path).</li><li>Truncate long outputs deterministically, by the same rule every time.</li></ul><p>This matters twice: once for the provider cache (stable history), and again for your own tool-result cache (stable keys).</p><p><strong>Level 3: query keys.</strong> For your own exact-match caches (tool results, retrieval, responses), build the key from a normalized form of the input:</p><ul><li>lowercase, collapse whitespace, strip punctuation where it carries no meaning</li><li>replace relative values with absolute ones (“yesterday” becomes a date) or drop them</li><li>canonicalize entity names and IDs (one spelling per customer, product, file path)</li><li>include the context that changes the answer in the key: tenant, permissions, tool or index version</li></ul><p>A normalized exact key is often enough to avoid a semantic cache entirely (9.3).</p><h3>Part 5. Design: the parts that move</h3><p>Layout handles content that stays still. Four kinds of change need their own policy.</p><h4>5.1 Tools, MCP servers, skills and subagents</h4><p>Tool definitions are the first thing in the request, so any change to them invalidates everything. In agents with MCP servers, skills and permission changes, this happens often. There are four ways to express a change:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pdz9JxeE4d2FOgDOvhVV0g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*udfJwVr3vkW-OC6cinYciw.png" /></figure><p><em>Figure 5. Use the native mechanism where it exists. Never express a removal as a note. Let additions pile up as notes, then fold them into one rebuild.</em></p><p>Three details make this work:</p><ul><li><strong>Notes must include the schema.</strong> A note that only names the tool makes the model guess its arguments.</li><li><strong>Rebuild at a cold moment when you can.</strong> After a long pause or a model switch the cache is cold anyway, so pending changes fold in for free.</li><li><strong>Keep catalogs out of tool descriptions.</strong> A spawn_agent tool whose description lists every subagent changes whenever the list does. Put catalogs in the session context, or behind a lookup tool.</li></ul><h4>5.2 Session storage and exact rebuilds</h4><p>Most production harnesses keep two copies of a session: a fast one (Redis, memory) and a durable one (Postgres, Firestore, an event log). When the fast copy is evicted or a different pod picks up the session, the harness rebuilds the conversation from the durable copy.</p><p>The trap is rebuilding from <strong>inputs</strong> (events, raw tool output, database rows) instead of from <strong>what was sent</strong>. Any difference in rendering produces different bytes and a silent full rewrite. Store the rendered blocks instead:</p><ul><li><strong>Hash chain:</strong> h[n] = sha256(h[n-1] + block[n]). One comparison proves the whole history is byte-identical.</li><li><strong>Durable first:</strong> write to the durable store before the fast one, so a crash never leaves the fast copy ahead of the truth.</li><li><strong>Idempotent appends:</strong> key writes by sequence number so a retried write cannot duplicate a message.</li><li><strong>Retries resend the same bytes:</strong> keep the rendered request until it succeeds.</li></ul><h4>5.3 Trimming long histories</h4><p>Any edit to old history is a rewrite: everything after the first changed message is written again. So <strong>how often</strong> you trim matters as much as <strong>what</strong> you trim.</p><p>The batched approach, step by step:</p><ol><li>Set a <strong>high watermark</strong> (your budget) and a <strong>low watermark</strong> (well below it).</li><li>While the context is between them, only append. Every request reads the cache.</li><li>When the context passes the high watermark, clear old tool results, <strong>oldest first</strong>, replacing each with a fixed placeholder, until it is under the low watermark. Never touch the last few messages.</li><li>If the cache is already cold (a long pause, a model switch), trim early when the context is above the midpoint: the rewrite is almost free then.</li><li>If clearing tool output is not enough, summarize.</li></ol><h4>5.4 Uploaded files and images</h4><p>A common pattern: inline the upload on the turn it arrives, strip it on the next turn, and let the agent re-read it through a tool. That costs three times: one rewrite when the file is stripped, a full uncached read each time the agent opens it again, and worse answers because the model no longer sees it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ztErLas6PbtWne6Gx42RcA.png" /></figure><p>A useful reference line looks like [report_q3.pdf, 48 pages, id=f_91: quarterly results; open with read_file]. Keep the bytes in object storage and only the ID in the session record.</p><h4>5.5 Subagents: isolated or shared context</h4><p>A subagent needs context, and there are three ways to give it. Each has a different cache profile and a different effect on quality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7K8LsvixTeQ5QCdYrmuZXA.png" /></figure><p><em>Figure 6. Forked children read the parent’s cache; isolated children share a cache per agent type; a task in the system prompt makes every child pay a full write.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2tCeyvCESjiJUBeGbGKxPg.png" /></figure><p>Rules that hold for all three:</p><ul><li><strong>Never put the task in the subagent’s system prompt.</strong> Every child then has a unique prefix and pays a full write.</li><li><strong>Forking only helps on the same model.</strong> Caches are per model, so a child on a cheaper model reads nothing from its parent. For a cheaper child, use the isolated template.</li><li><strong>Warm before fanning out</strong> (Part 6): one child first, the rest after its first token.</li><li><strong>Return only the result.</strong> Append the child’s final answer to the parent’s history, not its transcript. The parent’s prefix stays intact and its context stays small.</li><li><strong>Do not stuff every child with everything.</strong> “Include all repository context” in each child is a full write per child, multiplied by every parallel child.</li></ul><h4>5.6 Compaction without paying twice</h4><p>Compaction is the one rewrite you cannot avoid in long sessions. How you run the compaction call decides whether it costs a cache read of the history or a full cold pass over it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IO0hv8ANgwFF-A1DLLvijw.png" /></figure><p><em>Figure 7. Top: a new summarizer prompt processes the whole history cold. Middle: continuing the cached conversation reads it from cache. Bottom: the context after compaction keeps tools and system cached.</em></p><p><strong>Run the summary as a continuation of the cached conversation.</strong> Send the exact same tools, system prompt, settings and history, and append one user message: “Summarize the conversation so far for your own future use.” The whole history is a cache read; you pay for the instruction and the summary output.</p><p>The common default does the opposite: a separate summarizer system prompt with the history pasted into one message. That is a new prefix, so the whole history is processed cold.</p><p>For a 150,000-token history, that is the difference between paying for about 150,000 input tokens and paying for about 16,000.</p><p>Five more details:</p><ol><li><strong>Keep the model and settings identical</strong> for the compaction call. A different model, thinking setting or tool_choicemakes the continuation cold.</li><li><strong>Build the new context as tools + system + summary + the last few turns.</strong> Tools and system stay cached; only the summary and recent turns are written.</li><li><strong>Compact when the cache is cold anyway</strong> if the context allows it, and skip compaction when the session is about to end.</li><li><strong>Consider server-side compaction.</strong> Anthropic offers compaction as an API feature (beta): it summarizes when input passes a token trigger you set, and can pause after the summary so you can re-add recent messages before continuing.</li><li><strong>Warm the new context</strong> with a small request right after compacting, so the user’s next turn does not wait on the write.</li></ol><h3>Part 6. Design: time and place</h3><p>Three kinds of miss happen with perfectly stable bytes: the entry <strong>expired</strong>, the entry <strong>does not exist yet</strong>, or the entry <strong>lives somewhere else</strong>.</p><h4>6.1 Choose the lifetime from real pauses</h4><p>Agents pause for reasons the harness does not control: the user reads, a test suite runs, an approval waits. The choice of lifetime is a small calculation over the pauses you actually observe:</p><p>Look at the pauses you actually see between requests, ignoring the short gaps inside a tool loop. If sessions often pause between 5 and 60 minutes, the 1-hour cache is cheaper: one avoided rewrite pays for its higher write price. If almost every pause is under 5 minutes, stay on the default.</p><p>One rule matters in practice: <strong>switch lifetimes only when the cache is cold anyway.</strong> Moving a warm prefix to the longer lifetime writes it again at the higher price.</p><p><strong>Keep-alive.</strong> A tiny request that reads the cache resets its clock. Because a read costs a tenth of a rewrite, a keep-alive pays off whenever there is a reasonable chance (roughly 1 in 10 or better) that the user comes back within the next window.</p><h4>6.2 Warm the cache before fanning out</h4><p>An entry becomes readable only once the first response that wrote it has started. Ten subagents launched at the same moment with the same prefix all miss, and all pay the write.</p><ol><li>Put the shared instructions first, and each subagent’s specific task in its first user message, so all subagents of one type share a prefix.</li><li>Send the first subagent alone.</li><li>When its first token arrives, send the rest in parallel.</li></ol><p>The delay is a second or two. The saving is nine writes.</p><h4>6.3 Route by session, not by request</h4><p>A cache entry lives where it was written: one organization or workspace, one model, and in practice one region or deployment. Load balancing that sends each request of a conversation to the next region turns most requests into cold starts, especially when turns are minutes apart.</p><p>Route each session to one endpoint with rendezvous hashing:</p><ul><li>A session always lands on the same endpoint.</li><li>When an endpoint goes down, only its sessions move. When it recovers, they move back, possibly while their old entry is still warm.</li><li>On OpenAI, give related requests the same prompt_cache_key, and spread a very hot prefix over a few keys rather than one per request.</li><li>Before failing over, compare costs: moving a session costs about one full write of its prefix. For a short outage, a quick retry on the home endpoint can be cheaper.</li></ul><h3>Part 7. The quality trap: cheap but wrong</h3><p>Everything so far keeps the start of the request stable. Some ways of doing that hide information from the model, or leave it holding stale information. The bill improves and the agent gets worse, and a cost dashboard will report it as a win.</p><p>Three rules keep you out of this trap:</p><ol><li><strong>Correctness first, cache second.</strong> When a change cannot be expressed safely, rebuild and pay for the write.</li><li><strong>Removals are never notes.</strong> Use a native mechanism or a rebuild.</li><li><strong>Measure quality next to cost,</strong> every time you change how caching works. Part 8 shows how.</li></ol><h3>Part 8. Measurement: proving it works</h3><p>A single hit-rate number hides almost everything that matters. A useful setup answers three questions: <strong>what did we pay compared with no caching</strong>, <strong>where did each miss come from</strong>, and <strong>did the agent get worse</strong>?</p><h4>8.1 Log one record per request</h4><p>Every provider reports cache usage on each response. Log it, together with a hash of every part of the request:</p><h4>8.2 Find the cause of every miss</h4><p>A miss is a request that read clearly less than the previous request’s cached prefix. For each one, compare it with the previous request of the same session and agent:</p><ol><li><strong>Was it planned?</strong> (You marked it as a deliberate rebuild.) Then it is expected.</li><li><strong>Did a section hash change?</strong> The first changed section is the cause, down to a single tool name.</li><li><strong>Was the gap longer than the lifetime?</strong> Expiry.</li><li><strong>Did the route change?</strong> Routing.</li><li><strong>Did the request grow past the lookback window?</strong> Breakpoint placement.</li><li><strong>None of the above?</strong> Eviction or something on the provider side.</li></ol><p>This turns “the bill went up” into “since Tuesday, 40% of break cost comes from tool:spawn_agent&quot;.</p><h4>8.3 The metrics that matter</h4><ul><li><strong>Cost multiplier:</strong> what you paid for input, divided by what it would have cost with no caching. The headline number.</li><li><strong>Token hit rate:</strong> the share of input tokens read from cache. Weight by tokens, not requests: one big miss matters more than ten small hits.</li><li><strong>Reads per write:</strong> how often each written token is read back. Below 1 (5-minute) or 2 (1-hour), your writes lose money.</li><li><strong>Wasted writes:</strong> tokens written and never read before they expired. High values point to the wrong lifetime or a cold fan-out.</li><li><strong>Misses by cause and by section:</strong> which source to fix first, down to a single tool.</li><li><strong>Cache kept per event:</strong> how much of the prefix survived a tool change, a memory update or a rebuild.</li><li><strong>Rebuild drift:</strong> rebuilt sessions that produced different bytes. Should be zero.</li><li><strong>Cost per successful task:</strong> stops a cheaper but broken strategy from looking good.</li><li><strong>Time to first token,</strong> on hits versus misses. Caching cuts latency as well as cost.</li></ul><h4>8.4 Quality metrics</h4><ul><li><strong>Task success,</strong> from checks on the end state (the file was fixed, the ticket was created).</li><li><strong>Tool-selection accuracy,</strong> did the agent use the right tool.</li><li><strong>Calls to removed or forbidden tools.</strong></li><li><strong>Invalid calls,</strong> unknown tool names or arguments that fail the schema.</li></ul><h4>8.5 Scenarios, baseline, verdict</h4><p>Steady conversations tell you little; misses come from <strong>events</strong>. Script scenarios that include them: a tool added and removed, an MCP server connecting, a hot-cache eviction, a pause longer than the lifetime, a compaction, a model failover, a memory update, a region outage, a new tenant. Each event declares which sections it may change, so anything else is flagged.</p><ul><li>The baseline is always correct, so its quality is the reference.</li><li>Run each scenario several times and compare with confidence intervals. Agent runs are noisy.</li><li><strong>Pass</strong> means cheaper <em>and</em> not worse, within a margin you set in advance.</li></ul><h4>8.6 Keep it from regressing</h4><ul><li><strong>In CI:</strong> run the scenarios on every change and compare with the last release. Fail on a higher cost multiplier, lower quality, or <strong>a new source of misses</strong>. That last check catches the timestamp on the day it is added.</li><li><strong>In production:</strong> track the cache read share per hour against its recent baseline and alert on a sustained drop. Most cache regressions arrive with a deploy.</li></ul><h4>8.7 Telling a regression from noise</h4><p>Agent runs are noisy: the same scenario can take a different number of steps from run to run. Three habits keep comparisons honest:</p><ul><li><strong>Repeat and use intervals.</strong> Run each scenario several times (five is a reasonable start) and compare means with bootstrap confidence intervals, not single runs.</li><li><strong>Decide margins in advance.</strong> For example: the candidate passes if its cost multiplier is lower and its task success is no more than 2 points below the baseline at 95% confidence. Writing this down first stops you from moving the goalposts.</li><li><strong>Compare per scenario, then overall.</strong> An average can hide one scenario that got much worse. Report both, and fail on either.</li></ul><h4>8.8 The evaluation workflow</h4><ol><li><strong>Offline, on every change:</strong> scripted scenarios against a simulator or a cheap model, in CI. Catches new sources of misses before merge.</li><li><strong>Offline, before a release:</strong> the same scenarios against the real provider, several runs each. Confirms cost and quality with real tokens.</li><li><strong>In production, during rollout:</strong> send a share of sessions to the new strategy and compare cost per successful task and the miss causes with the old one.</li><li><strong>In production, always:</strong> read share and break cost by cause on a dashboard, with an alert on a sustained drop.</li></ol><h3>Part 9. Bonus topics</h3><h4>9.1 The provider cache is one layer of six</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eFO1BVUh5hhnRFHBPn4XSA.png" /></figure><h4>9.2 Self-hosted models</h4><p>Inference servers such as vLLM and SGLang reuse prefixes with the same exact-match rule and no write premium. Everything in this guide applies, with two differences:</p><ul><li><strong>The cache lives in one replica’s GPU memory.</strong> The load balancer must route a session to the replica that holds its prefix, or every replica keeps its own cold copy.</li><li><strong>Eviction follows memory pressure, not a clock.</strong> A busy cluster forgets sooner than a quiet one, so lifetime tuning becomes capacity planning.</li></ul><h4>9.3 Semantic caching</h4><p>A semantic cache embeds the incoming request, finds the nearest stored request, and returns the stored answer if the similarity passes a threshold. It is the only layer that can skip the model call entirely, and the only one that can return a wrong answer.</p><p><strong>Why it is risky for agents</strong></p><ul><li>Each agent step depends on the whole conversation, the tools available and the results so far. Two similar-looking requests rarely share a correct answer.</li><li>Similarity is not equivalence. One production study reports a request for ATM locations answered with loan-balance instructions at 80.9% confidence, and false-positive rates up to 99% for some embedding models at a 0.7 threshold.</li><li>A false hit raises no error. The user just gets a confident wrong answer.</li></ul><p><strong>If you use one, design it like this</strong></p><ol><li><strong>Only at stateless entry points:</strong> the first turn of an FAQ or support assistant, or a fixed retrieval query. Never mid-session agent steps.</li><li><strong>Try an exact cache on a normalized key first</strong> (4.6). It catches most repeats with no false hits.</li><li><strong>Scope the key:</strong> tenant, permissions, tool and index versions, and the date if the answer depends on it.</li><li><strong>Do not use one global threshold.</strong> Recent work learns a threshold per cached entry and bounds the error rate to a target you set (vCache, ICLR 2026); others add a reranker that scores each query and candidate pair before accepting a hit.</li><li><strong>Measure the false-hit rate</strong> on labelled pairs before launch and keep sampling hits in production. Hit rate alone is the wrong metric.</li><li><strong>Short lifetimes,</strong> and invalidate on any change to the underlying data.</li></ol><h4>9.4 What recent work found</h4><p>A few recent studies and write-ups, and what they add to this guide:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6H8_Q3HFtO-gCIsomRi6IA.png" /></figure><h3>Cheat sheet</h3><p>Take this into your next design review.</p><p><strong>Request layout</strong></p><ul><li>Tools, shared instructions, session context, history, new turn, in that order</li><li>Shared text before tenant text before session text, with a breakpoint after each group</li><li>No dates, IDs or other volatile values before the new turn</li><li>Sorted tools, canonical JSON, normalized text, each block rendered once</li><li>Breakpoints: last message, end of system, an anchor when a turn adds many blocks</li></ul><p><strong>Changes during a session</strong></p><ul><li>Date, memory and retrieved context sent in the new turn and stored as sent</li><li>Request settings fixed per session; one-offs as text or side calls</li><li>Tool removals through a native mechanism or a rebuild, never a note</li><li>Tool additions as notes with their schema, folded into a rebuild at a cold moment</li><li>History trimmed in batches between two watermarks</li><li>Uploads decided once by size: inline if small, a reference and a tool if large</li></ul><p><strong>Storage, time and place</strong></p><ul><li>Sessions stored as rendered blocks with a hash chain, verified on rebuild</li><li>Retries resend the same bytes</li><li>Lifetime chosen from observed pauses, switched only when the cache is cold</li><li>One request warms a shared prefix before a fan-out</li><li>Sessions routed to one endpoint, never spread per request</li></ul><p><strong>Measurement</strong></p><ul><li>Usage and section hashes logged for every request</li><li>Every miss classified by cause and section</li><li>Quality measured next to cost, against a baseline that always rebuilds</li><li>A CI check that fails on new sources of misses</li></ul><h3>Closing</h3><p>Prompt caching is one of the largest cost levers in an agent product, and one of the easiest to lose without noticing. None of the fixes are exotic. They come down to three habits: decide where each piece of content lives, decide when the start of the request is allowed to change, and measure cost and quality together so you notice when something slips.</p><p>In the next post I describe <strong>cache_it</strong>, an open-source project that turns this guide into tools: a benchmark that scores any harness on cost and quality across all ten sources of misses, and a small library with one independent fix for each. The code is at <a href="https://github.com/darshanlahamage/cache_it">github.com/darshanlahamage/cache_it</a>.</p><h3>Sources</h3><ul><li><a href="https://platform.claude.com/docs/en/build-with-claude/prompt-caching">Anthropic: prompt caching</a></li><li><a href="https://platform.claude.com/docs/en/build-with-claude/compaction">Anthropic: compaction</a></li><li><a href="https://developers.openai.com/api/docs/guides/prompt-caching">OpenAI: prompt caching</a></li><li><a href="https://arxiv.org/html/2601.06007">Don’t Break the Cache: An Evaluation of Prompt Caching for Long-Horizon Agentic Tasks</a></li><li><a href="https://langchain.com/blog/deep-agents-prompt-caching">LangChain: Prompt Caching with Deep Agents</a></li><li><a href="https://pi.dev/packages/pi-prefix-cache-compaction">pi-prefix-cache-compaction</a></li><li><a href="https://dev.to/akashy/my-agent-orchestrator-burned-1-2m-opus-tokens-per-task-heres-the-postmortem-2k7g">My agent orchestrator burned 1.2M Opus tokens per task: the post-mortem</a></li><li><a href="https://martinfowler.com/articles/orchestrator-tax.html">Martin Fowler: The Orchestrator’s Tax</a></li><li><a href="https://arxiv.org/abs/2502.03771">vCache: Verified Semantic Prompt Caching</a></li><li><a href="https://www.infoq.com/articles/reducing-false-positives-retrieval-augmented-generation">InfoQ: Reducing false positives in semantic caching</a></li></ul><p>Figure 2 is computed from the token counts shown in it, at Anthropic 5-minute prices. It is an illustration, not a measurement.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09a1af04ebcd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A guide for Python Monorepo using PantsBuild]]></title>
            <link>https://medium.com/@lahamagedarshan61/a-guide-for-python-monorepo-using-pantsbuild-3ca86562c504?source=rss-b26a1f5dc806------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ca86562c504</guid>
            <category><![CDATA[pantsbuild]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[monorepo]]></category>
            <dc:creator><![CDATA[Darshan sanjay lahamage]]></dc:creator>
            <pubDate>Tue, 01 Jul 2025 09:44:13 GMT</pubDate>
            <atom:updated>2025-07-01T09:44:13.447Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>What is a Monorepo?</strong></blockquote><p>A <strong>monorepo (monolithic repository)</strong> is a single version-controlled repository that holds the code for multiple projects or services. Instead of maintaining separate repositories for each module, everything is kept together — apps, libraries, tooling, and infrastructure. Popular with large-scale projects and engineering teams (e.g., <strong>Google, Meta, Uber</strong>).</p><blockquote><strong>Advantages:</strong></blockquote><p><em>Unified tooling : one build system, one linter setup, one CI pipeline.</em></p><p><em>Code sharing : easy to reuse modules across services.</em></p><p><em>Atomic changes : update multiple modules in a single commit.</em></p><p><em>Simplified dependency management : shared and also isolated requirements using lockfiles.</em></p><p><em>Better visibility </em>: <em>all teams can see and work on all parts of the codebase.</em></p><blockquote><strong>Why Pantsbuild?</strong></blockquote><ul><li>Designed specifically for <strong>Python-first monorepos</strong>, but also supports other languages.</li><li>Requires minimal boilerplate compared to Bazel.</li><li>Fast: uses aggressive caching, concurrency, and fine-grained invalidation.</li><li>Handles Python dependency inference, testing, Docker builds, and packaging with simple config.</li><li>Easy adoption: can be added incrementally to existing repos.</li></ul><blockquote><strong>Getting Started :</strong></blockquote><p>Alright, before jumping into Pants setup and config, let’s take a minute to understand what kind of monorepo we’re working with in this guide. We’ll assume you’re working on a <strong>machine learning-focused project</strong>, but you’re <strong>also building a web/API app</strong> around it. Maybe you have multiple ML models, shared utility libraries, a frontend or FastAPI app, and want to build and test everything modularly and efficiently. That’s exactly what Pants helps with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*GYr5gO-t7m0wU2XC8Ca3sA.png" /></figure><blockquote><strong>Installing Pants (v2.26):</strong></blockquote><p>Before we write a single BUILD file or run any Pants command, we need to get our environment ready. As per latest Pants version it supports <strong>Python 3.7 or higher. </strong>Pants uses your system Python to bootstrap itself (but builds run in isolated environments internally).</p><p><strong><em>(Optional)</em> </strong>Create a Virtual Environment While Pants doesn’t require a virtual environment to run, it’s a good idea to create one to isolate your tooling, especially if you’re working on multiple projects. To download and run follow this official link:</p><p><a href="https://www.pantsbuild.org/stable/docs/getting-started/installing-pants">Installing Pants | Pantsbuild</a></p><p>after you get this done, check the version and we are good to go.</p><blockquote><strong>Pants.toml — global configuration</strong></blockquote><p>once you install Pants, it doesn’t magically know how your project is laid out or what features you’re using. That’s where pants.toml comes in. This file tells Pants:</p><p>backend_packages: Enable only what you <strong>actually use</strong>.<br> <em>→ ML project? You need </em><em>python, </em><em>black, </em><em>mypy.<br> → Docker? Add </em><em>docker, </em><em>shell.</em></p><p>[source] – this defines <strong>which folders Pants should treat as roots</strong> for your Python packages. &quot;src&quot;, &quot;services&quot;, &quot;tests&quot; all become Python import roots. Using &quot;/&quot; is the simplest way to say <strong><em>“every folder at top-level could be a code root.”</em></strong></p><p>[python] – interpreter_constraints: Tells Pants what Python version(s) your code supports. Match this to your local python version to avoid mismatch errors.</p><p>[python.resolves] — You can define <strong>one lockfile</strong> for everything, or one <strong>per module</strong>. Great when different modules need conflicting or isolated dependencies (e.g., ML vs APIs).</p><p>[python.resolves_to_interpreter_constraints] — If your modules use <strong>different Python versions</strong>, map the resolve name to its version here. <strong><em>But you need to have the venv of the specified interpreter, pants find it through system path </em></strong>(make sure you add it to your path).</p><p>[python-repos] – Optional: use when hosting private wheels or working offline. <em>Leave this out unless you host local Python packages.</em></p><p>[test], [coverage-py], [pytest] — Sets up testing defaults. Coverage is enabled and outputs a JSON report. Pytest args are customizable, use your team’s standard.</p><p>[docker] – Needed only if you’re using docker_image() targets to build and/or publish the docker files. It let Pants build Docker images without manual scripting. <em>( we will soon discuss issues you might face while building docker files using pants, don’t worry !)</em></p><pre>[GLOBAL]<br>pants_version = &quot;2.26.0&quot; # Required. Locks your project to a specific Pants version.<br>unmatched_build_file_globs = &quot;ignore&quot; # Silences warnings if Pants finds BUILD files in unknown folders.<br>colors = true   # Keep it true for readable terminal output.<br>pythonpath = [&quot;%(buildroot)s/pants-plugins&quot;]  # Needed only if you&#39;re writing custom Pants plugins. Safe to leave empty otherwise.<br>backend_packages = [<br>  &quot;pants.backend.python&quot;,<br>  &quot;pants.backend.shell&quot;,<br>  &quot;pants.backend.docker&quot;,<br>  &quot;pants.backend.build_files.fmt.black&quot;, # format BUILD files <br>  &quot;pants.backend.python.lint.docformatter&quot;, # format docstrings<br>  &quot;pants.backend.python.lint.autoflake&quot;, # remove unused imports<br>  &quot;pants.backend.python.lint.black&quot;, # format python code<br>  &quot;pants.backend.python.lint.flake8&quot;, # enforce code style<br>  &quot;pants.backend.python.lint.isort&quot;, # sort imports<br>  &quot;pants.backend.python.typecheck.mypy&quot;,  # static type check <br>]<br># this tells Pants to ignore certain folders/files completely.<br>pants_ignore.add = [<br>  &quot;.venv&quot;, &quot;__pycache__&quot;, &quot;*.pyc&quot;,<br>  &quot;.mypy_cache&quot;, &quot;.pytest_cache&quot;,<br>  &quot;.git&quot;, &quot;.idea&quot;, &quot;.vscode&quot;,<br>  &quot;.pants.d&quot;, &quot;.pants.workdir&quot;,<br>  &quot;dist&quot;, &quot;wheels&quot;,<br>]<br>[source]<br>root_patterns = [&quot;/&quot;]<br><br>[docker]<br>use_buildx = true<br>build_args = [&quot;SHORT_SHA&quot;]  # dynamic git commit SHA  - env vars tagging to all docker iamges <br>env_vars = [&quot;DOCKER_CONFIG=%(env.HOME)s/.docker&quot;, &quot;HOME&quot;, &quot;USER&quot;, &quot;PATH&quot;]<br>tools = [<br>  # these are required for GCloud authentication if you are uploading docker iamges to GCP <br>  &quot;docker-credential-gcloud&quot;,<br>  &quot;dirname&quot;,<br>  &quot;readlink&quot;,<br>  &quot;python3.10&quot;,<br>]<br><br>[python]<br>interpreter_constraints = [&quot;==3.10.0&quot;]<br>enable_resolves = true  # Enables multiple lockfiles across modules which is important in monorepos.<br>default_resolve = &quot;global&quot; # Lockfile used by default for targets that don’t explicitly override it<br><br># lockfiles are used to resolve dependencies<br>[python.resolves]    #this tells pants where to look for lockfiles of particular module or global<br>global = &quot;global.lock&quot;<br>model1 = &quot;src/ml/model1/model1.lock&quot;<br>services = &quot;services/api_app/api_app.lock&quot;<br>tests = &quot;tests/test.lock&quot;<br>ci = &quot;ci.lock&quot;     # this is the lockfile generated from global reqs in our case which will have dependencies required for all linters and formatters <br><br>[python.resolves_to_interpreter_constraints] # Only use this if you&#39;re running mixed Python versions in your repo for any folder.<br>services = [&quot;==3.12.10&quot;] # this approach allows us gradually migrating to diff versions rather than changing config globally<br><br># Pants tries to guess imports and match them to dependencies. If it fails do this:-<br>[python-infer]  <br>unowned_dependency_behavior = &quot;ignore&quot;  # continue without error<br><br>[python-repos]<br>find_links = [&quot;%(buildroot)s/wheels&quot;]<br>path_mappings = [&quot;WHEELS_DIR|%(buildroot)s/wheels&quot;]<br><br>[test]    # configures the behavior of the pants test goal<br>output = &quot;all&quot;  # pants only shows output for failed tests. You can change this by setting output to one of &quot;all&quot;, &quot;failed&quot;, or &quot;never&quot;<br>report = false  # controls whether Pants generates a JUnit XML test report.<br>use_coverage = true  # permanently use coverage<br><br>[coverage-py] <br>report = &quot;json&quot;<br>global_report = true <br><br>[pytest]<br>args = [&quot;-vv&quot;, &quot;-s&quot;, &quot;-W ignore::DeprecationWarning&quot;, &quot;--no-header&quot;] # Change verbosity or add plugins in args as needed.<br><br># linters and formatters<br>[black] <br>install_from_resolve = &quot;ci&quot; # lets linters run with controlled dependencies.<br>interpreter_constraints = [&quot;==3.10.0&quot;]<br><br>[flake8]<br>args = [&quot;--extend-ignore=E203,E231,E501,F841&quot;]<br><br>[mypy]<br>install_from_resolve = &quot;ci&quot;<br>interpreter_constraints = [&quot;==3.10.0&quot;]<br>args = [ &quot;--pretty&quot;, &quot;--install-types&quot;, &quot;--non-interactive&quot;, ... ]<br><br>[anonymous-telemetry]  # Do not send usage data to Pants developers<br>enabled = false<br></pre><blockquote><strong>Now get onto writing BUILD files</strong></blockquote><p>A BUILD file is basically a <strong>declarative manifest</strong>. Each folder that contains code should usually have its own BUILD file. It tells Pants :- “This folder contains Python source files”, “Here are the requirements for this module”, “Here’s a test target”, “Build a wheel from this code” , And more…….</p><p><strong><em>General Rules We Follow in Our Monorepo — every source folder gets a BUILD file : —</em></strong></p><p><strong><em>example</em></strong></p><p>→src/ml/model1/BUILD<br> → services/api_app/BUILD<br> → tests/BUILD</p><ul><li>Every directory containing .py files must have a BUILD file with at least python_sources.</li><li>Every directory containing test_*.py must have a BUILD file with python_tests.</li><li>If tests depend on non-Python files (like test data), use a files target.</li></ul><p>Each top-level module should define:</p><ul><li>A files target to reference all files in that module.</li><li>A python_requirements target (if it has a requirements.txt).</li><li>Optional docker_image targets if that module builds Docker image</li></ul><blockquote><strong>1. src/ml/model1/BUILD &amp; src/ml/shared_utils/BUILD</strong></blockquote><p>Each directory that contains Python source code (.py files, excluding tests) must have a BUILD file. These files <strong>must include at least a </strong><strong>python_sources target</strong>. This target tells Pants :</p><ul><li>That this directory is a valid Python source root</li><li>To run Python-specific checks like formatting (Black), docstring formatting (docformatter), code cleanup (autoflake), linting (flake8), and static typing (mypy)</li><li>To infer dependencies from import statements</li></ul><p>In our monorepo, modules like model1 and shared_utils include this, and also define:</p><ul><li>A files target (model1_files, etc.) that includes sources=[&quot;**/*&quot;]. This makes it easy to use this entire module’s contents as a dependency in other targets, such as when building Docker images or wheel packages.</li><li>A python_requirements target, which tells Pants to install the module’s dependencies listed in requirements.txt. (optional — This is where you can optionally specify platform-specific overrides. For example, to use tensorflow-macos on M1 Macs )</li></ul><pre># ---------src/ml/model1/BUILD<br>files(<br>    name=&quot;model1_files&quot;,<br>    sources=[&quot;**/*&quot;],<br>)<br><br>python_sources(<br>    name=&quot;model1_src&quot;,<br>    resolve=&quot;model1&quot;, # this is used to resolve third party dependecies in python files<br>    dependencies=[                   # code on which the python files in the module dependes (like importing)<br>        &quot;src/ml/shared_utils: shared_utils_src&quot;,       # internal shared code<br>    ],<br>)<br><br>python_requirements(<br>    name=&quot;model1_reqs&quot;,<br>    source=&quot;requirements.txt&quot;,<br>    resolve=&quot;model1&quot;,   # lockfile name should be exactly same as declare in pants.toml python.resolves<br>    overrides={<br>        &quot;tensorflow&quot;: {<br>            &quot;requirements&quot;: (<br>                &quot;tensorflow==2.13.0; sys_platform != &#39;darwin&#39; or platform_machine == &#39;x86_64&#39;&quot;,<br>                &quot;tensorflow-macos==2.13.0; sys_platform == &#39;darwin&#39; and platform_machine == &#39;arm64&#39;&quot;,<br>            ),<br>        },<br>    },<br>)<br><br>python_distribution(  # Builds a reusable wheel for the model code.<br>    name=&quot;model1_dist&quot;,<br>    dependencies=[&quot;:model1_src&quot;, &quot;:model1_reqs&quot;],<br>    provides=setup_py(<br>        name=&quot;model1-encoder&quot;,<br>        version=&quot;0.1.0&quot;,<br>        description=&quot;Model1 image encoder and trainer&quot;,<br>        author=&quot;Platform ML Team&quot;,<br>    ),<br>    wheel=True,<br>    sdist=True,<br>    wheel_config_settings={&quot;--global-option&quot;: [&quot;--python-tag&quot;, &quot;py310&quot;]},<br>)</pre><pre># ------src/ml/shared_utils/BUILD<br>python_sources(<br>    name=&quot;shared_utils_src&quot;,<br>    resolve=&quot;model1&quot;,<br>)</pre><blockquote><strong>tests/BUILD</strong></blockquote><p>Any directory that contains tests (i.e., files like test_*.py) must have a BUILD file with a python_tests target. This tells Pants to:</p><ul><li>Discover and run tests using pytest</li><li>Apply the same Python formatting and linting rules</li><li>Infer dependencies based on imports (though we often explicitly declare them)</li></ul><p>If your tests rely on external files — for example, test datasets, config files, or test images — you should also define a files target in the same BUILD file. That target should list all the files needed during testing. Then, pass that files target as a dependency to the python_tests target.</p><pre># -------tests/BUILD<br>files(<br>    name=&quot;tests&quot;,<br>    sources=[&quot;**/*&quot;],<br>)<br>python_tests(     # makes sure Pants runs pytest on the test files.<br>    name=&quot;unit_tests&quot;,<br>    sources=[&quot;test_*.py&quot;], # you can also change the file glob pattern and inlcude that pattern in sources of python_tests target<br>    resolves=parametrize(&quot;test&quot;, &quot;model1&quot;, &quot;services&quot;)<br>    dependencies=[<br>        &quot;src/ml/model1: model1_files&quot;,<br>        &quot;services/api_app: api_app_files&quot;,<br>        &quot;src/ml/shared_utils:shared_utils_src&quot;,<br>    ],<br>)<br># if you have Config file for pytest<br>python_test_utils(<br>    name=&quot;test_utils&quot;,<br>    sources=[&quot;conftest.py&quot;],<br>    resolve=&quot;test&quot;,<br>)</pre><blockquote><strong>services/api_app</strong></blockquote><p>All other targets we have already discussed, now will discuss docker and python distribution :</p><p>python_distribution — target, named api_dist, tells Pants to build a Python distribution (specifically, a wheel and a source distribution) from the code and dependencies specified. provides=setup_py(...): This block defines the metadata that would typically go into a setup.py file for a traditional Python package. Pants uses this information to generate the necessary metadata for your wheel and sdist.</p><p>python_distribution : if another module (e.g., module_a) needs to import code from your api-app, it can declare a dependency on api_dist</p><p>e.g —</p><pre># ----sample usage<br>python_sources(<br>    name=&quot;xyz&quot;,<br>    sources=[&quot;**/*.py&quot;],<br>    dependencies=[<br>        &quot;//path/to/:api_dist&quot;, # Depend on the distribution target<br>    ],<br>    resolve=&quot;xyz&quot;, # this module can use its own resolve<br>)</pre><p>docker_image — if the module is packaged into a container Pulls all source files via the files target</p><ul><li>Builds an image using a Dockerfile in source</li><li>Tags the image using latest and SHORT_SHA(dynamic tag git commit sha — env var which is set in our global .<em>toml </em>declaration for all docker images)</li><li>Pushes to the specified container registry</li></ul><blockquote>If you are <strong><em>using any cloud provide container registry</em></strong>, <strong><em>suppose GCP/AWS</em></strong> artifact registry you need to authenticate it first locally (assuming you have necessary permissions). You can see in our .toml config file —</blockquote><blockquote>env_vars = [“DOCKER_CONFIG=%(env.HOME)s/.docker”, “HOME”, “USER”, “PATH”] — this tells pants to use ~/.docker/config.json for auth</blockquote><blockquote>&quot;PATH&quot;: <strong>This is important.</strong> It passes your shell&#39;s PATH environment variable into the Pants sandbox. This is how Pants finds the executables you listed in [docker].tools (like gcloud, dirname, readlink, python3). If you don&#39;t pass PATH, Pants won&#39;t be able to find these tools</blockquote><blockquote>GCloud authentication requires tools -dirname, readlink and python3</blockquote><pre># ------services/api_app<br>files(<br>    name=&quot;api_app_files&quot;,<br>    sources=[&quot;**/*&quot;],<br>)<br><br>python_sources(<br>    name=&quot;api_src&quot;,<br>    resolve=&quot;services&quot;,<br>)<br><br>python_requirements(<br>    name=&quot;api_reqs&quot;,<br>    source=&quot;requirements.txt&quot;,<br>    resolve=&quot;services&quot;,<br>)<br><br>docker_image(<br>    name=&quot;api_app_docker&quot;,<br>    source=&quot;Dockerfile&quot;,<br>    dependencies=[<br>        &quot;:api_app_files&quot;,  # includes files from services module that will eb required for docker build<br>        &quot;src/ml/model1:model1_files&quot;, # includes files from model1 files also <br>    ],<br>    image_tags=[&quot;latest&quot;, &quot;{build_args.SHORT_SHA}&quot;], # tags for the image<br>    repository=&quot;gcr.io/my-project/api-app&quot;,<br>    registries=[&quot;gcr.io&quot;], # you can use any artifact registry<br>)<br><br>python_distribution(<br>    name=&quot;api_dist&quot;,<br>    dependencies=[&quot;:api_src&quot;, &quot;:api_reqs&quot;],<br>    provides=setup_py(<br>        name=&quot;api-app&quot;,<br>        version=&quot;0.3.1&quot;,<br>        description=&quot;Offer-serving backend API&quot;,<br>        author=&quot;Backend Team&quot;,<br>    ),<br>    wheel=True,<br>    sdist=True,<br>)</pre><blockquote><strong>Pants goals :</strong></blockquote><p>For packaging and publishing <strong>dockerfiles </strong>: —</p><ul><li>SHORT_SHA=$(git rev-parse --short HEAD) <strong>pants package</strong> {module}:{docker-target-name} -&gt; build docker image locally, this is equivalent to running docker build with all the necessary arguments</li><li>SHORT_SHA=$(git rev-parse --short HEAD) to run and upload locally we need to pass git commit short SHA env var that will be used to tag docker image</li><li>SHORT_SHA=$(git rev-parse --short HEAD) <strong>pants publish</strong> {module}:{docker-target-name} -&gt; build docker image locally &amp; push to its remote registry; this is equivalent to running docker build and then docker push with all the necessary arguments</li><li>e.g — SHORT_SHA=$(git rev-parse --short HEAD) pants {publish/package} services/api_app:api_app_docker</li></ul><p>Generating lockfiles : These are the files pants uses to handle third party requirements in a isolated environment</p><ul><li>pants generate-lockfiles --resolve={module} -&gt; create and update the module&#39;s lockfile (needs to be run if you update the module&#39;s requirements.txt). Make sure module name matches the name in pants.toml resolves. e.g pants generate-lockfiles --resolve=model1 <strong>, </strong>this will create lockfile<strong> </strong>model1.lock<strong> </strong>using the requirements file passed in<strong> </strong>python_requirementstarget in the <em>BUILD </em>file of model1 module.</li></ul><p>Goals for linting and formatting :- pants {goal_name} {module_name}:: for running on specific module. pants {goal_name} :: run on entire repo.</p><ul><li>pants tailor {module_name}:: check and auto-generate BUILD file</li><li>pants test {module_name}:: Run tests.</li><li>pants lint {module_name}:: runs tools that check code quality/styling etc, without changing that code</li><li>pants check {module_name}:: Run type checking — mypy in our case. You can tell Pants to skip running MyPy on certain files by adding skip_mypy=True to the relevant targets.</li><li>pants fix {module_name}:: Autofix source code. (black and docformatter). This goal runs tools that make ‘semantic’ changes to source code, where the meaning of the code may change.</li><li>pants fmt {module_name}:: This goal runs tools that make ‘syntactic’ changes to source code, where the meaning of the code doesn’t (usually) change.</li></ul><blockquote><strong><em>What’s next?</em></strong></blockquote><ul><li>In this article we tried to cover set up for your python monorepo using pantsbuild. Best methods to write your global config and BUILD files.</li><li>But this is not the end, next we will cover how to use pants in CI, how to implement caching for CI, etc.</li><li>So stay tune…….</li></ul><p>If you found this article helpful, give it a clap 👏 and share it with your developer friends. I’d love to hear about your experiences and suggestions setting up Pants in the comments, thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ca86562c504" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI and ML — The Future Of Human Beings.]]></title>
            <link>https://medium.com/@lahamagedarshan61/ai-and-ml-the-future-of-human-beings-d0ad1a053beb?source=rss-b26a1f5dc806------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0ad1a053beb</guid>
            <dc:creator><![CDATA[Darshan sanjay lahamage]]></dc:creator>
            <pubDate>Sat, 18 Dec 2021 15:10:15 GMT</pubDate>
            <atom:updated>2021-12-18T15:10:15.507Z</atom:updated>
            <content:encoded><![CDATA[<h3>AI and ML — The Future Of Human Beings.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*6M4lAeBWIvnQ9KQ07bNh5Q.png" /></figure><blockquote>Artificial Intelligence and Machine Learning could be a hot topic within the technical school trade. maybe over our daily lives computing (AI) is impacting the business world a lot of. McKinsey (management consulting firm) estimates that AI could deliver a further economic output of around US$13 trillion by 2030, increasing world value by concerning one.2 % annually. this may in the main return from substitution of labour by automation and magnified innovation in product and services.</blockquote><h4>A Brief History of computing</h4><p>Here’s a quick timeline of the past six decades of however AI evolved from its beginning.</p><blockquote>1956 — John McCarthy coined the term ‘artificial intelligence’ and had the primary AI conference.</blockquote><blockquote>1969 — Shakey was the primary all-purpose mobile golem designed. it’s currently able to do things with a purpose vs. simply an inventory of directions.</blockquote><blockquote>1997 — Supercomputer ‘Deep Blue’ was designed, and it defeated the globe champion player in a very match. it absolutely was a vast milestone by IBM to make this massive pc.</blockquote><blockquote>2002 — The initial commercially winning robotic home appliance was created.</blockquote><blockquote>2005–2019 — Today, we’ve got speech recognition, robotic method automation (RPA), a saltation golem, sensible homes, and far a lot of to return.</blockquote><h4>What is Artificial Intelligence ?</h4><p>According to Stanford investigator, John McCarthy, “Artificial Intelligence is that the science and engineering of creating intelligent machines, particularly intelligent pc programs. computing is expounded to the similar task of exploitation computers to know human intelligence, however AI doesn’t ought to confine itself to ways that area unit biologically noticeable.”</p><p>Simply put, AI’s goal is to create computers/computer programs sensible enough to imitate the human mind behaviour.</p><p>Knowledge Engineering is a necessary a part of AI analysis. Machines and programs ought to have bountiful info associated with the globe to usually act and react like people at large. AI should have access to properties, categories, objects and relations between all of them to implement data engineering. AI initiates logic, problem-solving and analytical reasoning power in machines, that is far troublesome and a tedious job.</p><p>AI services is classified into Vertical or Horizontal AI</p><h4>What is Vertical AI?</h4><blockquote>These area unit services specialise in the one job, whether or not that is planning meeting, automating repetitive work, etc. Vertical AI Bots performs only one job for you and copulate therefore well, that we’d mistake them for somebody’s.</blockquote><h4>What is Horizontal AI?</h4><blockquote>These services area unit such they’re able to handle multiple tasks. there’s no single job to be done. Cortana, Siri and Alexa area unit a number of the samples of Horizontal AI. These services work a lot of massively because the question and answer settings, like “What is that the temperature in New York?” or “Call Alex”. They work for multiple tasks and not only for a specific task entirely.</blockquote><blockquote>AI is achieved by analysing however the human brain works whereas determination a problem then exploitation that analytical problem-solving techniques to make complicated algorithms to perform similar tasks. AI is an automatic decision-making system, that unendingly learn, adapt, recommend and take actions mechanically. At the core, they need algorithms that area unit able to learn from their expertise. this is often wherever Machine Learning comes into the image.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*-ksZp4zGF6TpBzW4DvPkmA.jpeg" /></figure><h4>WHAT IS MACHINE LEARNING?</h4><blockquote>Artificial Intelligence and Machine Learning area unit abundant trending and additionally confused terms these days. Machine Learning (ML) could be a set of computing. metric capacity unit could be a science of planning and applying algorithms that area unit able to learn things from past cases. If some behaviour exists in past, then you’ll predict if or it will happen once more. suggests that if there are not any past cases then there’s no prediction.</blockquote><blockquote>ML is applied to resolve robust problems like mastercard fraud detection, change self-driving cars and face detection and recognition. metric capacity unit uses complicated algorithms that perpetually tell over giant knowledge sets, analyzing the patterns in knowledge and facilitating machines to reply completely different things that they need not been expressly programmed. The machines learn from the history to supply reliable results. The metric capacity unit algorithms use technology and Statistics to predict rational outputs.</blockquote><h4>Current Scenario Of AI</h4><p>AI-enhanced technologies and solutions area unit currently a lot of wide obtainable than before across industries, although they’re not essentially low-cost to implement.</p><p>Voice-based assistants area unit at the forefront of the AI adoption method in industries as numerous because it, automotive, and retail.</p><p>Smaller-scale AI as seen in chatbots permits smaller brands to save lots of resources and improve client satisfaction.</p><p>An increasing variety of AI-enhanced tools area unit obtainable as software-as-a-service (SaaS).</p><p>Mobile devices and apps became one amongst the best ways in which to deploy AI technologies across industries, whether or not it’s within the sort of voice assistants, sensible watching and management, customized looking experiences, or warehouse management apps.</p><p>AI is gift in intelligent applications, somatic cell networks, AI platforms as a service, and AI cloud services.</p><p>Emerging AI technologies embody increased intelligence, that seeks to boost human intelligence and edge AI, wherever AI algorithms area unit processed domestically while not the necessity for a web association (such as some varieties of face recognition).</p><p>According to the synthetic Intelligence Index Report, AI computing power keeps doubling each three 4 months.</p><h4>State Of AI and ML in INDIA</h4><p>India is one of the most lucrative countries to invest in technology transactions worldwide. Being one of the fastest-growing hubs of business around the world, India has a lot of scope for Artificial Intelligence. Over the last few years, the youth has focused its interest more on technology, and developments in the field. As a result of this shift of thought in youngsters, the government of India has realized that it is a vital part of the country’s economic development. The rise of Artificial Intelligence in India can help it bring about a transformation in various domains, such as education, health, agriculture, and transportation.</p><p>In just two short years, the <strong>growth of </strong><a href="https://www.geeksforgeeks.org/artificial-intelligence-an-introduction/">Artificial Intelligence</a><strong> in India</strong> will be so significant that some reports suggest it will increase the rate of innovation in the country by over <strong>220%</strong>. <em>NITI Aayog’s</em> paper on Artificial intelligence “National Strategy for Artificial Intelligence” says that India will require a unique national strategy that bases itself on a framework that adapts itself according to India’s requirements and aspirations as a country. In attempting to show that it is serious about India’s future in the realm of Artificial Intelligence, in May 2019, NITI Aayog proposed a scheme to develop an institutional framework in India. The circulation of a cabinet note to provide <strong>Rs 7500 Crore</strong> of funding has taken place. Its short-term plan is to create a cloud computing platform called <strong><em>AIRAWAT</em></strong> and research institutes. Then to set up a high-level task force to ensure the implementation of Artificial Intelligence in India. If India is to compete in the global AI race, India must take strides in the fields such as education and research. Currently, the number of PhDs that India is producing in areas such as Artificial Intelligence and machine learning are too few. Hopefully, this initiative by NITI Aayog is a step in the right direction.</p><p>Artificial Intelligence has the potential to <strong>drive massive changes in the economy</strong>. By automating multi-layered physical tasks that require adaptability across various industries. Accenture’s recent AI research report provides a framework to assess the economic impact of Artificial Intelligence on G20 countries. It predicts that catching up with this technological trend will expedite India’s annual growth rate by <strong>1.3 percentage by 2035</strong>, which means that it could potentially add <strong>$957 Billion</strong> to India’s current gross value in the same year. NITI Aayog has analyzed a large number of sectors in the new national Artificial Intelligence strategy document to understand where AI can be most effective. It has taken a conscious decision to focus on a select set of sectors where private sector-led initiatives are not the only actions that lead to achieving a desirable societal outcome.</p><p>Sure, <strong>India’s road to success in the realm of Artificial Intelligence looks well lit</strong>, and it will, without a doubt, be very propitious for the country.</p><h4>Future Scope For Students</h4><blockquote>As the AI and ML technologies are growing day by day , there are many career oportunities for students . The adaptation rate of new AI and ML technologies are high. Artificial intelligence (AI) hopes to produce some of this century’s most important and revolutionary inventions. The products of the new AI revolution are self-driven vehicles, robot assistance and digital disease diagnostics that will affect how we live and function. And as demand for qualified engineers has more than doubled in recent years, professionals who want to take a lead in research and development in AI are providing endless opportunities. AI &amp; ML engineering will produce an immense amount of career opportunities for the future.</blockquote><p>Some of the career options for students:</p><ol><li>Data Scientist</li><li>Machine Learning Engineer</li><li>Research Scientist</li><li>Business Intelligence Developer</li><li>AI Data Analyst</li><li>Big data engineering</li><li>Robotics Scientist</li><li>AI engineer</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0ad1a053beb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>