agentleFS
RBraga01RBraga01/builder-ai/skills/context-optimization/SKILL.md

context-optimization

Skill2 starsChanged 5 months agoMITView on GitHub

Use when prompt cost is too high, latency is above threshold, or context window limits are being approached. Requires measurement before and after each reduction. Blocks "I shortened the prompt so it should be cheaper" completions.

24 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use bdi-mental-states, long-horizon-prompting and 10 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • Downey6689Skill

    bdi-mental-states

    Transforms external RDF context into BDI mental states. Invoke when modeling beliefs, desires, and intentions.

    Also in 7 projects that use this

  • DVwebBiz11Skill

    long-horizon-prompting

    This skill should be used when writing, enhancing, or evaluating the launch prompt for a long-running autonomous agent or a parallel multi-agent orchestration attacking a hard problem: pseudo-formal task briefs that define terms and an exact success predicate linguistically, enumerate non-counting outcomes, set persistence rules with explicit stop and return conditions and effort floors, manage a diverse portfolio of parallel approaches with an approach registry and blocked-route bookkeeping, and gate the return on adversarial audit. Route agent topology and coordination protocols to multi-agent-patterns, runtime control surfaces and loop governance to harness-engineering, evaluator and quality-gate construction to evaluation, judge design to advanced-evaluation, and compaction or memory mechanics to context-compression and memory-systems.

    Also in 5 projects that use this

  • Downey6689Skill

    hosted-agents

    Guidance for hosted/sandboxed agents. Invoke when running background agents in isolated VMs or multi-client setups.

    Also in 6 projects that use this

  • DVwebBiz11Skill

    self-improvement-loops

    This skill should be used when the harness, scaffold, workflow, or optimizer itself is the optimization target: recursive self-improvement (RSI) loops, meta-harnesses, self-improving harnesses that mine their own failures and propose bounded edits, evolutionary or population-based search over agent scaffolds, acceptance gates for self-modifying systems, and agentic context evolution where the mechanism that produces context is versioned and evolved. Route governance of a single autonomous loop (locked surfaces, durable logs, rollback, novelty gates, approval boundaries) to harness-engineering, measurement and quality-gate design to evaluation, judge design to advanced-evaluation, and remote sandbox infrastructure to hosted-agents.

    Also in 4 projects that use this

  • AbdelrhmanAlquranSkill

    latent-briefing

    This skill should be used when the user asks to "share memory between agents", "KV cache compaction for multi-agent", "orchestrator worker context", "latent briefing", "reduce worker tokens", "cross-agent memory without summarization", or discusses Attention Matching compaction, recursive language models with workers, or token explosion in hierarchical agents.

    Also in 4 projects that use this

  • rohunvoraSkill

    advanced-evaluation

    Master LLM-as-a-Judge evaluation techniques including direct scoring, pairwise comparison, rubric generation, and bias mitigation. Use when building evaluation systems, comparing model outputs, or establishing quality standards for AI-generated content.

    Also in 6 projects that use this

  • +1 more from Downey6689

The file

We split this skill into the rules it gives an agent

8 rules. 0 are common, 8 are distinctive, and 0 are very specific to this project.

  • 0

    Common

    Most of the 22 edited versions we read keep these.

  • 8

    Distinctive

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Run the prompt without each instruction — does output quality change?

    line 39
  2. Distinctive:

    Remove any instruction the model follows without it

    line 40
  3. Distinctive:

    Remove few-shot examples that duplicate knowledge the model already has

    line 41
  4. Distinctive:

    If using RAG, before any other change:

    line 54
  5. Distinctive:

    Add or tighten a similarity threshold (filter chunks below 0.75 cosine similarity)

    line 56
  6. Distinctive:

    If system prompt or retrieval context is identical across many calls:

    line 81
  7. Distinctive:

    Run this before applying any reduction, and after:

    line 89
  8. Distinctive:

    When context-optimization is satisfied, state it like this:

    line 112

“Common” is measured: kept by at least 6 in 10 of the 22 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Context Optimization

The Law

PROMPT COST IS NOT OPTIMISED BY GUESSING.
"I already have a short prompt" is a guess about token count.
"Reducing context will hurt quality" is a guess about the quality/cost curve.
Measure first. Apply the hierarchy. Measure again. THEN claim improvement.

When to Use

Trigger when:

  • Prompt + context exceeds 60% of the model's context window
  • p95 latency is above target
  • Cost per 1k calls exceeds budget
  • RAG pipeline is stuffing too many chunks into each call
  • Output quality is degrading on long inputs (long context dilution)

When NOT to Use

  • The feature has < 100 calls/month and total monthly cost is < $20 — optimisation ROI is negative at this volume
  • Quality is currently below threshold — fix quality first; optimising a broken pipeline only makes it cheaper to be wrong
  • The system prompt changes every call — prompt caching (Level 5) has no effect; skip straight to Level 1–3

The Reduction Hierarchy

Apply in order. Stop when the target is met. Do not apply all steps preemptively.

Level 1 — Trim the System Prompt

Audit every sentence:

  • Run the prompt without each instruction — does output quality change?
  • Remove any instruction the model follows without it
  • Remove few-shot examples that duplicate knowledge the model already has
  • Replace verbose explanations with single directives

Target: system prompt under 500 tokens for most tasks. Measure token count precisely:

import tiktoken
enc = tiktoken.get_encoding("cl100k_base")
print(len(enc.encode(system_prompt)))

Level 2 — Reduce Retrieved Context

If using RAG, before any other change:

  1. Reduce top_k by 1 and run eval-before-ship — recall often holds at lower top_k
  2. Add or tighten a similarity threshold (filter chunks below 0.75 cosine similarity)
  3. Set a hard context budget: MAX_CONTEXT_TOKENS = context_window × 0.4

Level 3 — Compress Retrieved Content

Before injecting:

  • Strip document headers, footers, and repeated boilerplate
  • Normalise whitespace and remove formatting artefacts
  • Convert verbose JSON to compact tabular format
  • For chunks over 600 tokens: LLM-summarise to 1/3 length with a fast model

Level 4 — Split the Pipeline

Move expensive operations to a cheaper model:

Before: Frontier model does everything
After:  Fast/cheap model → classify, extract, summarise
        Frontier model → final answer generation only

This typically cuts costs 5–10× with minimal quality loss. The frontier model only sees pre-processed, high-signal input.

Level 5 — Cache Stable Context

If system prompt or retrieval context is identical across many calls:

  • Enable prompt caching (Anthropic Beta, OpenAI prompt caching)
  • Cache embedding results for repeated queries (TTL matched to data freshness)

Prompt caching saves 50–90% on the cached portion. It is the highest-leverage optimization when the system prompt is long and stable.

Measuring Before and After

Run this before applying any reduction, and after:

Token count:  <input tokens>, <output tokens>, <total>
Latency:      p50 = Xs, p95 = Ys
Cost/1k:      $Z
Quality:      <eval suite pass rate: A%>

A reduction that saves 30% cost but drops quality 10% past threshold is not an optimization — it is a regression.

Rationalization Red Flags

These thoughts mean the prompt has not been measured — stop:

  • "I already have a short prompt" — count the tokens; "short" is not a token count
  • "Reducing context will hurt quality" — you don't know until you measure with eval-before-ship
  • "It costs too little to matter now" — $0.05/call is $1,500/month at 1k calls/day; growth events don't announce themselves; run the 10× projection from ai-cost-audit before calling it negligible
  • "Prompt caching is complex to set up" — it is a one-line header change; do Level 5 before assuming it's hard
  • "The frontier model is only marginally more expensive" — at 10k calls/day, "marginally" compounds

Completion Statement Format

When context-optimization is satisfied, state it like this:

Context optimized.
Reductions applied: <list of levels: e.g., L1 (trim), L2 (top_k 10→5), L5 (caching)>

Before:
  Input tokens: N (system: A, context: B, user: C)
  Latency p95: Xs
  Cost/1k: $Y
  Quality: Z% — evals/<feature>/results-<date-before>.md

After:
  Input tokens: N' (system: A', context: B', user: C')
  Latency p95: X's
  Cost/1k: $Y'
  Quality: Z'% — evals/<feature>/results-<date-after>.md ✓ (above threshold)

Delta: -X% cost, -Ys latency, quality delta: Z'% - Z% = ±Xpp

Quality must be verified with eval-before-ship — not eyeballed.

Why This Matters

LLM API costs compound with volume. A pipeline that costs $0.05/call at 1k calls/day costs $1,800/month. The same pipeline at 10k calls/day costs $18,000/month. Optimization at 1k is a 2-hour project. Optimization at 10k is a crisis sprint.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.