leanprompt 0.0.0-stage → 0.1.0-dev.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/LICENSE-DOCS +396 -0
- package/NOTICE +11 -0
- package/README.md +89 -2
- package/cli/dist/detect.d.ts +23 -0
- package/cli/dist/detect.js +219 -0
- package/cli/dist/evalAudit.d.ts +32 -0
- package/cli/dist/evalAudit.js +161 -0
- package/cli/dist/facts.d.ts +14 -0
- package/cli/dist/facts.js +43 -0
- package/cli/dist/forms.d.ts +23 -0
- package/cli/dist/forms.js +199 -0
- package/cli/dist/frontmatter.d.ts +10 -0
- package/cli/dist/frontmatter.js +32 -0
- package/cli/dist/help.d.ts +27 -0
- package/cli/dist/help.js +118 -0
- package/cli/dist/init.d.ts +78 -0
- package/cli/dist/init.js +358 -0
- package/cli/dist/install.d.ts +20 -0
- package/cli/dist/install.js +225 -0
- package/cli/dist/isMain.d.ts +6 -0
- package/cli/dist/isMain.js +18 -0
- package/cli/dist/lesson.d.ts +16 -0
- package/cli/dist/lesson.js +205 -0
- package/cli/dist/lint/facts.d.ts +7 -0
- package/cli/dist/lint/facts.js +163 -0
- package/cli/dist/lint/numbers.d.ts +26 -0
- package/cli/dist/lint/numbers.js +163 -0
- package/cli/dist/lint/rules.d.ts +20 -0
- package/cli/dist/lint/rules.js +170 -0
- package/cli/dist/log/logger.d.ts +49 -0
- package/cli/dist/log/logger.js +148 -0
- package/cli/dist/log/record.d.ts +56 -0
- package/cli/dist/log/record.js +117 -0
- package/cli/dist/main.d.ts +6 -0
- package/cli/dist/main.js +67 -0
- package/cli/dist/profile.d.ts +93 -0
- package/cli/dist/profile.js +372 -0
- package/cli/dist/report/cost.d.ts +55 -0
- package/cli/dist/report/cost.js +151 -0
- package/cli/dist/report/html.d.ts +81 -0
- package/cli/dist/report/html.js +555 -0
- package/cli/dist/report/template.html +269 -0
- package/cli/dist/score/calibrate.d.ts +65 -0
- package/cli/dist/score/calibrate.js +213 -0
- package/cli/dist/score/measured.d.ts +66 -0
- package/cli/dist/score/measured.js +191 -0
- package/cli/dist/score/static.d.ts +112 -0
- package/cli/dist/score/static.js +172 -0
- package/cli/dist/score/write.d.ts +29 -0
- package/cli/dist/score/write.js +247 -0
- package/forms/AGENTS.block.md +25 -0
- package/forms/opencode/commands/leanprompt-audit.md +10 -0
- package/forms/opencode/commands/leanprompt.md +8 -0
- package/forms/skills/generation-economy/SKILL.md +89 -0
- package/forms/skills/generation-economy/rules/LP-GE-01.md +93 -0
- package/forms/skills/generation-economy/rules/LP-GE-02.md +82 -0
- package/forms/skills/generation-economy/rules/LP-GE-03.md +87 -0
- package/forms/skills/generation-economy/rules/LP-GE-04.md +118 -0
- package/forms/skills/generation-economy/rules/LP-GE-05.md +84 -0
- package/forms/skills/generation-economy/rules/LP-GE-06.md +76 -0
- package/forms/skills/generation-economy/rules/LP-GE-07.md +84 -0
- package/forms/skills/generation-economy/rules/LP-GE-08.md +71 -0
- package/forms/skills/generation-economy/rules/LP-GE-09.md +79 -0
- package/forms/skills/generation-economy/rules/LP-GE-10.md +104 -0
- package/forms/skills/leanprompt/SKILL.md +48 -0
- package/forms/skills/leanprompt/fix.md +15 -0
- package/forms/skills/leanprompt/init.md +30 -0
- package/forms/skills/llm-call-audit/SKILL.md +169 -0
- package/forms/skills/llm-call-audit/call-shapes.md +99 -0
- package/forms/skills/llm-call-audit/presenting.md +72 -0
- package/forms/skills/llm-call-audit/report-template.md +113 -0
- package/forms/skills/lmwarden/SKILL.md +97 -0
- package/forms/skills/lmwarden/rules/LP-LW-01.md +73 -0
- package/forms/skills/lmwarden/rules/LP-LW-02.md +78 -0
- package/forms/skills/lmwarden/rules/LP-LW-03.md +73 -0
- package/forms/skills/measure-loop/SKILL.md +155 -0
- package/forms/skills/measure-loop/templates/stable-head.template.ts +38 -0
- package/forms/skills/measure-loop/templates/stable_head_template.py +40 -0
- package/forms/skills/prefill-cache/SKILL.md +66 -0
- package/forms/skills/prefill-cache/rules/LP-PC-01.md +103 -0
- package/forms/skills/prefill-cache/rules/LP-PC-02.md +80 -0
- package/forms/skills/prefill-cache/rules/LP-PC-03.md +75 -0
- package/forms/skills/prefill-cache/rules/LP-PC-04.md +79 -0
- package/forms/skills/prefill-cache/rules/LP-PC-05.md +68 -0
- package/forms/skills/prefill-cache/rules/LP-PC-06.md +71 -0
- package/forms/skills/prefill-cache/rules/LP-PC-07.md +97 -0
- package/forms/skills/prefill-cache/rules/LP-PC-08.md +67 -0
- package/forms/skills/prefill-cache/rules/LP-PC-09.md +75 -0
- package/forms/skills/prefill-cache/rules/LP-PC-10.md +76 -0
- package/forms/skills/prefill-cache/rules/LP-PC-11.md +72 -0
- package/forms/skills/prefill-cache/rules/LP-PC-12.md +73 -0
- package/forms/skills/prompt-diet/SKILL.md +69 -0
- package/forms/skills/prompt-diet/rules/LP-PD-01.md +79 -0
- package/forms/skills/prompt-diet/rules/LP-PD-02.md +73 -0
- package/forms/skills/prompt-diet/rules/LP-PD-03.md +65 -0
- package/forms/skills/prompt-diet/rules/LP-PD-04.md +77 -0
- package/forms/skills/prompt-diet/rules/LP-PD-05.md +71 -0
- package/forms/skills/prompt-diet/rules/LP-PD-06.md +68 -0
- package/models/anthropic-thinking.md +38 -0
- package/models/openai-reasoning.md +35 -0
- package/models/qwen.md +34 -0
- package/package.json +32 -4
- package/providers/anthropic.md +83 -0
- package/providers/deepinfra.md +46 -0
- package/providers/gemini.md +61 -0
- package/providers/openai.md +73 -0
- package/providers/openrouter.md +66 -0
- package/providers/sglang.md +41 -0
- package/providers/vllm.md +52 -0
- package/runtimes/http-clients.md +20 -0
- package/skills/_template/RULE.md +31 -0
- package/skills/generation-economy/SKILL.md +88 -0
- package/skills/generation-economy/rules/LP-GE-01.md +92 -0
- package/skills/generation-economy/rules/LP-GE-02.md +81 -0
- package/skills/generation-economy/rules/LP-GE-03.md +86 -0
- package/skills/generation-economy/rules/LP-GE-04.md +117 -0
- package/skills/generation-economy/rules/LP-GE-05.md +83 -0
- package/skills/generation-economy/rules/LP-GE-06.md +75 -0
- package/skills/generation-economy/rules/LP-GE-07.md +83 -0
- package/skills/generation-economy/rules/LP-GE-08.md +70 -0
- package/skills/generation-economy/rules/LP-GE-09.md +78 -0
- package/skills/generation-economy/rules/LP-GE-10.md +103 -0
- package/skills/leanprompt/SKILL.md +47 -0
- package/skills/leanprompt/fix.md +14 -0
- package/skills/leanprompt/init.md +29 -0
- package/skills/llm-call-audit/SKILL.md +168 -0
- package/skills/llm-call-audit/call-shapes.md +98 -0
- package/skills/llm-call-audit/presenting.md +71 -0
- package/skills/llm-call-audit/report-template.md +112 -0
- package/skills/lmwarden/SKILL.md +96 -0
- package/skills/lmwarden/rules/LP-LW-01.md +72 -0
- package/skills/lmwarden/rules/LP-LW-02.md +77 -0
- package/skills/lmwarden/rules/LP-LW-03.md +72 -0
- package/skills/measure-loop/SKILL.md +154 -0
- package/skills/measure-loop/templates/stable-head.template.ts +38 -0
- package/skills/measure-loop/templates/stable_head_template.py +40 -0
- package/skills/prefill-cache/SKILL.md +65 -0
- package/skills/prefill-cache/rules/LP-PC-01.md +102 -0
- package/skills/prefill-cache/rules/LP-PC-02.md +79 -0
- package/skills/prefill-cache/rules/LP-PC-03.md +74 -0
- package/skills/prefill-cache/rules/LP-PC-04.md +78 -0
- package/skills/prefill-cache/rules/LP-PC-05.md +67 -0
- package/skills/prefill-cache/rules/LP-PC-06.md +70 -0
- package/skills/prefill-cache/rules/LP-PC-07.md +96 -0
- package/skills/prefill-cache/rules/LP-PC-08.md +66 -0
- package/skills/prefill-cache/rules/LP-PC-09.md +74 -0
- package/skills/prefill-cache/rules/LP-PC-10.md +75 -0
- package/skills/prefill-cache/rules/LP-PC-11.md +71 -0
- package/skills/prefill-cache/rules/LP-PC-12.md +72 -0
- package/skills/prompt-diet/SKILL.md +68 -0
- package/skills/prompt-diet/rules/LP-PD-01.md +78 -0
- package/skills/prompt-diet/rules/LP-PD-02.md +72 -0
- package/skills/prompt-diet/rules/LP-PD-03.md +64 -0
- package/skills/prompt-diet/rules/LP-PD-04.md +76 -0
- package/skills/prompt-diet/rules/LP-PD-05.md +70 -0
- package/skills/prompt-diet/rules/LP-PD-06.md +67 -0
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: LP-PC-11
|
|
3
|
+
title: Keep pauses inside the cache lifetime
|
|
4
|
+
skill: prefill-cache
|
|
5
|
+
applies_to: [anthropic, openai, gemini, openrouter, deepinfra, vllm, sglang]
|
|
6
|
+
saves: prefill
|
|
7
|
+
severity: low
|
|
8
|
+
evidence:
|
|
9
|
+
- doc: https://platform.claude.com/docs/en/build-with-claude/prompt-caching
|
|
10
|
+
checked: 2026-11-26
|
|
11
|
+
- doc: https://developers.openai.com/api/docs/guides/prompt-caching
|
|
12
|
+
checked: 2026-11-26
|
|
13
|
+
- doc: https://openrouter.ai/docs/features/prompt-caching
|
|
14
|
+
checked: 2026-11-26
|
|
15
|
+
---
|
|
16
|
+
## Rule
|
|
17
|
+
Schedule work that shares a prefix so the gaps between its requests stay inside the provider's cache lifetime; where they cannot, pick a longer lifetime only when the break-even rule favours it, or expect a cold prefix.
|
|
18
|
+
|
|
19
|
+
## Why
|
|
20
|
+
A cached prefix expires after a period without use. The lifetimes differ by provider and option, and some are refreshed on each read; they are in the provider tables ([providers/anthropic.md](../../../providers/anthropic.md), [providers/openai.md](../../../providers/openai.md), [providers/gemini.md](../../../providers/gemini.md), [providers/deepinfra.md](../../../providers/deepinfra.md)). Self-hosted engines have no lifetime but evict under memory pressure ([providers/vllm.md](../../../providers/vllm.md), [providers/sglang.md](../../../providers/sglang.md)). On OpenRouter, sticky routing to the provider that holds the cache has its own inactivity timer ([providers/openrouter.md](../../../providers/openrouter.md)). Documented, not yet measured here.
|
|
21
|
+
|
|
22
|
+
The shapes: a batch job that processes documents round-robin, so each document's long prefix comes back only after every other document has been seen; an agent waiting for a human approval; a rate limiter that spaces calls further apart than the lifetime; a cron job that runs the same long prompt at an interval just over it.
|
|
23
|
+
|
|
24
|
+
Longer lifetimes cost more to write where they exist, and Gemini's explicit cache objects bill storage for as long as they live, so a longer lifetime is a cost decision, not a default (LP-PC-01, break-even rule).
|
|
25
|
+
|
|
26
|
+
## Detect in code
|
|
27
|
+
Python:
|
|
28
|
+
```
|
|
29
|
+
rg -n 'time\.sleep\(|asyncio\.sleep\(|RateLimiter|requests_per_minute|input\(|wait_for_approval' -g '*.py'
|
|
30
|
+
```
|
|
31
|
+
Shapes: `for item in items: for doc in docs: ask(doc, item)` (round-robin over documents with long shared prefixes); a sleep or rate limit between calls that share a prefix; a loop that waits on a human between turns.
|
|
32
|
+
|
|
33
|
+
TS/JS:
|
|
34
|
+
```
|
|
35
|
+
rg -n 'setTimeout\(|setInterval\(|minTime|p-limit|Bottleneck|cron' -g '*.{ts,tsx,js,mjs}'
|
|
36
|
+
```
|
|
37
|
+
Shapes: a `Bottleneck({ minTime })` limiter on a pipeline that re-sends one long prefix; a scheduled job whose interval is close to the lifetime.
|
|
38
|
+
|
|
39
|
+
Go:
|
|
40
|
+
```
|
|
41
|
+
rg -n 'time\.Sleep\(|time\.NewTicker\(|rate\.NewLimiter\(|cron\.' -g '*.go'
|
|
42
|
+
```
|
|
43
|
+
Shapes: a ticker-driven loop that re-sends a long shared prompt; a limiter shared by many prefixes so each prefix's turn comes rarely.
|
|
44
|
+
|
|
45
|
+
## Fix
|
|
46
|
+
Group requests by prefix in time.
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
# before: each document's prefix is reused only after all other documents have been seen
|
|
50
|
+
for q in questions:
|
|
51
|
+
for doc in docs:
|
|
52
|
+
answer(doc, q)
|
|
53
|
+
|
|
54
|
+
# after: all questions for one document while its prefix is warm
|
|
55
|
+
for doc in docs:
|
|
56
|
+
for q in questions:
|
|
57
|
+
answer(doc, q)
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
For a gap that cannot be avoided (a human in the loop), compare the cost of a rewrite at the default lifetime with a longer lifetime, using the break-even rule in LP-PC-01 and the multipliers in the provider table. Send a keep-warm request only when the next use is certain and its cost is below a rewrite, and never add it to the conversation history.
|
|
61
|
+
|
|
62
|
+
## Don't break meaning
|
|
63
|
+
Regrouping changes the order in which work runs, not the prompts, so answers do not change; but if a later item depends on an earlier result, keep that dependency order. A keep-warm request must not reach the user or the stored history.
|
|
64
|
+
|
|
65
|
+
## Verify
|
|
66
|
+
(a) Send the same prefix twice, once with a gap shorter than the lifetime and once with a longer gap. The first pair reports `cached_tokens` or `cache_read_input_tokens` on the second request; the second pair reports a cold prefix (no read, or a new cache write). That is expected, not a bug.
|
|
67
|
+
|
|
68
|
+
(b) kvsig: the two requests have equal `nodes` across the gap. Equal ids with a miss after a gap longer than the lifetime is a cold prefix; equal ids with a miss inside the lifetime point to another rule (LP-PC-01 marks, LP-PC-12 split).
|
|
69
|
+
|
|
70
|
+
## Waste signal
|
|
71
|
+
Measured: not counted against the app. The score caps "reusable" by the provider's cache lifetime, so a prefix last seen longer ago than the lifetime leaves E and S unchanged; the audit reports how many requests had a cold prefix. Static: severity low, with the break-even advice (mark, don't mark, longer lifetime, restructure).
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: LP-PC-12
|
|
3
|
+
title: Do not split one prefix across models or keys that do not share a cache
|
|
4
|
+
skill: prefill-cache
|
|
5
|
+
applies_to: [anthropic, openai, gemini, openrouter, deepinfra, vllm, sglang]
|
|
6
|
+
saves: prefill
|
|
7
|
+
severity: medium
|
|
8
|
+
evidence:
|
|
9
|
+
- doc: https://developers.openai.com/api/docs/guides/prompt-caching
|
|
10
|
+
checked: 2026-11-26
|
|
11
|
+
- doc: https://openrouter.ai/docs/features/provider-routing
|
|
12
|
+
checked: 2026-11-26
|
|
13
|
+
---
|
|
14
|
+
## Rule
|
|
15
|
+
Send requests that share a long prefix to the same model, the same provider route and the same cache key, and switch any of them per session, not per request.
|
|
16
|
+
|
|
17
|
+
## Why
|
|
18
|
+
A KV cache is computed by one model's weights, so two models never share one, and a cache lives with the provider (and the key, and on self-hosted servers the replica) that wrote it. Traffic that shares a prefix but is spread over several of them gives each part its own cold cache. This follows from how KV caches work; the cited pages document the key and routing behaviour. Not yet measured here.
|
|
19
|
+
|
|
20
|
+
- Models: an A/B test assigned per request; a cheap model for some turns of a session and a large one for others; a fallback chain that moves a conversation on the first error.
|
|
21
|
+
- Routes: a router load-balancing one model over several upstream providers. OpenRouter keeps a conversation with one provider only while that provider's cache is warm and the conditions in [providers/openrouter.md](../../../providers/openrouter.md) hold; fallbacks are on by default.
|
|
22
|
+
- Keys: OpenAI's `prompt_cache_key` routes requests that share it together ([providers/openai.md](../../../providers/openai.md)); a key unique per request, or per user when the prefix is per tenant, splits the group. On self-hosted servers a per-request `cache_salt` or session scope does the same.
|
|
23
|
+
- Replicas of one self-hosted model: reuse needs the request to reach the replica that holds the prefix. That is engine-side routing, covered in the `lmwarden` skill.
|
|
24
|
+
|
|
25
|
+
## Detect in code
|
|
26
|
+
Python:
|
|
27
|
+
```
|
|
28
|
+
rg -n 'random\.choice\(.*(model|MODEL)|prompt_cache_key\s*=|allow_fallbacks|"order"|models\s*=\s*\[|routing_strategy' -g '*.py'
|
|
29
|
+
```
|
|
30
|
+
Shapes: `model = random.choice(MODELS)` per request; `model = SMALL if is_easy(msg) else LARGE` inside one conversation; `prompt_cache_key=str(uuid.uuid4())`; a LiteLLM `Router` with `routing_strategy="simple-shuffle"` over several deployments; OpenRouter calls with no `provider` preferences on a long session.
|
|
31
|
+
|
|
32
|
+
TS/JS:
|
|
33
|
+
```
|
|
34
|
+
rg -n 'Math\.random\(\).*model|prompt_cache_key|allow_fallbacks|models:\s*\[' -g '*.{ts,tsx,js,mjs}'
|
|
35
|
+
```
|
|
36
|
+
Shapes: `model: Math.random() < split ? A : B` per request; `prompt_cache_key: crypto.randomUUID()`; an OpenRouter body with `models: [a, b]` as a per-request fallback list.
|
|
37
|
+
|
|
38
|
+
Go:
|
|
39
|
+
```
|
|
40
|
+
rg -n 'rand\.(Intn|IntN)\(len\(models|PromptCacheKey|AllowFallbacks' -g '*.go'
|
|
41
|
+
```
|
|
42
|
+
Shapes: `models[rand.Intn(len(models))]` per request; `PromptCacheKey: uuid.NewString()`.
|
|
43
|
+
|
|
44
|
+
## Fix
|
|
45
|
+
Make the choice once per session (or per tenant) and keep it.
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
# before
|
|
49
|
+
model = random.choice(["model-a", "model-b"])
|
|
50
|
+
resp = client.chat.completions.create(model=model, messages=history,
|
|
51
|
+
extra_body={"prompt_cache_key": str(uuid.uuid4())})
|
|
52
|
+
|
|
53
|
+
# after
|
|
54
|
+
model = session.model # assigned once, when the session starts
|
|
55
|
+
resp = client.chat.completions.create(model=model, messages=history,
|
|
56
|
+
extra_body={"prompt_cache_key": f"tenant:{tenant.id}",
|
|
57
|
+
"provider": {"order": [session.provider],
|
|
58
|
+
"allow_fallbacks": False}})
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
The `provider` block is OpenRouter's; leave it out for a direct provider. Fail over to another provider or model per session, after an error, and expect one cold prefix when you do.
|
|
62
|
+
|
|
63
|
+
## Don't break meaning
|
|
64
|
+
Pinning a route removes automatic fallbacks: keep error handling that moves the session elsewhere on failure, rather than failing the user. An A/B test assigned per session still compares the same two arms. Do not widen a cache key or scope across tenants that must stay isolated; isolation beats cache reuse.
|
|
65
|
+
|
|
66
|
+
## Verify
|
|
67
|
+
(a) Two consecutive requests of one session report the same model (and, on OpenRouter, the same upstream provider), and the second reports `cached_tokens` or `cache_read_input_tokens` covering the first.
|
|
68
|
+
|
|
69
|
+
(b) kvsig: in the usage log, requests whose exact `nodes` share a long prefix carry the same model and key. Equal `nodes` prefixes with different models or keys and `cached_tokens` of 0 is the split.
|
|
70
|
+
|
|
71
|
+
## Waste signal
|
|
72
|
+
Measured: lowers E. kvsig says the prefix was seen before, the provider reports no read because the earlier request went to another model, route or key. Static: severity medium for a per-request model choice, per-request cache key or unpinned router on long sessions.
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: prompt-diet
|
|
3
|
+
description: Use when writing, reviewing or debugging code that builds what an LLM call sends (tool and function lists, MCP tool sets, system prompts assembled from several templates, per-turn reminders or policies, tool results, retrieved RAG chunks, documents, conversation history, JSON put into the prompt) for Anthropic, OpenAI, Gemini, OpenRouter, DeepInfra or a self-hosted vLLM or SGLang server, or when usage shows prompt tokens per call far above what the answer needs or growing turn after turn. Cuts dead weight from the prompt without changing the answers and without breaking the provider's cache.
|
|
4
|
+
license: CC-BY-4.0
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# prompt-diet
|
|
8
|
+
|
|
9
|
+
Cuts dead weight from what each call sends: tools the call cannot use, instructions said twice, reminders sent on every turn, tool results and retrieved context passed whole, old turns that no longer bear on the answer, and data serialised with more characters than it needs. Six rules, `LP-PD-01` to `LP-PD-06`, each in its own file under `rules/`, each with a way to detect it in code, the smallest fix, what the fix must not break, and how to verify it.
|
|
10
|
+
|
|
11
|
+
The `prefill-cache` skill makes the prompt cheaper to read again. This skill makes it smaller in the first place. The two pull against each other at one point, the shared head of the prompt, and the rules below say how to settle it.
|
|
12
|
+
|
|
13
|
+
## When to use
|
|
14
|
+
|
|
15
|
+
- You are writing or changing the code that decides what a call sends: which tools it offers, how the system prompt is assembled, what goes into each user message, how tool results and retrieved chunks are put into the prompt, and how long the history is kept.
|
|
16
|
+
- Usage shows prompt tokens per call far above what the answer needs, or prompt tokens that grow turn after turn without the answers needing more context.
|
|
17
|
+
- The `llm-call-audit` skill sends you here for an `LP-PD-*` finding.
|
|
18
|
+
|
|
19
|
+
## Three things every trim must respect
|
|
20
|
+
|
|
21
|
+
1. **An answer check, before and after.** Cutting text from a prompt can change what the model does. Every trim ships with an answer check: a fixed set of inputs (synthetic, or recorded and anonymised), run through the `measure-loop` skill before and after on the same scenario, outputs compared, pass or fail. The trim ships only when the answers are unchanged or better.
|
|
22
|
+
2. **Weigh the cache before cutting the shared head.** A token in the cached head of the prompt (the tools, the system prompt) is read from the provider's cache on every later call at a fraction of the input price ([providers/anthropic.md](../../providers/anthropic.md), [providers/openai.md](../../providers/openai.md)). Cutting it saves little per call, and changing the head breaks the cached prefix for every call that follows until the new head is cached. Trim the head only when the saving over the cache lifetime is larger than one full prefill of the head on each route, and do it once, in one release, not per call. The rules of [prefill-cache](../prefill-cache/SKILL.md) say what must stay byte-identical.
|
|
23
|
+
3. **Do not strip blindly.** Stripping reasoning from the history to save tokens produced about 3x more generation in agent loops (E11): the model redid the work it could no longer see. Context that looks stale may be what keeps the model from repeating itself. Remove a kind of content only after the answer check shows the model does not need it, and keep what a provider requires (on Anthropic, the thinking blocks of a tool-use turn in progress).
|
|
24
|
+
|
|
25
|
+
## Workflow
|
|
26
|
+
|
|
27
|
+
1. **Know the target and priority.** Read `leanprompt.yaml` if the project has one (`target`, `priority`). Otherwise infer the provider and model from the SDK, `base_url` and model names, and ask if it is unclear. Open that provider's table; each has a "Prompt size facts" section where the provider documents them.
|
|
28
|
+
2. **Measure what each call sends.** For each call site, list what the request carries and roughly how big each part is: tools, system prompt, per-turn additions, tool results, retrieved context, history. Count with the provider's tokenizer or token-counting endpoint when you can; otherwise estimate from the text's length and say so.
|
|
29
|
+
3. **Check each rule,** in the order of the index below. Each rule's "Detect in code" gives `rg` patterns and code shapes for Python, TS/JS and Go. Open a rule file when its pattern matches.
|
|
30
|
+
4. **Propose the fix.** Give the rule id, file and line, and the smallest change from the rule's "Fix", with its "Don't break meaning" check and the cache question from point 2 above. When you are reviewing existing code, propose and ask before editing. When you are writing the call now, apply the rules directly.
|
|
31
|
+
5. **Verify.** Use the rule's "Verify": (a) the provider's usage fields (prompt or input tokens per call, cached tokens), and (b) the leanprompt usage record (`prompt_tokens` and `cached_tokens` per call, and the kvsig ids that must stay equal). Run the answer check with `measure-loop` on the same scenario before and after.
|
|
32
|
+
|
|
33
|
+
## Provider facts, in brief
|
|
34
|
+
|
|
35
|
+
What each provider documents lives only in the dated tables; read it there, not from memory.
|
|
36
|
+
|
|
37
|
+
- **Anthropic.** Tool definitions are input tokens, and any tool adds a tool use system prompt. Tools render first, so a change to the tool list invalidates the whole cached prefix. Within a tool-use turn, thinking blocks must be passed back unchanged; older ones are filtered by the API. Context editing (beta) can clear old tool results, which invalidates the cache from that point. [providers/anthropic.md](../../providers/anthropic.md)
|
|
38
|
+
- **OpenAI.** Function definitions count against the context limit and are billed as input tokens, and they are part of the cached prefix. `allowed_tools` restricts which tools a call may use while the tool list stays the same. [providers/openai.md](../../providers/openai.md)
|
|
39
|
+
- **Gemini.** Every function declaration is billed as input tokens on every request. [providers/gemini.md](../../providers/gemini.md)
|
|
40
|
+
- **OpenRouter and DeepInfra.** What the upstream provider does applies; tool definitions are rendered into the prompt the model reads. [providers/openrouter.md](../../providers/openrouter.md), [providers/deepinfra.md](../../providers/deepinfra.md)
|
|
41
|
+
- **vLLM and SGLang (self-hosted).** The chat template renders tool definitions into the prompt, so they cost prefill time and KV memory; a cached prefix is reused in whole blocks. [providers/vllm.md](../../providers/vllm.md), [providers/sglang.md](../../providers/sglang.md)
|
|
42
|
+
|
|
43
|
+
Evidence rows (E1 to E12) are in [docs/evidence.md](../../docs/evidence.md). A rule whose only source is provider documentation says "documented, not yet measured here".
|
|
44
|
+
|
|
45
|
+
## Rules
|
|
46
|
+
|
|
47
|
+
| Id | Rule | Severity | Evidence |
|
|
48
|
+
|---|---|---|---|
|
|
49
|
+
| [LP-PD-01](rules/LP-PD-01.md) | Offer each route only the tools it can use | medium | E11, provider docs |
|
|
50
|
+
| [LP-PD-02](rules/LP-PD-02.md) | Say each instruction once | low | E11, provider docs |
|
|
51
|
+
| [LP-PD-03](rules/LP-PD-03.md) | Do not resend the same boilerplate on every turn | medium | E11, provider docs |
|
|
52
|
+
| [LP-PD-04](rules/LP-PD-04.md) | Trim tool results and retrieved context at the tool boundary | high | E11, provider docs |
|
|
53
|
+
| [LP-PD-05](rules/LP-PD-05.md) | Drop stale history on purpose, not by stripping | medium | E11, provider docs |
|
|
54
|
+
| [LP-PD-06](rules/LP-PD-06.md) | Compact serialisation for data in the prompt | low | E11, provider docs |
|
|
55
|
+
|
|
56
|
+
## Reading the usage record
|
|
57
|
+
|
|
58
|
+
Dead weight shows as prompt tokens, not as cache misses. In `.leanprompt/usage.jsonl`:
|
|
59
|
+
|
|
60
|
+
- **Per call:** `prompt_tokens` for the same call site (same `ids.head` and the same kind of input) falls after a trim, by about the size of what was cut.
|
|
61
|
+
- **Over a conversation:** `prompt_tokens` that rise turn after turn by more than the new user message and the last answer point at per-turn boilerplate (LP-PD-03), whole tool results (LP-PD-04) or history that is never dropped (LP-PD-05).
|
|
62
|
+
- **The head:** `ids.head`, `ids.sys` and `ids.tools` stay equal from call to call within a route after the fix; a trim that changes them on every call has broken the cache (LP-PC-03, LP-PC-04).
|
|
63
|
+
|
|
64
|
+
The score does not count prompt size: its prefill side measures reuse, so a smaller prompt can leave it unchanged. The report shows a prompt-diet finding by its tokens per 1,000 calls (`tokens_per_1k.prompt`), and with prices, in money.
|
|
65
|
+
|
|
66
|
+
## What this skill does not do
|
|
67
|
+
|
|
68
|
+
It does not compress prompts by rewriting them on the wire, it does not make the prompt cache better (that is `prefill-cache`), it does not change how much the model generates or how output is formatted (that is `generation-economy`), and it does not promise a saving for an app it has not measured.
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: LP-PD-01
|
|
3
|
+
title: Offer each route only the tools it can use
|
|
4
|
+
skill: prompt-diet
|
|
5
|
+
applies_to: [anthropic, openai, gemini, openrouter, deepinfra, vllm, sglang, any]
|
|
6
|
+
saves: prefill
|
|
7
|
+
severity: medium
|
|
8
|
+
evidence:
|
|
9
|
+
- E11
|
|
10
|
+
- doc: https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview
|
|
11
|
+
checked: 2026-11-26
|
|
12
|
+
- doc: https://developers.openai.com/api/docs/guides/function-calling
|
|
13
|
+
checked: 2026-11-26
|
|
14
|
+
- doc: https://developers.openai.com/api/docs/guides/prompt-caching
|
|
15
|
+
checked: 2026-11-26
|
|
16
|
+
- doc: https://aistudio.google.com/docs/function-calling
|
|
17
|
+
checked: 2026-11-26
|
|
18
|
+
---
|
|
19
|
+
## Rule
|
|
20
|
+
Give each route (a kind of call with its own job) a fixed tool list that holds only the tools the app's flow lets the model use on that route, instead of sending every registered tool on every call.
|
|
21
|
+
|
|
22
|
+
## Why
|
|
23
|
+
Tool definitions are prompt tokens. Anthropic prices tool use on all input tokens "including in the `tools` parameter" and adds a tool use system prompt whenever a tool is present; OpenAI says function definitions "count against the model's context limit and are billed as input tokens"; Gemini says every function declaration "is billed as input tokens on every request" ([providers/anthropic.md](../../../providers/anthropic.md), [providers/openai.md](../../../providers/openai.md), [providers/gemini.md](../../../providers/gemini.md)). A title call, a classifier or a summariser that is sent the agent's whole tool registry pays for tools it is never allowed to call, and a self-hosted engine spends prefill time and KV memory on them ([providers/vllm.md](../../../providers/vllm.md)).
|
|
24
|
+
|
|
25
|
+
The cache pulls the other way. Tools render first on Anthropic and sit in the cached prefix on OpenAI, so a tool list that changes from call to call within one conversation loses the whole cached prefix on every change (LP-PC-04, LP-PC-05). The fix is therefore per route, not per call: each route has one list that never changes while its conversations run. Where a route's turns need different subsets, keep the list and restrict the choice instead: OpenAI `tool_choice: {"type": "allowed_tools", ...}` restricts which tools may be called while the list stays the same, which the docs give as the way to keep prompt caching ([providers/openai.md](../../../providers/openai.md)). Documented, not yet measured here.
|
|
26
|
+
|
|
27
|
+
## Detect in code
|
|
28
|
+
Python:
|
|
29
|
+
```
|
|
30
|
+
rg -n 'tools\s*=\s*(ALL_TOOLS|TOOLS|registry|tool_registry|get_tools\(\))|tools=\[\*|list_tools\(\)' -g '*.py'
|
|
31
|
+
rg -n 'tool_choice\s*=\s*["\x27]none|tool_choice=\{"type":\s*"none' -g '*.py'
|
|
32
|
+
```
|
|
33
|
+
Shapes: one module-level `TOOLS` (or every MCP server's tools) passed to every `create(...)` call, including calls whose code never handles a `tool_use` or `tool_calls` reply; `tool_choice="none"` on a call that still sends the full list; a list built per call from the user's message or permissions inside one conversation (that is a cache break, LP-PC-04).
|
|
34
|
+
|
|
35
|
+
TS/JS:
|
|
36
|
+
```
|
|
37
|
+
rg -n 'tools:\s*(allTools|TOOLS|registry|Object\.values\(tools\)|await \w+\.listTools\(\))' -g '*.{ts,tsx,js,mjs}'
|
|
38
|
+
```
|
|
39
|
+
Shapes: Vercel AI SDK `generateText({ tools: allTools, ... })` for a call that only needs text; one shared options object with `tools` spread into every request.
|
|
40
|
+
|
|
41
|
+
Go:
|
|
42
|
+
```
|
|
43
|
+
rg -n 'Tools:\s*(allTools|AllTools|registry\.|tools\b)' -g '*.go'
|
|
44
|
+
```
|
|
45
|
+
Shapes: one package-level `[]Tool` slice used in the params of every request type.
|
|
46
|
+
|
|
47
|
+
## Fix
|
|
48
|
+
```python
|
|
49
|
+
# before: every call gets the whole registry
|
|
50
|
+
TOOLS = registry.all()
|
|
51
|
+
title = client.messages.create(model=M, tools=TOOLS, messages=[ask_for_title(chat)], max_tokens=64)
|
|
52
|
+
answer = client.messages.create(model=M, tools=TOOLS, system=AGENT_SYSTEM, messages=history, max_tokens=2048)
|
|
53
|
+
|
|
54
|
+
# after: one fixed, sorted list per route, built once
|
|
55
|
+
ROUTE_TOOLS = {
|
|
56
|
+
"title": [], # never calls a tool
|
|
57
|
+
"agent": sorted(registry.for_agent(), key=lambda t: t["name"]), # the same list on every turn
|
|
58
|
+
}
|
|
59
|
+
title = client.messages.create(model=M, messages=[ask_for_title(chat)], max_tokens=64)
|
|
60
|
+
answer = client.messages.create(model=M, tools=ROUTE_TOOLS["agent"], system=AGENT_SYSTEM, messages=history, max_tokens=2048)
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
On OpenAI, when one conversation needs a smaller set for some turns, keep the list and narrow the choice:
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
tool_choice={"type": "allowed_tools", "mode": "auto", "tools": [{"type": "function", "name": "search_docs"}]}
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Don't break meaning
|
|
70
|
+
Remove a tool from a route only when the code shows the model can never use it there: no handler for it on that route, or a flow that forbids it. A tool the model rarely calls may still be the one it needs; check the logs or the code path, not your intuition. Run the answer check with `measure-loop` on a fixed set of inputs for that route, before and after: answers unchanged or better, and no new "I cannot do that" replies. Weigh the cache before changing the agent's own list: the tools are the start of its cached head, so change them once, in one release, and never per call. Do not drop tool calls or tool results from the history to match the new list; stripping what the model already did made it redo the work: about 3x more generation (E11). The head and what keeps it cached: [prefill-cache](../../prefill-cache/SKILL.md).
|
|
71
|
+
|
|
72
|
+
## Verify
|
|
73
|
+
(a) Provider usage: `usage.input_tokens` (Anthropic), `usage.prompt_tokens` or `usage.input_tokens` (OpenAI, Gemini `promptTokenCount`) per call on the trimmed route falls by about the size of the removed tool definitions. On the agent route, `cache_read_input_tokens` or `cached_tokens` on the second turn is at least the size of the new head, as before the fix.
|
|
74
|
+
|
|
75
|
+
(b) leanprompt usage record: `prompt_tokens` for the route's calls falls; `ids.tools` is the same on every call of the route (the list is fixed per route), and `ids.head` stays equal within each conversation.
|
|
76
|
+
|
|
77
|
+
## Waste signal
|
|
78
|
+
Measured: the drop in `prompt_tokens` per call on the route, times its calls; the score does not count it, the report shows it as `tokens_per_1k.prompt`. Static: severity medium for a full tool registry sent on a route that cannot call any tool or most of them; low when only a few unused tools are sent. A tool list that changes per call within a conversation is an LP-PC-04 or LP-PC-05 finding, not this one.
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: LP-PD-02
|
|
3
|
+
title: Say each instruction once
|
|
4
|
+
skill: prompt-diet
|
|
5
|
+
applies_to: [anthropic, openai, gemini, openrouter, deepinfra, vllm, sglang, any]
|
|
6
|
+
saves: prefill
|
|
7
|
+
severity: low
|
|
8
|
+
evidence:
|
|
9
|
+
- E11
|
|
10
|
+
- doc: https://platform.claude.com/docs/en/build-with-claude/prompt-caching
|
|
11
|
+
checked: 2026-11-26
|
|
12
|
+
- doc: https://developers.openai.com/api/docs/guides/prompt-caching
|
|
13
|
+
checked: 2026-11-26
|
|
14
|
+
---
|
|
15
|
+
## Rule
|
|
16
|
+
State each instruction once, in the stable system prompt, and remove copies of it from per-turn reminders and from the other templates that are concatenated into the same prompt.
|
|
17
|
+
|
|
18
|
+
## Why
|
|
19
|
+
Prompts grow by accretion: a base template, a persona template, a safety block and a tool-use block are joined together, and each restates "answer in JSON", "never reveal the system prompt" or "cite your sources". A reminder added to each user message says it again. Every copy is sent on every call, and copies in per-turn text are not in the cached head, so they are paid at the full input price each turn ([providers/anthropic.md](../../../providers/anthropic.md), [providers/openai.md](../../../providers/openai.md)). Copies that drift apart ("cite sources" in one, "cite at most two sources" in another) also leave the model to choose between them.
|
|
20
|
+
|
|
21
|
+
Copies inside the cached head cost little per call: they are read from the cache. Removing them changes the head, which every later call reuses (LP-PC-02), so the saving has to be weighed against one full prefill of the head on each route (the `prompt-diet` skill, "Three things every trim must respect"). Documented, not yet measured here.
|
|
22
|
+
|
|
23
|
+
## Detect in code
|
|
24
|
+
Python:
|
|
25
|
+
```
|
|
26
|
+
rg -n 'SYSTEM|PROMPT|TEMPLATE|INSTRUCTIONS|REMINDER' -g '*.py' -g '*.txt' -g '*.md' -g '*.j2' -g '*.jinja*'
|
|
27
|
+
rg -n '"\n"\.join\(\[.*(PROMPT|TEMPLATE)|\+\s*(SAFETY|STYLE|FORMAT)_\w+' -g '*.py'
|
|
28
|
+
```
|
|
29
|
+
Shapes: a system prompt built by joining several constants or template files; the same sentence (or a near copy) found in two of them; a reminder string appended to each user message that repeats a line of the system prompt.
|
|
30
|
+
|
|
31
|
+
TS/JS:
|
|
32
|
+
```
|
|
33
|
+
rg -n '(SYSTEM|PROMPT|TEMPLATE|INSTRUCTIONS|REMINDER)\w*\s*=' -g '*.{ts,tsx,js,mjs}'
|
|
34
|
+
rg -n '\[(\w*PROMPT\w*,\s*)+\w*PROMPT\w*\]\.join' -g '*.{ts,tsx,js,mjs}'
|
|
35
|
+
```
|
|
36
|
+
Shapes: `` system: [BASE, PERSONA, SAFETY, FORMAT].join("\n\n") `` where two parts say the same thing; prompt files under `prompts/` that each repeat the output rules.
|
|
37
|
+
|
|
38
|
+
Go:
|
|
39
|
+
```
|
|
40
|
+
rg -n '(System|Prompt|Template|Instructions|Reminder)\w*\s*=\s*`|strings\.Join\(\[\]string\{' -g '*.go'
|
|
41
|
+
```
|
|
42
|
+
Shapes: raw-string prompt constants joined with `strings.Join`, two of them sharing a paragraph.
|
|
43
|
+
|
|
44
|
+
To find copies, normalise case and whitespace and compare sentences across the parts; a short script or a careful read of the assembled prompt (print it once) is enough.
|
|
45
|
+
|
|
46
|
+
## Fix
|
|
47
|
+
```python
|
|
48
|
+
# before: the output rule three times, once per turn
|
|
49
|
+
BASE = "You are a support assistant. Answer in JSON with keys answer and sources."
|
|
50
|
+
FORMAT = "Always answer in JSON with keys answer and sources. Cite your sources."
|
|
51
|
+
SYSTEM = BASE + "\n\n" + PERSONA + "\n\n" + FORMAT
|
|
52
|
+
user = {"role": "user", "content": question + "\n\nRemember: answer in JSON with keys answer and sources."}
|
|
53
|
+
|
|
54
|
+
# after: once, in the stable system prompt, merged into one wording
|
|
55
|
+
BASE = "You are a support assistant."
|
|
56
|
+
FORMAT = "Answer in JSON with keys answer and sources. Cite your sources."
|
|
57
|
+
SYSTEM = BASE + "\n\n" + PERSONA + "\n\n" + FORMAT
|
|
58
|
+
user = {"role": "user", "content": question}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Where the copies differ, keep the version the app relies on and say so in the change; do not merge two different rules into a new third one without the answer check.
|
|
62
|
+
|
|
63
|
+
## Don't break meaning
|
|
64
|
+
A repeated instruction is sometimes there because it was needed: a format rule restated near the end of a long prompt can be what keeps the model on format. Remove a copy only after the answer check with `measure-loop` on a fixed set of inputs, before and after, shows answers unchanged or better, with the format checks of the app (schema, length, refusals) passing. Weigh the cache before editing the head; change it once, not per call. Never strip earlier turns or reasoning from the history as part of this change; stripping reasoning produced about 3x more generation (E11). What must stay byte-identical in the head: [prefill-cache](../../prefill-cache/SKILL.md).
|
|
65
|
+
|
|
66
|
+
## Verify
|
|
67
|
+
(a) Provider usage: `usage.input_tokens` or `usage.prompt_tokens` per call falls by about the size of the removed copies; for copies removed from per-turn text, the uncached part of each turn falls (`input_tokens` minus `cache_read_input_tokens`, or `prompt_tokens` minus `cached_tokens`).
|
|
68
|
+
|
|
69
|
+
(b) leanprompt usage record: `prompt_tokens` for the call site falls; after the one-time change, `ids.sys` and `ids.head` are again equal from call to call within each route.
|
|
70
|
+
|
|
71
|
+
## Waste signal
|
|
72
|
+
Measured: the drop in `prompt_tokens` per call times the calls; the score does not count it, the report shows it as `tokens_per_1k.prompt`. Static: severity low for copies inside the cached head (they are read from the cache); medium when the copy is in per-turn text, where it is sent uncached on every turn (that shape is also LP-PD-03).
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: LP-PD-03
|
|
3
|
+
title: Do not resend the same boilerplate on every turn
|
|
4
|
+
skill: prompt-diet
|
|
5
|
+
applies_to: [anthropic, openai, gemini, openrouter, deepinfra, vllm, sglang, any]
|
|
6
|
+
saves: prefill
|
|
7
|
+
severity: medium
|
|
8
|
+
evidence:
|
|
9
|
+
- E11
|
|
10
|
+
- doc: https://platform.claude.com/docs/en/build-with-claude/prompt-caching
|
|
11
|
+
checked: 2026-11-26
|
|
12
|
+
- doc: https://developers.openai.com/api/docs/guides/prompt-caching
|
|
13
|
+
checked: 2026-11-26
|
|
14
|
+
---
|
|
15
|
+
## Rule
|
|
16
|
+
Put policies, reminders and fixed context that apply to the whole conversation in the stable system prompt once, instead of wrapping every user message in the same block of text.
|
|
17
|
+
|
|
18
|
+
## Why
|
|
19
|
+
Some apps wrap each user message in a template: the policy, the style guide, "remember the rules above", a list of the user's settings that has not changed. The block is sent again in every new message, so a conversation of many turns carries many copies of it, and the history grows by the block on every turn. Each new copy is in the uncached tail of its request and is paid at the full input price; the older copies are read from the cache on later turns, but they still fill the context window and, on a self-hosted engine, KV memory ([providers/anthropic.md](../../../providers/anthropic.md), [providers/openai.md](../../../providers/openai.md), [providers/vllm.md](../../../providers/vllm.md)). Documented, not yet measured here.
|
|
20
|
+
|
|
21
|
+
Text that really changes per turn (the current time, a fresh retrieval) belongs in the newest message (LP-PC-03); this rule is about text that is the same every turn.
|
|
22
|
+
|
|
23
|
+
## Detect in code
|
|
24
|
+
Python:
|
|
25
|
+
```
|
|
26
|
+
rg -n 'content["\x27]?\s*[:=]\s*f?["\x27]{1,3}.*\{(policy|rules|reminder|guidelines|instructions|context)\}' -g '*.py'
|
|
27
|
+
rg -n '(REMINDER|POLICY|GUIDELINES|RULES)\w*\s*\+\s*(user_)?(msg|message|input|query)|\+\s*(REMINDER|POLICY)' -g '*.py'
|
|
28
|
+
```
|
|
29
|
+
Shapes: `{"role": "user", "content": POLICY + "\n\n" + user_text}` in the turn loop; a `wrap_user_message()` helper that adds the same header to every turn; settings re-rendered into each message although they change once per session.
|
|
30
|
+
|
|
31
|
+
TS/JS:
|
|
32
|
+
```
|
|
33
|
+
rg -n 'content:\s*`\$\{(POLICY|REMINDER|RULES|GUIDELINES)\w*\}' -g '*.{ts,tsx,js,mjs}'
|
|
34
|
+
```
|
|
35
|
+
Shapes: `` messages.push({ role: "user", content: `${REMINDER}\n\n${input}` }) ``; a middleware that prepends the same block to each user turn.
|
|
36
|
+
|
|
37
|
+
Go:
|
|
38
|
+
```
|
|
39
|
+
rg -n 'Content:\s*(policy|reminder|rules)\w*\s*\+|fmt\.Sprintf\("%s\\n\\n%s",\s*(policy|reminder)' -g '*.go'
|
|
40
|
+
```
|
|
41
|
+
Shapes: `Content: reminder + "\n\n" + input` inside the request loop.
|
|
42
|
+
|
|
43
|
+
## Fix
|
|
44
|
+
```python
|
|
45
|
+
# before: the policy rides on every user message
|
|
46
|
+
history.append({"role": "user", "content": POLICY + "\n\n" + user_text})
|
|
47
|
+
|
|
48
|
+
# after: once, in the system prompt, which stays byte-identical for the session
|
|
49
|
+
SYSTEM = BASE_PROMPT + "\n\n" + POLICY
|
|
50
|
+
history.append({"role": "user", "content": user_text})
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Make the change for new conversations. Do not rewrite the user messages already sent in a running conversation to remove the block: that rewrites the history and loses its cached prefix (LP-PC-06).
|
|
54
|
+
|
|
55
|
+
## Don't break meaning
|
|
56
|
+
Some apps repeat a reminder on purpose, because in long conversations the model drifts from instructions it saw only at the start. Move the block only after the answer check with `measure-loop`, on a fixed set of long conversations (as many turns as the app really sees), before and after: answers unchanged or better on the late turns too. If the late turns drift, keep a one-line reminder instead of the whole block. Weigh the cache: adding the policy to the system prompt changes the head once, which is a cost of one prefill per route. Do not strip the copies, tool results or reasoning from history to save more; stripping reasoning produced about 3x more generation (E11). What must stay byte-identical in the head: [prefill-cache](../../prefill-cache/SKILL.md).
|
|
57
|
+
|
|
58
|
+
## Verify
|
|
59
|
+
(a) Provider usage: the uncached part of each turn (`input_tokens` minus `cache_read_input_tokens`, or `prompt_tokens` minus `cached_tokens`) falls by about the size of the block, and `prompt_tokens` on late turns of a long conversation falls by about the block times the turns so far. `cached_tokens` on the second turn still covers the head.
|
|
60
|
+
|
|
61
|
+
(b) leanprompt usage record: `prompt_tokens` grows turn over turn by about the user message plus the last answer, not by the block too; `ids.sys` is equal on every turn of the conversation.
|
|
62
|
+
|
|
63
|
+
## Waste signal
|
|
64
|
+
Measured: the drop in `prompt_tokens` across a conversation, times conversations; the score does not count it, the report shows it as `tokens_per_1k.prompt`. Static: severity medium for a fixed block wrapped around every user message in a multi-turn conversation; low for a short reminder line.
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: LP-PD-04
|
|
3
|
+
title: Trim tool results and retrieved context at the tool boundary
|
|
4
|
+
skill: prompt-diet
|
|
5
|
+
applies_to: [anthropic, openai, gemini, openrouter, deepinfra, vllm, sglang, any]
|
|
6
|
+
saves: prefill
|
|
7
|
+
severity: high
|
|
8
|
+
evidence:
|
|
9
|
+
- E11
|
|
10
|
+
- doc: https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview
|
|
11
|
+
checked: 2026-11-26
|
|
12
|
+
- doc: https://developers.openai.com/api/docs/guides/prompt-caching
|
|
13
|
+
checked: 2026-11-26
|
|
14
|
+
---
|
|
15
|
+
## Rule
|
|
16
|
+
Before a tool result or a retrieved document enters the prompt, cut it to what the model needs for the task: select the fields, cap the rows and the length, and summarise long text, in the code that runs the tool, so the smaller version is the only one the history ever holds.
|
|
17
|
+
|
|
18
|
+
## Why
|
|
19
|
+
A tool that returns a whole API response, a database row with every column, a web page with its markup, or ten retrieved chunks where two answer the question, puts all of it into the prompt. Anthropic counts `tool_result` blocks as input tokens ([providers/anthropic.md](../../../providers/anthropic.md)). In an agent loop the result stays in the history, so it is paid once uncached on the next call and then on every later call of the conversation, read from the cache or, after the cache lifetime, at the full price again ([providers/openai.md](../../../providers/openai.md)). Large results also push conversations into compaction sooner (LP-PC-08). Documented, not yet measured here.
|
|
20
|
+
|
|
21
|
+
The boundary matters for the cache. Trim when the result is first added: the trimmed text then never changes, and the history stays append-only. Shortening a result later, after it has been sent, rewrites the history and loses the cached prefix from that point (LP-PC-06).
|
|
22
|
+
|
|
23
|
+
## Detect in code
|
|
24
|
+
Python:
|
|
25
|
+
```
|
|
26
|
+
rg -n '"content":\s*(json\.dumps\()?(resp|response|result|data|r)\.(json\(\)|text|content)\b|tool_result' -g '*.py'
|
|
27
|
+
rg -n 'similarity_search\(|\.query\(.*(top_k|k)\s*=\s*\d{2,}|as_retriever\(' -g '*.py'
|
|
28
|
+
```
|
|
29
|
+
Shapes: `{"type": "tool_result", "content": json.dumps(resp.json())}` with the raw response; `requests.get(url).text` (HTML) passed as a tool result; `top_k=20` retrieval joined into the prompt with no cap on length; a SQL tool that returns `SELECT *`.
|
|
30
|
+
|
|
31
|
+
TS/JS:
|
|
32
|
+
```
|
|
33
|
+
rg -n 'content:\s*(JSON\.stringify\()?(await \w+\.(json|text)\(\)|res(ponse)?\.data|result)\b' -g '*.{ts,tsx,js,mjs}'
|
|
34
|
+
rg -n 'topK:\s*\d{2,}|similaritySearch\(' -g '*.{ts,tsx,js,mjs}'
|
|
35
|
+
```
|
|
36
|
+
Shapes: an MCP tool handler that returns the upstream payload as text; `role: "tool", content: JSON.stringify(data)` with the full object.
|
|
37
|
+
|
|
38
|
+
Go:
|
|
39
|
+
```
|
|
40
|
+
rg -n 'io\.ReadAll\(|json\.Marshal\((resp|result|data)\)' -g '*.go'
|
|
41
|
+
```
|
|
42
|
+
Shapes: a tool handler that returns `string(body)` from `io.ReadAll(resp.Body)` with no field selection or limit.
|
|
43
|
+
|
|
44
|
+
## Fix
|
|
45
|
+
```python
|
|
46
|
+
# before: the whole response goes into the history
|
|
47
|
+
def get_order(order_id):
|
|
48
|
+
return requests.get(f"{API}/orders/{order_id}", timeout=10).json() # dozens of fields, nested
|
|
49
|
+
|
|
50
|
+
messages.append({"role": "user", "content": [{"type": "tool_result", "tool_use_id": tid, "content": json.dumps(get_order(oid))}]})
|
|
51
|
+
|
|
52
|
+
# after: the tool returns what the task needs, with a cap, decided once at the boundary
|
|
53
|
+
ORDER_FIELDS = ("id", "status", "items", "total", "shipped_at")
|
|
54
|
+
MAX_ITEMS = 20
|
|
55
|
+
|
|
56
|
+
def get_order(order_id):
|
|
57
|
+
raw = requests.get(f"{API}/orders/{order_id}", timeout=10).json()
|
|
58
|
+
out = {k: raw[k] for k in ORDER_FIELDS if k in raw}
|
|
59
|
+
if len(out.get("items", [])) > MAX_ITEMS:
|
|
60
|
+
out["items"] = out["items"][:MAX_ITEMS]
|
|
61
|
+
out["items_truncated"] = True # tell the model, so it can ask for more
|
|
62
|
+
return out
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
For retrieval, cap the number of chunks and their total length, and drop near-duplicate chunks before they are joined into the prompt. For long text the model only needs the gist of, summarise it in the tool (a small model can do it) and offer a follow-up tool to fetch the full text when it is needed.
|
|
66
|
+
|
|
67
|
+
## Don't break meaning
|
|
68
|
+
The field the model needs is sometimes the one you would cut. Choose the fields from what the app's answers use (read the prompts and the outputs), say in the result when it was cut, and give the model a way to get more (a page argument, a "full" flag). Run the answer check with `measure-loop` on a fixed set of inputs that exercise each tool, before and after: answers unchanged or better, and no new extra tool calls to fetch what was cut; extra calls cost more than they save. Do not trim tool results already in the history, and do not strip the model's reasoning about them: stripping reasoning made agents redo the work: about 3x more generation (E11). These results are not part of the shared head, so trimming them at the boundary does not break any other call's cache. The append-only history this relies on: [prefill-cache](../../prefill-cache/SKILL.md) (LP-PC-06).
|
|
69
|
+
|
|
70
|
+
## Verify
|
|
71
|
+
(a) Provider usage: on the call after a tool runs, the uncached input (`input_tokens` minus `cache_read_input_tokens` on Anthropic, `prompt_tokens` minus `cached_tokens` on OpenAI) falls by about the size cut from the result; on later turns `prompt_tokens` stays lower by the same amount. The number of tool calls per task does not rise.
|
|
72
|
+
|
|
73
|
+
(b) leanprompt usage record: `prompt_tokens` per turn of agent conversations falls; `cached_tokens` on the next turn still covers everything up to the new result (the history stays append-only, `ids.nodes` of earlier messages unchanged).
|
|
74
|
+
|
|
75
|
+
## Waste signal
|
|
76
|
+
Measured: the drop in `prompt_tokens` per turn times the turns after each tool call; the score does not count it, the report shows it as `tokens_per_1k.prompt`. Static: severity high for raw API responses, HTML pages or `SELECT *` results put whole into an agent loop's history; medium for retrieval with no cap on chunks or length; low for a few unused fields.
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: LP-PD-05
|
|
3
|
+
title: Drop stale history on purpose, not by stripping
|
|
4
|
+
skill: prompt-diet
|
|
5
|
+
applies_to: [anthropic, openai, gemini, openrouter, deepinfra, vllm, sglang, any]
|
|
6
|
+
saves: prefill
|
|
7
|
+
severity: medium
|
|
8
|
+
evidence:
|
|
9
|
+
- E11
|
|
10
|
+
- doc: https://platform.claude.com/docs/en/build-with-claude/thinking
|
|
11
|
+
checked: 2026-11-26
|
|
12
|
+
- doc: https://platform.claude.com/docs/en/build-with-claude/context-editing
|
|
13
|
+
checked: 2026-11-26
|
|
14
|
+
- doc: https://platform.claude.com/docs/en/build-with-claude/prompt-caching
|
|
15
|
+
checked: 2026-11-26
|
|
16
|
+
---
|
|
17
|
+
## Rule
|
|
18
|
+
Keep a long conversation's history bounded with one deliberate step taken rarely (compaction past a size threshold, or clearing old tool outputs in one large cut), and never by removing pieces of earlier turns on every call.
|
|
19
|
+
|
|
20
|
+
## Why
|
|
21
|
+
An agent that keeps every turn and every tool output sends all of it on every call. Past some point most of it no longer bears on the answer: the files read before the last edit, the search results of a question already answered. Each call pays for it, read from the cache at a fraction of the price or, after a pause longer than the cache lifetime, at the full price (LP-PC-11).
|
|
22
|
+
|
|
23
|
+
Trimming it the wrong way costs more than it saves. Removing old messages or old tool outputs a little on every call rewrites the history, so the cached prefix ends at the first removed piece and everything after it is prefilled again on every call (LP-PC-06). Stripping the model's earlier reasoning to save tokens produced about 3x more generation in agent loops (E11): the model redid the reasoning it could no longer see. On Anthropic, the thinking blocks of a tool-use turn in progress must be passed back complete and unmodified, the API itself filters older thinking blocks, and on models with preserved thinking a change to an earlier message can make the request fail ([providers/anthropic.md](../../../providers/anthropic.md)).
|
|
24
|
+
|
|
25
|
+
So the step is rare and large. Compaction (summarise and continue) is described in LP-PC-08, which says how to keep the head cached across it; this rule says when to do it and what to keep. On Anthropic, context editing (beta) can clear old tool results past a token trigger, and its `clear_at_least` setting skips a clearing that would remove too little to be worth the cache write ([providers/anthropic.md](../../../providers/anthropic.md)). Documented, not yet measured here.
|
|
26
|
+
|
|
27
|
+
## Detect in code
|
|
28
|
+
Python:
|
|
29
|
+
```
|
|
30
|
+
rg -n 'messages\s*=\s*messages\[-\d+:\]|history\[-\d+:\]|messages\.pop\(\d*\)|del messages\[' -g '*.py'
|
|
31
|
+
rg -n '(strip|remove|drop)_(thinking|reasoning)|block\.type\s*[!=]=\s*.(thinking|reasoning)' -g '*.py'
|
|
32
|
+
```
|
|
33
|
+
Shapes: a sliding window (`history[-10:]`) applied on every call; a loop that deletes or shortens old `tool_result` contents each turn; a filter that removes `thinking` or `reasoning` blocks from assistant messages before resending; the opposite, a history that grows with no bound and no compaction at all.
|
|
34
|
+
|
|
35
|
+
TS/JS:
|
|
36
|
+
```
|
|
37
|
+
rg -n 'messages\.slice\(-\d+\)|history\.slice\(-\d+\)|\.shift\(\)|filter\(\s*\(?\w+\)?\s*=>\s*\w+\.type\s*!==\s*.(thinking|reasoning)' -g '*.{ts,tsx,js,mjs}'
|
|
38
|
+
```
|
|
39
|
+
Shapes: `messages = messages.slice(-20)` before each request; old tool outputs replaced with `"[truncated]"` in place, turn by turn.
|
|
40
|
+
|
|
41
|
+
Go:
|
|
42
|
+
```
|
|
43
|
+
rg -n 'messages\[len\(messages\)-\d+:\]|history\[len\(history\)-\d+:\]' -g '*.go'
|
|
44
|
+
```
|
|
45
|
+
Shapes: a window re-sliced on every request.
|
|
46
|
+
|
|
47
|
+
## Fix
|
|
48
|
+
```python
|
|
49
|
+
# before: a sliding window every call, and reasoning stripped from the history
|
|
50
|
+
messages = strip_thinking(history)[-12:]
|
|
51
|
+
resp = client.messages.create(model=M, system=SYSTEM, tools=TOOLS, messages=messages, max_tokens=2048)
|
|
52
|
+
|
|
53
|
+
# after: the history is sent as it is, append-only, and compacted rarely, past a threshold
|
|
54
|
+
if estimate_tokens(history) > COMPACT_AT: # a threshold well above a typical task
|
|
55
|
+
history = compact(history) # LP-PC-08: same system and tools, summary appended
|
|
56
|
+
resp = client.messages.create(model=M, system=SYSTEM, tools=TOOLS, messages=history, max_tokens=2048)
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
When the bulk of an agent's history is old tool output, clearing it in one cut can replace compaction. On Anthropic that is context editing with a `clear_tool_uses_20250919` edit, a `trigger`, a `keep` count for the latest results, and `clear_at_least` (beta; check the table for the current header). Elsewhere, do the same in code: past the threshold, replace the content of old tool results with a short placeholder in one step, then append-only again.
|
|
60
|
+
|
|
61
|
+
## Don't break meaning
|
|
62
|
+
What looks stale may be what the model needs: the file it read before the edit, the error that explains the retry. Choose the threshold and what is kept (the latest turns, the latest tool results, the task statement, the decisions made) with the answer check from `measure-loop`: a fixed set of long conversations or agent tasks, run before and after on the same scenario, with answers or task results unchanged or better and no rise in output tokens or tool calls; after stripping reasoning, agents made about 3x more generation (E11). Never strip thinking or reasoning blocks to save tokens, and keep the current tool-use turn whole. The compaction step must keep the system prompt and tools byte-identical (LP-PC-08); cutting the shared head to make room breaks the prefix for every later call. How compaction keeps the head cached: [prefill-cache](../../prefill-cache/SKILL.md) (LP-PC-08).
|
|
63
|
+
|
|
64
|
+
## Verify
|
|
65
|
+
(a) Provider usage: between compactions, each call's `cache_read_input_tokens` or `cached_tokens` covers everything up to the newest messages (the history is append-only again); after a compaction or clearing, `input_tokens` or `prompt_tokens` falls by about what was removed and `cached_tokens` still covers the head. `output_tokens` per task does not rise after the change.
|
|
66
|
+
|
|
67
|
+
(b) leanprompt usage record: `ids.nodes` of earlier messages are equal from call to call between compactions; `prompt_tokens` per call stays below the threshold; `output_tokens` per conversation is not higher than before.
|
|
68
|
+
|
|
69
|
+
## Waste signal
|
|
70
|
+
Measured: a sliding window shows as `cached_tokens` far below `prompt_tokens` on calls that continue a conversation (the score's S falls); an unbounded history shows as `prompt_tokens` that keep growing per conversation. Static: severity medium for a per-call window or per-call trimming of old turns (it breaks the cache on every call; also LP-PC-06), medium for stripping reasoning or thinking blocks from the history (E11), low for a history with no bound in an app whose conversations are long.
|