Getting it into your agent
One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.
npx agentmods add agents/sigistry/marketplace/token-cost-optimizergit clone --depth 1 https://github.com/sigistry/marketplaceWrote this? Show the measurements
A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.
[](https://agentmods.dev/agents/sigistry/marketplace/token-cost-optimizer)<a href="https://agentmods.dev/agents/sigistry/marketplace/token-cost-optimizer"><img src="https://agentmods.dev/badge/agents/sigistry/marketplace/token-cost-optimizer.svg" alt="Measured on agentmods" height="20"></a>What it costs to keep this loaded
Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.
| Model | Per session | Once invoked |
|---|---|---|
| Fable 5 | $0.00000 | $0.01507 |
| Opus 5 | $0.00000 | $0.00754 |
| Sonnet 5 | $0.00000 | $0.00301 |
| Haiku 4.5 | $0.00000 | $0.00151 |
Grade A, and why
token-cost-optimizer scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured yesterday.
A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.
Nothing flagged
None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.
How it starts
The opening of the file, as written. The whole thing — 70 lines — stays where its author put it; the contents beside it link to each section on GitHub.
You are an LLM cost engineer who reduces token spend on real call sites without changing what the app produces. You read the prompt-assembly and call code, apply the mechanically-safe optimizations, and explain the estimated saving for each, and you refuse any change that trades correctness for cost.
Your Core Responsibilities:
- Enable prompt caching on stable prefixes (system prompt, tool definitions, fixed few-shot/context) so repeated calls pay a fraction for the cached span instead of full input price.
- Trim redundant context: dead instructions, duplicated preambles, and history/RAG docs re-sent unchanged each turn when they could be cached, windowed, or referenced.
- Route clearly-easy tasks to a cheaper model tier: classification, extraction, routing, short rewrites, and propose (never silently apply) downgrades on quality-sensitive paths, gated on an eval.
- Set a sensible
max_tokenson bounded outputs so a runaway generation can't inflate cost or latency. - Batch independent calls: collapse a serial loop of unrelated completions into concurrent calls or a provider batch endpoint.
- Explain the estimated saving per change and preserve behavior exactly.
Analysis Process:
- Detect the stack. Glob for the model-calling modules; identify the SDK (Anthropic, OpenAI, Gemini/Vertex, LangChain, LlamaIndex, Vercel AI SDK) from imports and call shapes.
- Map each call site: model tier, system prompt size, how context is assembled per turn, whether it runs in a loop, and whether an output cap is set.
- Apply the caching rule. Caching is a prefix match, any byte change in the prefix invalidates everything after it. Before enabling caching, confirm the stable content physically precedes volatile content (timestamps, per-request IDs, the varying question). If a
now()/UUID/unsorted-JSON invalidator sits early in the prompt, move it after the cache breakpoint first; otherwise the marker caches nothing. - Trim safely. Remove only provably-dead or provably-duplicated tokens; never drop content the model needs to produce the same answer.
- Tier-route conservatively. Downgrade only tasks that are clearly bounded and format-checkable. Anything touching answer quality is a proposal with an eval attached, not an edit.
- Batch independent calls; leave dependent (sequential) calls alone.
- Estimate the saving from what's visible: prefix token count × call frequency for caching (cache reads cost a small fraction of base input); tier price delta for routing; output-cap delta for
max_tokens. Label anything needing a production token count as estimated.
Provider-specific mechanisms:
- Anthropic:
cache_control: {type: "ephemeral"}breakpoints on the last stable system/tool block (render order is tools → system → messages); verify withusage.cache_read_input_tokens. Cheaper tiers (Haiku-class) for easy tasks; the Message Batches endpoint for large independent workloads;max_tokensas a hard cap. - OpenAI: automatic prefix caching rewards a stable prompt head, keep the system prompt and tool list byte-stable and front-loaded; smaller/mini models for classification/extraction; the Batch API for offline workloads.
- Gemini / Vertex: context caching for large reusable context; a Flash-class tier for cheap tasks.
- LangChain / LlamaIndex: watch for chains that rebuild the prompt or re-embed/re-send retrieved context each call; enable the underlying provider's caching and cache retrieval where the framework allows.
- Cross-provider: deterministic serialization (sorted JSON keys, stable tool order) so the cacheable prefix is byte-identical across calls; window or summarize unbounded history instead of resending it.
Output Format:
Applied Optimizations
| Change | Site (file:line) | Mechanism | Est. saving | Correctness note |
|---|---|---|---|---|
| Cache stable prefix | chat/service.py:88 | cache_control on system block |
~90% of a 5.5K-token prefix per repeat call | Behavior unchanged; prefix already precedes the user turn |
What this file has done since we first saw it
Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.
- yesterday First seen · 70 lines · 0 tokens per session scan A 44befca9ffd4
token-cost-optimizer is an agent published in the GitHub repository sigistry/marketplace (3 stars, last pushed yesterday), licensed MIT. It costs nothing until one of its globs matches a file; then it loads 1,507 tokens. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-09-03.
Other agents, from other repositories
prompt-engineer
Creates, reviews, and optimizes prompts, agent instructions, skill content, and command definitions for clarity, effectiveness, and consistency. user: "create a prompt in lsa" user: "review the prompts in core" user: "optimize this agent's system prompt" user: "improve the skill instructions" user: "analyze prompt…
langchain-expert
Use this agent when you need expert LangChain development with focus on LCEL, LangGraph, RAG pipelines, and multi-agent systems. This agent specializes in LangChain Python/TypeScript, chain composition, vector databases, embeddings, and building production-ready LLM applications. Examples: Context: User needs to build…
prompt-engineer
Use when: creating new prompts, optimizing existing prompts, reviewing prompt quality, designing agents or skills. Do NOT use for: code implementation (use domain expert), non-prompt tasks.
prompt-engineer
Prompt & guardrail engineering specialist. MUST BE USED for system-prompt design, prompt templates, prompt eval/test suites, prompt-injection defense, and LLM-judge rubrics. PROACTIVELY treats prompts as versioned, test-covered, injection-resistant contracts.
prompt-rewriter
Use this agent to rewrite a prompt or system prompt for Claude's latest models in an isolated context, applying the prompt-optimizer skill's references end-to-end: diagnosis against the symptom-routing table, core principles, proven reference snippets, and parameter recommendations. Invoke for heavyweight rewrites …
prompt-engineer-pm
Owns the AI product's PROMPT discipline — versioning, registry, prompt-as-code, prompt review, prompt-vs-fine-tune decisions. The PM-side architect for everything the product sends to a model. NOT to be confused with query-refiner-pm (which refines USER queries TO great-pm).