token-cost-optimizer

token-cost-optimizer is an agent for coding agents from sigistry/marketplace. It costs 0 tokens per session (1,507 once invoked), scanned A, original, MIT.

A code-review agent that reduces the cost of language-model calls while preserving the application's behaviour. It examines prompts, context, model choices, output limits, and independent calls.

In plain words
What is it for?
Use it to review prompt caching, remove duplicate context, suggest cheaper models for suitable tasks, set output limits, and batch independent calls.
Why use it?
It helps control token spending and latency caused by repeated context, unnecessarily expensive models, oversized outputs, or avoidable serial requests.

Agent

Part of the llm-app-hardener plugin — 4 skills, 4 commands, 2 agents shipped together

Install

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.

agentmods
npx agentmods add agents/sigistry/marketplace/token-cost-optimizer
Clone the repo
git clone --depth 1 https://github.com/sigistry/marketplace

Or install llm-app-hardener, the plugin that ships this one along with the rest of its 4 skills, 4 commands, 2 agents.

Wrote 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.

agentmods badge for token-cost-optimizer

README.md
[![agentmods](https://agentmods.dev/badge/agents/sigistry/marketplace/token-cost-optimizer.svg)](https://agentmods.dev/agents/sigistry/marketplace/token-cost-optimizer)
Your own site
<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>
Per session 0 Only the description is in the session, so the agent can decide to use it. The body loads when it is invoked.
When invoked 1,507 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

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.

ModelPer sessionOnce 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

Measured yesterday against content hash 44befca9ffd4, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

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.

plugins/llm-app-hardener/agents/token-cost-optimizer.md · 70 lines

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:

  1. 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.
  2. Trim redundant context: dead instructions, duplicated preambles, and history/RAG docs re-sent unchanged each turn when they could be cached, windowed, or referenced.
  3. 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.
  4. Set a sensible max_tokens on bounded outputs so a runaway generation can't inflate cost or latency.
  5. Batch independent calls: collapse a serial loop of unrelated completions into concurrent calls or a provider batch endpoint.
  6. Explain the estimated saving per change and preserve behavior exactly.

Analysis Process:

  1. 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.
  2. 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.
  3. 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.
  4. Trim safely. Remove only provably-dead or provably-duplicated tokens; never drop content the model needs to produce the same answer.
  5. 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.
  6. Batch independent calls; leave dependent (sequential) calls alone.
  7. 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 with usage.cache_read_input_tokens. Cheaper tiers (Haiku-class) for easy tasks; the Message Batches endpoint for large independent workloads; max_tokens as 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

Read the full file on GitHub · 70 lines

Changes

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.

  1. yesterday First seen · 70 lines · 0 tokens per session scan A 44befca9ffd4

Subscribe to this mod's changes

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.

Related

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…

NVZver/claude-marketplace · 125 tokens

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…

andisab/swe-marketplace · 400 tokens

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.

fusengine/agents · 41 tokens

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.

komluk/scaffolding · 58 tokens

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 …

Aznatkoiny/zAI-Skills · 334 tokens

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).

VandanaAjayDubey111/great-pm · 71 tokens