Advanced token reduction and prompt optimization framework for LLMs, featuring linguistic, algorithmic, and architectural patterns.
SaferSkills independently audited token-diet (Agent Skill) and scored it 100/100 (green). The audit ran 55 deterministic rules across Security, Supply Chain, Maintenance, Transparency, and Community; it found 0 high-severity and 0 lower-severity findings. The full rule-by-rule trace and per-finding evidence are below. Free, methodology-open.
Findings & checks · 0 flagged
Every scanned point with the score it earned and what moved between them.
First recorded scan — no prior version to compare against.
The primary manifest — the file an agent reads to learn what this artifact does.
Deployment-grade token optimization with execution order, ROI metrics, guardrails, and measurable outcomes.
Q → Retrieve → Prune → Cache → Route → Build Prompt → Compress → Call LLM → Measure → Update StateWhy this order: Early pruning eliminates waste before caching/routing decisions. Compression happens last (post safety checks). Measurement feeds back into next iteration.
Goal: Never send unnecessary tokens.
Pipeline:
query → embed → topK(20) → dedupe → sentence-trim → topK(5–8)Concrete rules:
Win: 30–60% reduction immediately (no quality loss if done right).
Split prompt into 3 blocks:
[STATIC_SYS] → cache (reuse across requests)
[DYNAMIC_CTX] → no cache (changes per request)
[USER_INPUT] → no cache (one-off query)Cache candidates:
Decision rule:
if block_reused_in_next_N_requests → cache
else → inline (no caching overhead)Implementation: Use API cache headers (cache_control: {"type": "ephemeral"} for Anthropic; similar for other providers).
Decision tree:
if task ∈ {format, extract, classify, summarize}
→ small model (Haiku, GPT-4o-mini, Gemini-Flash)
else if task ∈ {reason, synthesize, creative}
→ large model (Sonnet, GPT-4o, Gemini-Pro)Safety guard: If confidence low or error detected → retry on stronger model (don't downgrade past first attempt).
Result: 60–80% cost reduction on simple tasks without quality hit.
Bad (5 calls + reread context 5x):
get_user(1) → get_user(2) → get_user(3)Good (1 call):
get_users([1, 2, 3])Also batch:
Structure state as JSON:
{
"facts": ["user_id=42", "role=admin"],
"constraints": ["budget_limit=$1000", "deadline=2026-04-30"],
"open_tasks": ["approval_pending", "docs_missing"],
"summary": "(optional) Human-readable 150-token version"
}When to regenerate:
Why: Structured state lets LLM reason precisely. Optional summary is for readability/debugging, not required.
Apply only right before the API call:
"Please analyze the dataset and provide a concise summary"
→ "Analyze data. Summarize concise."DO NOT compress:
Benefit: ~15% token reduction on prose prompts; safe only if applied surgically.
Minimal structure (reorder as needed):
[SYS — cached]
Context:
{pruned_context_1200_tokens_max}
State:
{facts + constraints (JSON)}
Task:
{compressed_user_input}Why minimal: Every line you don't send saves tokens. No filler, no explanations that don't move the needle.
Track per request:
tokens_in
tokens_out
latency_ms
cache_hit_rate (%)
retrieval_tokens_before / after
cost_usdAdd alerts:
Why: Without measurement, you're flying blind. Guardrails only work if you see violations early.
| Problem | Signal | Action |
|---|---|---|
| Answer quality drops | User feedback or eval score ↓ | Disable compression first, then increase context |
| Hallucination risk rises | Repeated factual errors | Increase context, not summary; rebuild state from raw history |
| Silent drift | State contradicts history | Rebuild state from scratch; check if constraints stale |
| Over-pruning | Query unmatched to results | Fetch more chunks before pruning; lower similarity threshold |
Golden rule: If unsure whether compression/routing broke something, disable it and rerun. Measure the difference. Only re-enable if safe.
Retrieve → prune hard
Cache static
Route cheap→expensive
Batch all
State > summary
Compress last
Measure always
Guard drift| Metric | Target | Conditions |
|---|---|---|
| Token reduction | 50–80% | All 9 steps applied in order |
| Latency | ↓20–50% | Caching + routing active |
| Cost | ↓40–75% | Routing to smaller models + cache hits >70% |
| Quality | Stable | Guards enforced; no compression on code/schema/legal |
Typical breakdown:
| Mistake | Result | Fix |
|---|---|---|
| Skip measurement | Invisible failures | Instrument from day 1 |
| Compress code/JSON | Syntax errors, parsing fails | Never compress structured data |
| Prune too aggressively | Relevant context lost → hallucinations | Keep ≥1200 tokens context; test quality on pruned versions |
| Cache everything | No room for dynamic context | Cache only truly static blocks |
| Summarize too early | Miss important detail → wrong answer | Use structured state; regenerate if contradiction |
| Ignore routing guardrails | Quality collapse on hard tasks | Always allow retry on stronger model |
~30 seconds. Free. No account. Every finding cites a rule and a line of evidence.