<?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 Hamza Tbatou on Medium]]></title>
        <description><![CDATA[Stories by Hamza Tbatou on Medium]]></description>
        <link>https://medium.com/@hamza.tbatou?source=rss-80c87ddac0c9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mA7_QW2-P_nEma_jELhUiQ.jpeg</url>
            <title>Stories by Hamza Tbatou on Medium</title>
            <link>https://medium.com/@hamza.tbatou?source=rss-80c87ddac0c9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 01:55:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hamza.tbatou/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[Token Optimization for Coding Agents: How to Cut AI Coding Costs Without Slowing Developers Down]]></title>
            <link>https://medium.com/sia-ai/token-optimization-for-coding-agents-how-to-cut-ai-coding-costs-without-slowing-developers-down-4d6bc942bc4f?source=rss-80c87ddac0c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d6bc942bc4f</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[token-optimization]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[coding-agents]]></category>
            <dc:creator><![CDATA[Hamza Tbatou]]></dc:creator>
            <pubDate>Fri, 04 Dec 2026 13:13:28 GMT</pubDate>
            <atom:updated>2026-12-04T13:23:21.453Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3JBzOUz2B2ZzjvlGXNjVTg.png" /></figure><p>Earlier this year, Uber burned through its entire 2026 AI coding tools budget in four months. Its president and COO, Andrew Macdonald, put the problem plainly on the <em>Rapid Response</em> podcast: “That link is not there yet, right? I think maybe implicitly there is more that is getting shipped, but it’s very hard to draw a line between one of those stats and, ‘Okay, now we’re actually producing 25 percent more useful consumer features.’”[¹]</p><p>Where a copilot answers one prompt, a coding agent reads files, runs commands, inspects test results, and retries. At every step, the full accumulated context is sent back to the model. The bill compounds with each action, and multiplies across parallel agents. Gartner predicts that by 2028, AI coding costs will overtake the average developer’s salary, driven by rising token consumption and an industry-wide shift to consumption-based pricing that makes the bill scale with usage rather than with seats.[²]</p><p>At Sia, we spent the past months measuring which optimization methods actually deliver. We ran them on real GitHub issues, where a fix either passes the project’s test suite or it does not. The tests are small: twenty issues per comparison, which resolves large effects and says nothing about small ones. On that basis, our best result came from a skill file injected into the system prompt, which cut cost per resolved task by 26% without the agent resolving fewer issues. One tool we expected to help everywhere saved 38% of tokens on refactoring work and cost 40% more on bug fixes, and that split turned out to be the most useful finding of the series.</p><h3>The invisible billing problem</h3><p>High token consumption would be manageable if the bill were readable, and it rarely is. A cloud bill can be broken down by service, by team, by environment; a token bill usually cannot be without the right tool. Providers invoice at the API-key or subscription level, and the breakdown below that line rarely tells you which agent consumed what, on which task, or for which project. A session that resolved a critical bug and a session that spent thousands of tokens retrying a failing test look identical on the invoice.</p><p>That leaves two bad options when the bill grows: cap usage across the board, which penalizes the teams that use agents well, or keep paying without knowing what the spend buys. Neither is a position anyone wants to defend in a budget review, which is why we started with measurement rather than with reduction.</p><h3>Measuring before optimizing</h3><p>A tool that cuts token consumption by half is worthless if the agent stops solving the problem. We needed a setup where both sides of that trade could be observed on the same tasks.</p><p>We built our benchmark on SWE-bench Lite, a set of 300 real GitHub issues drawn from widely used Python projects such as Django, Flask, scikit-learn and sympy. Each instance gives the agent a bug report written by a human and the exact state of the repository at the time the issue was filed. The verdict comes from a test suite the agent never sees: either the patch makes the tests pass, or it does not. Each comparison reported below runs on a 20-instance subset rather than on the full set, for a practical reason: a single baseline sweep across all 300 instances costs more than the savings we were trying to measure.</p><p>The protocol runs in three steps. <strong>Generate:</strong> Claude Code runs headless on the repository, reads the code, edits it, runs commands, and produces a git patch. <strong>Evaluate:</strong> the patch is applied inside a container and the hidden test suite runs. <strong>Score:</strong> we record the resolution rate, the tokens consumed, and the cost, per instance.</p><p>We score on cost per resolved task rather than on tokens per session. An agent that halves its token usage while failing twice as often has not saved anything; it has made the same work more expensive, and the token graph will look like a win the whole time.</p><p>The comparisons are not all like for like. Prompt strategies and model routing ran on SWE-bench issues directly. Tooling was compared on matched task sets, meaning the same repositories and the same tasks with and without the tool, because those tools act on repository exploration rather than on issue resolution. Where a result depends on that difference, we flag it in the relevant section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*_Pz-d4remUA5s1upSEMaAA.png" /></figure><h3>The four levers of token optimization</h3><p>We organized the methods around four variables: measurement, meaning knowing where tokens go; input volume, meaning sending less context; output volume, meaning generating fewer tokens for the same work; and cost per token, meaning routing to a cheaper model or pricing tier. Measurement has to come first, because without it the other three are guesses. Those three combine freely, with one exception under Lever 4 that we come back to.</p><h3>Lever 1. Measurement: building token observability</h3><p>Coding agents already log everything they do. Claude Code writes session files in ~/.claude/projects/; Codex and Gemini CLI produce their own traces. The data exists; nobody reads it.</p><p>Token Telemetry is the tool an independent open-source tool that we adapted to close that gap. It parses the native log files of all three agents and renders them in a single local dashboard: sessions in flight, tokens per session, running cost, refreshed every 15 seconds. It reads files that are already on disk and sends nothing anywhere, which is what makes it usable on client code.</p><p>Aggregates are not much more useful than the invoice itself. Knowing that yesterday’s agents consumed four million tokens does not tell you which of them to change. Token Telemetry replays a session turn by turn, with the messages, the tool calls, the files read and the commands run, which is where the failure modes are visible.</p><p>One session in our own logs shows the shape of the problem. It spent 800,000 tokens on a single Django issue, and the replay showed the agent re-reading the same 12,000-line module nine times: once at the start, then again after each failed test run, because nothing in its context told it the file had not changed since the last read. The fix was one line in CLAUDE.md. Nothing in the monthly total would have surfaced it.</p><p>Cut by model and by agent, the same data shows which combination drives spend. On our matched task sets, the agent that resolved tasks in the fewest turns came out cheaper than the one with the lowest per-token price. Budget thresholds and alerts are the part that changes behavior: an alert part-way through a session gives a developer the chance to stop and re-scope it, which is a decision nobody can make from an invoice thirty days later.</p><h3>Lever 2. Reducing input tokens</h3><p>Input tokens are the largest line item. Every turn, the model receives the full conversation history, system prompt, every file it has read, and every command output. On a long session that can reach 100k tokens per turn across dozens of turns, which is why most of the methods below act on the input side.</p><p><strong>CLAUDE.md and context hygiene.</strong> CLAUDE.md is Claude Code’s native persistent-memory file: project conventions, file layout, test commands. A well-scoped one steers the agent toward the right files early; a bloated one that dumps full architecture docs into the system prompt adds thousands of tokens to every turn of every session. Our working rule is to include only what changes the agent’s first three decisions. Architecture documentation that a developer would read once belongs in the repository, where the agent can fetch it if a task needs it.</p><p><strong>Managing context: `/compact` vs. prompt caching.</strong> These two built-in mechanisms, a Claude Code command and an Anthropic API feature, pull in opposite directions. /compact summarizes the history into a shorter version and cuts input tokens, but rewriting the prefix invalidates any prompt cache built on it. On a long debugging session where the early turns still matter, keeping the cache is usually worth more than the compaction. Once the session has moved past exploration and those turns are dead weight, the reverse holds. Lever 4 has the pricing arithmetic.</p><p><strong>MCP scoping.</strong> MCP (Model Context Protocol) is the open standard that connects an agent to external tools. Each connected MCP server adds its tool definitions (descriptions, parameter schemas, examples) to the system prompt, and ten servers can mean several thousand tokens on every turn whether the agent calls them or not. Attaching servers per project rather than globally is the whole of the fix: a backend debugging session has no use for a Figma connector.</p><p><strong>Subagents.</strong> In this native Claude Code feature, a subagent gets its own clean context window with no inherited history. A targeted sub-task, such as finding every file that imports a given module, runs on a few thousand tokens instead of on an 80k-token accumulation. The gain is largest on workflows with one planning phase and several independent execution steps, and we have not measured it precisely enough to put a number on it.</p><p><strong>RTK.</strong> Most of what a coding agent sends to the model is the raw output of the commands it ran: a failing pytest on a large project can dump 20k tokens of stack traces and logs into the context, much of it repeated line for line. RTK is an independent open-source tool written in Rust[³] that compresses command output. It plugs into Claude Code as a PreToolUse hook[⁴]. It intercepts each Bash command before it runs, strips ANSI codes, deduplicates repeated error lines, and truncates stack traces to the relevant frames. The full raw output is still written to disk, so nothing is lost for a developer debugging by hand; only the agent sees the reduced version. In our tests, input tokens dropped 60 to 90% per CLI call, with no resolution difference we could detect at this sample size.</p><p><strong>Headroom. </strong>A second compressor, <a href="https://github.com/headroomlabs-ai/headroom">Headroom</a>, is an independent open-source tool, available as a library, a local proxy or an MCP server, that targets the same problem from a wider angle: instead of intercepting only Bash output the way RTK does, it runs as a local proxy or MCP server and compresses tool outputs, logs, files, and RAG chunks before any of them reach the context window. Its published figures claim roughly 20% fewer tokens overall on a typical coding-agent workload, and 60 to 95% fewer tokens specifically on JSON-heavy tool output, with the original content retrievable on demand. The two are not mutually exclusive; at least one third-party wrapper chains RTK and Headroom in the same pipeline. We have not run Headroom through our own benchmark yet, so read the vendor’s numbers as a starting point rather than as a result.</p><p><a href="https://github.com/safishamsi/graphify"><strong>Graphify.</strong></a> On a small repository, an agent can read its way to the right files in a few turns. On a thousand-file codebase, that exploration becomes the dominant cost: the agent greps directories, opens wrong files, backtracks, reads more. Graphify, an independent open-source tool, indexes the repository once into a code-level dependency graph, then exposes it as an MCP tool the agent queries on demand, asking which modules depend on a class or what calls a function instead of grepping the whole tree on every request. On large-repository tasks in our benchmark, this cut tokens by 39%. On small repos the gain was negligible, because exploration cost was already low there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*US5bDYvy31T9RcwXlF84SA.png" /></figure><p><strong>jev plugin.</strong> The jev plugin is an independent open-source Claude Code plugin backed by Jev, a small hosted model from TypeSafe that returns probabilities rather than text. It exposes the model as commands that locate code from a description, check a property across many files and narrow large file reads, so the agent does not load those files into its context. Its author reports 30 to 38% fewer billed tokens on search and audit tasks, measured on private repositories. We tested it differently from the other tools. We measured the plugin’s effect on the agent’s total token use, not the model alone, and we ran it outside the SWE-bench setup used elsewhere in this article. The test used 24 search, audit and large-file tasks on six public repositories in Go, Python and TypeScript. The repositories had 240 to 1,900 files. Each task ran three times in each of three conditions: Claude Code without the plugin, with the plugin, and with an instruction to use the plugin first. That made 216 runs on Sonnet 5.5 and 81 on Haiku 5.5.</p><p>The results are not conclusive. Left alone, the agent never called the jev plugin (0 of 99 runs) and kept using its native grep and read tools. When told to use it, billed input tokens ended 6% above baseline (95% interval 0.97 to 1.15), with the same answer accuracy and within the roughly 15% noise between identical runs. The plugin does shrink what tool output adds to the context (29%), but on tasks this short 93% of billed tokens are the fixed prefix re-read at each turn, so little was left to save. Above 800 files, its search command also refuses to run without a narrowed path. On typical repositories we would not adopt it, since Claude’s native tools already explore efficiently. What our tests cannot rule out is the case it was built for, very large repositories where exploration dominates cost, which none of ours reached and where it may prove interesting, as Graphify does.</p><h3>Lever 3. Reducing output tokens</h3><p>Output is the smaller half of the bill and the more expensive one per unit on most providers. On a long session, the agent’s own responses accumulate: explanations nobody asked for, full-file rewrites where a three-line patch would do, reasoning preambles before every edit. The absolute volume is smaller than on the input side, but the unit price makes trimming it worth some effort.</p><p><strong>Skill files. </strong>A SKILL.md file dropped into Claude Code’s skills directory is read in two stages: only the skill’s short description is available at session start, and the full content loads when the skill is invoked, after which it stays in the conversation. An unused skill therefore costs only its description, and the instruction does not have to be repeated in every prompt. Caveman is a community-built output-style skill that strips commentary to fragments: “I’d recommend using useMemo to memoize the object” becomes “Wrap in useMemo.” On Q&amp;A-style tasks that cuts roughly 65% of output tokens. On real coding work the gain drops to about 10%, because most of the output is code, which does not compress the same way. Skill files stack without conflicting, so Caveman can run alongside the others.</p><p><a href="https://github.com/DietrichGebert/ponytail"><strong>Ponytail.</strong></a><strong> </strong>Ponytail, a third-party open-source add-on for coding agents, goes further than reformatting: its overall goal is to cut unnecessary exploration and unnecessary code changes, which changes how the agent works. To that end, it bans chit-chat and verbose reasoning, forces exploration through ripgrep instead of full-file reads, and replaces full-file rewrites with differential patches, using sed and awk-style edits rather than regenerating files wholesale. On a published benchmark using Haiku 4.5 across 12 tasks, it produced 54% fewer lines of code, 22% fewer tokens, 20% lower cost and 27% less wall-clock time. and 27% less wall-clock time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*lrMweIArnPtKVnKQt1HG8g.png" /></figure><h3>Lever 4. Reducing cost per token</h3><p>This last lever leaves the agent’s behavior alone and works on the price of each token instead.</p><p><strong>Model switching.</strong> /model and /effort are built-in Claude Code commands that swap model or reasoning depth mid-session; opusplan, a built-in Claude Code model alias, automates the same instinct, planning with Opus and executing with Sonnet at zero configuration. <a href="https://github.com/musistudio/claude-code-router">CCR</a> (Claude Code Router), a community open-source proxy, routes across providers deterministically: background tasks like diff summaries go to <a href="https://ollama.com/">Ollama</a> (local, free), default coding tasks to a mid-range provider like DeepSeek or Qwen, anything past a context threshold to a frontier model. The lever is substitution rather than reduction: it trades quality for price on whatever gets routed down, which is fine for a diff summary and rarely fine for the code that ships.</p><p><strong>Prompt caching.</strong> Prompt caching is an Anthropic API feature that Claude Code uses automatically: a cache read runs at one-tenth the standard input rate. On Sonnet 4.6 ($3/M standard input), a cache hit costs $0.30/M, a 90% discount that holds as long as nothing breaks the prefix mid-session. Compacting the history, switching models, or restructuring the system prompt all invalidate it, for the reason described under Lever 2.</p><p><strong>Batch processing.</strong> For work where nobody is waiting on a reply (repo-wide audits, nightly PR sweeps, documentation passes) the Messages Batch API, an asynchronous Anthropic API service, offers 50% off on both input and output tokens, with results within 24 hours. It cannot serve a live coding session, but it stacks with caching when both conditions apply.</p><h3>What our experiments showed</h3><p>The four comparisons below each ran on twenty SWE-bench Lite instances against a matched baseline. At that sample size the token and cost differences are large enough to act on. The pass rates are not: twenty tasks means one resolved issue moves the rate by five points, so read every pass rate here as evidence that resolution did not collapse, and as nothing stronger than that.</p><p><strong>Skill injection</strong> gave the cleanest result. A full-stack-dev skill loaded into Claude Sonnet’s system prompt, tested against baseline on 20 SWE-bench issues, cut tokens by 27% and cost per resolved task by 26%. Resolution held at 13 of 20 tasks against 12 of 20 for the baseline, a difference of one issue, which is the point: the saving did not come out of the agent solving less.</p><p><strong>Model routing</strong> ran against what the per-token price would suggest. Switching from Sonnet to Opus 4.8 on the same 20 tasks cut tokens per instance by 68% and cost per resolved task by 23%, with both models resolving 12 of 20. Opus costs more per token and reached the answer in far fewer iterations, which more than covered the difference. A team optimizing on token count alone would have moved in the wrong direction here.</p><p><strong>Ponytail</strong> was the most useful result because it was mixed. On bug-fix tasks it increased cost per resolved task by roughly 40%. Its instinct to question whether code needs to exist is overhead when the job is to locate a defect in code that already exists and mostly works. On modification and refactoring anchored in existing code, the same tool cut tokens by 38% and cost by a comparable margin, because there the questioning does real work: it stops the agent from re-reading and regenerating files it has already seen.</p><p><strong>Graphify</strong> helped most where the mechanism says it should, on feature development in large repositories, where the bottleneck is retrieving the right context rather than writing the fix. It cut tokens by 39% there and beat Ponytail on the same tasks, because querying a pre-built dependency graph costs a fraction of what grepping a flat file tree costs.</p><p>Across the four comparisons, the choice of tool mattered more than any setting inside it. The same technique saved 39% in one context and cost 40% more in another, and the variable separating the two cases was task type rather than run-to-run variance. That makes tool selection a workflow decision rather than a procurement one, which changes how you would roll any of this out to a team of fifty.</p><h3>Choosing the right method for the right work</h3><p>The table below recaps every method covered above, in lever order: what it is, what it delivers, where it falls short, and when to use it. Figures come from our 20-task tests unless marked as a vendor claim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*8XPgMdQSWAe31M8iIAl3fw.png" /></figure><h3>Governance and security</h3><p>Routing is a data residency decision, not just a cost one. CCR is a community proxy, not an Anthropic product. It can redirect requests to DeepSeek, Qwen, GLM, Ollama, or OpenRouter. Once routed, client code leaves the contracted environment with no SLA, no DPA, no audit trail beyond the third party’s own terms. DeepSeek and Qwen process data under Chinese jurisdiction. Ollama, run locally, is the only zero-exposure option among them.</p><p>Ponytail, RTK, and Graphify sit on the other side of that line by construction. A Rust binary, Node.js hooks and a local graph index call no external API beyond the LLM provider already under contract. They change what reaches the model, not where it goes.</p><p>The resulting framework: on-premise or air-gapped clients get Ollama only, CCR excluded by default; EU-regulated clients in finance or health get Anthropic direct, no CCR; unregulated internal use can run CCR, but only with a documented provider choice and a DPA review.</p><h3>From quick wins to sustained practice</h3><p>Some of what we tested costs nothing to adopt: CLAUDE.md hygiene, /compact timing, skill files, and knowing which model switch saves money without losing resolution. None of it requires a procurement conversation, and the measurement side can be running in an afternoon.</p><p>The harder part is matching tools to workflows: Ponytail for refactor-heavy teams, Graphify for large monorepos, RTK for CLI-dense sessions, with routing and caching layered underneath. Getting that match wrong is not a neutral outcome, as the Ponytail numbers show, so the measurement has to be in place before the tooling decisions rather than after them.</p><p>What we cannot tell you yet is how any of this behaves over months rather than over twenty tasks, or how much of the 26% survives contact with a team that did not run the benchmark and has no particular interest in token counts. We are running the same protocol on larger samples and on a second language ecosystem, and we will publish those numbers whether or not they hold.</p><p><em>Neirouz Bouchaira, Antoine Marques and Hamza Tbatou, Sia</em></p><p>[¹]: Uber president and COO Andrew Macdonald, interviewed on the <em>Rapid Response</em> podcast, May 2026. See <a href="https://fortune.com/2026/05/26/uber-coo-ai-spending-tokens-claude-code/">“Uber’s COO says it’s getting harder to justify the company’s AI spend: ‘That link is not there yet’”</a>, <em>Fortune</em>, May 26, 2026. [²]: <a href="https://www.gartner.com/en/newsroom/press-releases/2026-06-24-gartner-predicts-ai-coding-costs-will-surpass-average-developer-salary-by-2028-as-token-consumption-surges">“Gartner Predicts AI Coding Costs Will Surpass Average Developer’s Salary by 2028 as Token Consumption Surges”</a>, Gartner Newsroom, June 24, 2026. [³]: Rust is a compiled programming language. A tool written in Rust ships as a single self-contained binary with nothing else to install, and adds negligible overhead to each command. [⁴]: A PreToolUse hook is a script that Claude Code runs automatically just before the agent executes a tool, such as a Bash command. The script can inspect, modify or block the call; RTK uses it to route each command through its compression step.</p><p>RTK: <a href="https://github.com/rtk-ai/rtk">rtk-ai/rtk: CLI proxy that reduces LLM token consumption by 60–90% on common dev commands. Single Rust binary, zero dependencies</a></p><p>Ponytail: <a href="https://github.com/DietrichGebert/ponytail">DietrichGebert/ponytail: Makes your AI agent think like the laziest senior dev in the room. The best code is the code you never wrote.</a></p><p>Graphify: <a href="https://github.com/Graphify-Labs/graphify">Graphify-Labs/graphify: Turn any codebase, with its docs, SQL schemas, configs, and PDFs, into a queryable knowledge graph. A /graphify skill for Claude Code, Cursor, Codex, and Gemini CLI: local deterministic AST parsing, every edge explained, no vector store.</a></p><p>Headroom: <a href="https://github.com/headroomlabs-ai/headroom">headroomlabs-ai/headroom: Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60–95% fewer tokens for JSON, same answers. Library, proxy, MCP server.</a></p><p>Great tool for token optimization: <a href="https://github.com/alexgreensh/token-optimizer">alexgreensh/token-optimizer: Find the ghost tokens. Fix them. Survive compaction. Avoid context quality decay.</a></p><p>jev plugin: <a href="https://github.com/BorisLeMeec/jev">BorisLeMeec/jev: A claude code plugin for jev</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d6bc942bc4f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/sia-ai/token-optimization-for-coding-agents-how-to-cut-ai-coding-costs-without-slowing-developers-down-4d6bc942bc4f">Token Optimization for Coding Agents: How to Cut AI Coding Costs Without Slowing Developers Down</a> was originally published in <a href="https://medium.com/sia-ai">Sia AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>