leanprompt 0.0.1 → 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 +86 -3
- 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 +31 -8
- 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-06
|
|
3
|
+
title: Append-only history
|
|
4
|
+
skill: prefill-cache
|
|
5
|
+
applies_to: [anthropic, openai, gemini, openrouter, deepinfra, vllm, sglang]
|
|
6
|
+
saves: prefill
|
|
7
|
+
severity: high
|
|
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
|
+
---
|
|
14
|
+
## Rule
|
|
15
|
+
Send every earlier message byte for byte as it was sent before, and add new content only at the end.
|
|
16
|
+
|
|
17
|
+
## Why
|
|
18
|
+
A turn can reuse the cache only if every message before it is identical to what was sent last time. A rewrite at message `k` makes everything after `k` a miss, and a rewrite that happens on every call makes every turn a miss. The provider docs require the whole rendered prefix to match ([providers/openai.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openai.md), [providers/anthropic.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/anthropic.md)). Documented, not yet measured here.
|
|
19
|
+
|
|
20
|
+
The rewrites that cause it are rarely deliberate:
|
|
21
|
+
- history re-serialised from objects or database rows on each call (different whitespace, key order or number formatting);
|
|
22
|
+
- `.strip()` or Markdown re-rendering of old messages;
|
|
23
|
+
- a reminder or "current state" block updated inside an old message, or inserted in the middle;
|
|
24
|
+
- old tool results truncated in place to stay under a budget;
|
|
25
|
+
- conversion between SDK message types (for example Responses items to Chat Completions messages) on each call.
|
|
26
|
+
|
|
27
|
+
## Detect in code
|
|
28
|
+
Python:
|
|
29
|
+
```
|
|
30
|
+
rg -n 'messages\[\d+\]\s*=|history\[-?\d+\]\[.content.\]\s*\+?=|messages\.insert\(|\.strip\(\)|model_dump\(|json\.dumps\(' -g '*.py'
|
|
31
|
+
```
|
|
32
|
+
Shapes: `messages = [to_api(row) for row in db.load(conv_id)]` on every call, where `to_api` formats content; `for m in history: m["content"] = render(m)`; `history[0]["content"] += reminder`; `result[:MAX_CHARS]` applied to all old tool results on each call.
|
|
33
|
+
|
|
34
|
+
TS/JS:
|
|
35
|
+
```
|
|
36
|
+
rg -n 'messages\.splice\(|history\.map\(|\.trim\(\)|JSON\.stringify\(\w+,\s*null,\s*\d' -g '*.{ts,tsx,js,mjs}'
|
|
37
|
+
```
|
|
38
|
+
Shapes: `history.map(m => ({ ...m, content: render(m) }))` before each request; `JSON.stringify(result, null, 2)` when the tool result is first shown and `JSON.stringify(result)` when history is rebuilt.
|
|
39
|
+
|
|
40
|
+
Go:
|
|
41
|
+
```
|
|
42
|
+
rg -n 'json\.MarshalIndent\(|strings\.TrimSpace\(|messages\[\w+\]\s*=' -g '*.go'
|
|
43
|
+
```
|
|
44
|
+
Shapes: `[]Message` rebuilt from the store each call with `fmt.Sprintf`; `json.MarshalIndent` in one path and `json.Marshal` in another for the same tool result.
|
|
45
|
+
|
|
46
|
+
## Fix
|
|
47
|
+
Store exactly what was sent, and replay it.
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
# before
|
|
51
|
+
messages = [{"role": r.role, "content": render(r)} for r in store.load(conv_id)]
|
|
52
|
+
messages[0]["content"] += f"\n\n<reminder>{state()}</reminder>"
|
|
53
|
+
|
|
54
|
+
# after
|
|
55
|
+
messages = store.load_sent(conv_id) # the exact dicts sent last time, stored after each send
|
|
56
|
+
messages.append({"role": "user", "content": f"<reminder>{state()}</reminder>\n\n{user_input}"})
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Truncate or redact a tool result once, when it is added, never later. Keep cache marks off the stored copies (LP-PC-01 adds them at send time).
|
|
60
|
+
|
|
61
|
+
## Don't break meaning
|
|
62
|
+
If the app rewrote history to keep the model informed (an updated plan, the current state), say the same thing in a new message at the end and state that it supersedes the earlier one; do not silently drop it. If old messages were trimmed to fit the context window, trim by compaction (LP-PC-08), not on every call. Redaction for privacy still happens, once, before the first send.
|
|
63
|
+
|
|
64
|
+
## Verify
|
|
65
|
+
(a) In a multi-turn session, each request reports `cached_tokens` or `cache_read_input_tokens` close to the previous request's prompt size, less the tail the engine rounds away (step and block sizes in the provider tables).
|
|
66
|
+
|
|
67
|
+
(b) kvsig: for consecutive requests A and B of one conversation, `B.nodes` starts with all of `A.nodes`. A shorter shared prefix points at the first rewritten message: the index where the two `nodes` lists first differ.
|
|
68
|
+
|
|
69
|
+
## Waste signal
|
|
70
|
+
Measured: lowers S, the share of prompt tokens that requests continuing a conversation could reuse. Static: severity high for history rebuilt or modified on every call, medium for a one-off rewrite (a single insertion or truncation point).
|
|
71
|
+
<!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: LP-PC-07
|
|
3
|
+
title: Shared context before per-user context
|
|
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://docs.deepinfra.com/chat/prompt-caching.md
|
|
12
|
+
checked: 2026-11-26
|
|
13
|
+
---
|
|
14
|
+
## Rule
|
|
15
|
+
In an app that serves many users or tenants, put what is the same for everyone (instructions, tools, shared reference documents, examples) before anything specific to a tenant, then a user, then a request.
|
|
16
|
+
|
|
17
|
+
## Why
|
|
18
|
+
A cache is shared between requests only up to the first byte that differs. If the system prompt opens with "You are helping Alice at Acme" and then carries a long shared handbook, every user gets a private copy of the handbook in cache and every user's first request pays for it again. Ordered from widest to narrowest audience (everyone, tenant, user, request), each layer is reused by everyone who shares it. OpenAI and DeepInfra both ask for stable content first; OpenAI's `prompt_cache_key` groups requests that share a prefix, and it should name the group that shares it (for example the tenant), not a single request ([providers/openai.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openai.md), [providers/deepinfra.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/deepinfra.md)). Documented, not yet measured here.
|
|
19
|
+
|
|
20
|
+
Order is not enough if a per-user transform runs over the whole rendered prompt afterwards. A redaction step that replaces a requester's name, email or account number wherever it occurs, or a template pass that fills per-user placeholders across every message, also rewrites the shared head whenever the same value happens to appear there (a customer whose name is also a product name, a name that is also a word in the instructions). For those requests the head differs from everyone else's and is paid for again. This follows from prefix matching; not yet measured here. It is rare in any one request, invisible without comparing kvsig ids across users, and more likely the more name-like terms the shared text contains.
|
|
21
|
+
|
|
22
|
+
On a self-hosted server a cache shared across tenants is also a privacy question; see the `lmwarden` skill (keys, isolation, `cache_salt`).
|
|
23
|
+
|
|
24
|
+
## Detect in code
|
|
25
|
+
Python:
|
|
26
|
+
```
|
|
27
|
+
rg -n 'f"(You are|Hello|Hi)[^"]*\{(user|customer|tenant|account)' -g '*.py'
|
|
28
|
+
```
|
|
29
|
+
```
|
|
30
|
+
rg -n 'redact|scrub|anonymi[sz]e|presidio|mask_pii|pii' -g '*.py'
|
|
31
|
+
```
|
|
32
|
+
Shapes: `system = f"You are assisting {user.name} ({user.plan}).\n{HANDBOOK}"`; `messages = [redact(m, user) for m in [system_msg, *msgs]]` or `scrub(render(prompt), names=[user.name])` (a per-user transform over the whole prompt, shared head included); `system = user_profile + SHARED_DOCS`; few-shot examples picked per user and placed before the shared instructions; `prompt_cache_key=request_id`.
|
|
33
|
+
|
|
34
|
+
TS/JS:
|
|
35
|
+
```
|
|
36
|
+
rg -n '`(You are|Hello|Hi)[^`]*\$\{(user|customer|tenant|account)|prompt_cache_key' -g '*.{ts,tsx,js,mjs}'
|
|
37
|
+
```
|
|
38
|
+
```
|
|
39
|
+
rg -n 'redact|scrub|anonymi[sz]e|maskPii|pii' -g '*.{ts,tsx,js,mjs}'
|
|
40
|
+
```
|
|
41
|
+
Shapes: `` system: `Customer: ${customer.name}\n${HANDBOOK}` ``; `messages.map((m) => redact(m, requester))` applied to the system message too; `prompt_cache_key: crypto.randomUUID()`.
|
|
42
|
+
|
|
43
|
+
Go:
|
|
44
|
+
```
|
|
45
|
+
rg -n 'Sprintf\("(You are|User|Customer|Tenant)[^"]*%s' -g '*.go'
|
|
46
|
+
```
|
|
47
|
+
```
|
|
48
|
+
rg -n '(?i)redact|scrub|anonymi[sz]e|pii' -g '*.go'
|
|
49
|
+
```
|
|
50
|
+
Shapes: `fmt.Sprintf("User: %s\n%s", u.Name, sharedDocs)` as the system prompt; a `Redact(prompt, user)` call on the fully rendered prompt.
|
|
51
|
+
|
|
52
|
+
## Fix
|
|
53
|
+
Layer from the widest audience to the narrowest.
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
# before
|
|
57
|
+
system = f"You are assisting {user.name} at {tenant.name}.\n\n{INSTRUCTIONS}\n\n{HANDBOOK}"
|
|
58
|
+
|
|
59
|
+
# after
|
|
60
|
+
system = f"{INSTRUCTIONS}\n\n{HANDBOOK}" # same for every user
|
|
61
|
+
first_user = (
|
|
62
|
+
f"<tenant>{tenant.name}: {tenant.notes}</tenant>\n"
|
|
63
|
+
f"<user>{user.name}, plan {user.plan}</user>\n\n{question}"
|
|
64
|
+
)
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
// before
|
|
69
|
+
prompt_cache_key: crypto.randomUUID(),
|
|
70
|
+
// after
|
|
71
|
+
prompt_cache_key: `tenant:${tenant.id}`, // one key per group that shares the prefix
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Apply per-user transforms (redaction, per-user templating) only to the per-user parts, then put the shared head in front unchanged.
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
# before: the scrubber sees the whole prompt, shared head included
|
|
78
|
+
messages = scrub([{"role": "system", "content": SYSTEM}, {"role": "user", "content": request_text}], names=[requester.name])
|
|
79
|
+
|
|
80
|
+
# after: scrub only what is per request; the shared head is never transformed per user
|
|
81
|
+
messages = [{"role": "system", "content": SYSTEM},
|
|
82
|
+
{"role": "user", "content": scrub(request_text, names=[requester.name])}]
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
When a tenant has a large block of its own (its documents), it can go at the end of the system prompt, after the shared part, so that tenant's users share it.
|
|
86
|
+
|
|
87
|
+
## Don't break meaning
|
|
88
|
+
The model must still know whom it serves: keep the user and tenant blocks labelled, and update instructions that referred to them by position. If per-user settings are meant to override the shared defaults, say so in the user block ("These preferences take precedence over the defaults above"). Run the answer check on a few personalised cases before and after. Moving redaction off the shared head must not let personal data through: the shared head must hold none to begin with (it is the same for everyone), and every per-user part must still pass through the transform. If the head does contain personal data, remove it from the head; do not keep scrubbing it per user.
|
|
89
|
+
|
|
90
|
+
## Verify
|
|
91
|
+
(a) Send the first request for user A, then for user B. B's request reports `cached_tokens` or `cache_read_input_tokens` covering the shared part.
|
|
92
|
+
|
|
93
|
+
(b) kvsig: build the first request for two users. Exact `tools` and `sys` are equal, so `head` is equal; the per-user part starts at the first message. Where a per-user transform runs, pick two users whose values also occur in the shared text (a name that is also a product term) and check that `sys` and `head` are still equal after the transform.
|
|
94
|
+
|
|
95
|
+
## Waste signal
|
|
96
|
+
Measured: first requests of different users share a short prefix with each other; the score's S counts only continuing requests, so the loss shows as many `sys` or `head` ids for one shared prompt. Static: severity medium for per-user or per-tenant values before long shared text, low for a `prompt_cache_key` that is unique per request, low for a per-user transform run over the shared head (it costs only on the requests whose values occur in the head).
|
|
97
|
+
<!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: LP-PC-08
|
|
3
|
+
title: Cache-aware compaction
|
|
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://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
|
+
---
|
|
14
|
+
## Rule
|
|
15
|
+
When you compact a long conversation, keep the system prompt and the tool list byte-identical and put the summary in the messages after them, and run the summarising call as a continuation of the same prompt.
|
|
16
|
+
|
|
17
|
+
## Why
|
|
18
|
+
Compaction replaces the history with a summary, so the message part is recomputed once whatever you do. If the compaction also rewrites the system prompt (appending "Summary of the conversation so far: ..." to it) or rebuilds the tool list, the head is lost too, on every compaction. On Anthropic, tools and system render before messages, so an unchanged head stays cached across the compaction ([providers/anthropic.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/anthropic.md)). Documented, not yet measured here.
|
|
19
|
+
|
|
20
|
+
The summarising call itself is the second cost. Sent with its own system prompt ("You are a summariser") over the full history, it pays for the whole history again. Sent as the same head and history plus a final instruction to summarise, it reads the cache that the last turn wrote.
|
|
21
|
+
|
|
22
|
+
## Detect in code
|
|
23
|
+
Python:
|
|
24
|
+
```
|
|
25
|
+
rg -n '(system|system_prompt)\s*\+=|summary|summari[sz]e|compact' -g '*.py'
|
|
26
|
+
```
|
|
27
|
+
Shapes: `system_prompt += f"\n\nEarlier conversation:\n{summary}"`; `client.messages.create(system="Summarise this conversation.", messages=history)`; tools rebuilt from the registry after compaction (LP-PC-04).
|
|
28
|
+
|
|
29
|
+
TS/JS:
|
|
30
|
+
```
|
|
31
|
+
rg -n 'system\w*\s*\+=|system\w*\s*=\s*`\$\{\w+\}.*summary|summari[sz]e|compact' -g '*.{ts,tsx,js,mjs}'
|
|
32
|
+
```
|
|
33
|
+
Shapes: `` systemPrompt = `${BASE}\n\n${summary}` ``; a summariser request with a different `system` and the full `messages`.
|
|
34
|
+
|
|
35
|
+
Go:
|
|
36
|
+
```
|
|
37
|
+
rg -n 'sys(tem)?\w*\s*\+=|sys(tem)?\w*\s*=\s*\w+\s*\+\s*.*summary|Summari[sz]e|Compact' -g '*.go'
|
|
38
|
+
```
|
|
39
|
+
Shapes: `sys = basePrompt + "\n" + summary`.
|
|
40
|
+
|
|
41
|
+
## Fix
|
|
42
|
+
```python
|
|
43
|
+
# before
|
|
44
|
+
summary = client.messages.create(system="Summarise this conversation.", messages=history, ...)
|
|
45
|
+
system = BASE_PROMPT + "\n\nSummary of the conversation so far:\n" + text_of(summary)
|
|
46
|
+
history = []
|
|
47
|
+
|
|
48
|
+
# after
|
|
49
|
+
ask = {"role": "user", "content": "Summarise the conversation so far for your own later use."}
|
|
50
|
+
summary = client.messages.create(system=BASE_PROMPT, tools=TOOLS, messages=[*history, ask], ...)
|
|
51
|
+
system = BASE_PROMPT # unchanged, byte for byte
|
|
52
|
+
history = [{"role": "user", "content": "Summary of the conversation so far:\n" + text_of(summary)}]
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Keep the tools exactly as they were (same list, same order, same serialisation). To stop the summarising call from calling a tool, say so in the instruction rather than changing `tool_choice`: on OpenAI `"none"` drops the tools from the rendered prompt, and on Anthropic a `tool_choice` change invalidates the message blocks ([providers/openai.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openai.md), [providers/anthropic.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/anthropic.md)).
|
|
56
|
+
|
|
57
|
+
## Don't break meaning
|
|
58
|
+
The summary must still be read as context: label it ("Summary of the conversation so far"), and if the system prompt used to say how to treat the summary, keep that instruction in the stable system prompt. A summariser call made as a continuation sees the agent's own instructions; ask for a summary in plain terms, and compare a few post-compaction answers on a fixed long conversation before and after the change.
|
|
59
|
+
|
|
60
|
+
## Verify
|
|
61
|
+
(a) The request right after a compaction reports `cached_tokens` or `cache_read_input_tokens` of at least the head (tools and system). The summarising call reports a read close to the size of the history it summarised.
|
|
62
|
+
|
|
63
|
+
(b) kvsig: `head` (and `sys`, `tools`) is equal before and after the compaction. `conv` changes, as expected: kvsig reads it as "different conv, same sys". The summarising call's `nodes` start with all of the last pre-compaction request's `nodes`.
|
|
64
|
+
|
|
65
|
+
## Waste signal
|
|
66
|
+
Measured: compaction starts a new `conv`, so the score's S does not see it; it shows as a new `sys` right after a long conversation where the same `sys` was expected, and as a summarising call with a short shared prefix. Static: severity medium for a summary written into the system prompt or a summariser call with its own system prompt.
|
|
67
|
+
<!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: LP-PC-09
|
|
3
|
+
title: Consistent reasoning handling; thinking fixed per session
|
|
4
|
+
skill: prefill-cache
|
|
5
|
+
applies_to: [anthropic, openai, vllm, sglang, openrouter]
|
|
6
|
+
saves: both
|
|
7
|
+
severity: high
|
|
8
|
+
evidence: [E7, E11]
|
|
9
|
+
---
|
|
10
|
+
## Rule
|
|
11
|
+
Decide once per session whether thinking is on, at what budget or effort, and how earlier reasoning is carried in the history, and keep all three the same on every turn.
|
|
12
|
+
|
|
13
|
+
## Why
|
|
14
|
+
Chat templates and providers render earlier assistant turns differently depending on the thinking setting, so a setting that changes between turns changes the prefix behind them.
|
|
15
|
+
|
|
16
|
+
- On a self-hosted Qwen hybrid model, toggling thinking on and off between turns of one session lost 47% of what those turns could have reused; turns with the same setting as the turn before lost nothing (E7). The template rules are in [models/qwen.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/models/qwen.md).
|
|
17
|
+
- On Anthropic, the thinking mode and budget are rendered into the prompt, and changing either invalidates the message blocks ([models/anthropic-thinking.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/models/anthropic-thinking.md)).
|
|
18
|
+
- On OpenAI reasoning models, reasoning items returned with tool calls are meant to be passed back in their original order ([models/openai-reasoning.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/models/openai-reasoning.md)).
|
|
19
|
+
|
|
20
|
+
Stripping reasoning from history to save tokens changes the prefix from the first stripped turn on, and it can cost more than it saves: in agent loops it produced about 3x more generation (E11).
|
|
21
|
+
|
|
22
|
+
The shapes: a router that turns thinking on for "hard" turns only; an effort level picked per request by a heuristic; a history store that keeps only the final text of each assistant turn.
|
|
23
|
+
|
|
24
|
+
## Detect in code
|
|
25
|
+
Python:
|
|
26
|
+
```
|
|
27
|
+
rg -n 'enable_thinking|reasoning_effort|budget_tokens|thinking=|reasoning_content|"thinking"' -g '*.py'
|
|
28
|
+
```
|
|
29
|
+
Shapes: `extra_body={"chat_template_kwargs": {"enable_thinking": is_hard(msg)}}`; `reasoning_effort=pick_effort(msg)`; `thinking={"type": "enabled", "budget_tokens": budget_for(turn)}`; `m.pop("reasoning_content", None)` or `[b for b in content if b.type != "thinking"]` when saving history.
|
|
30
|
+
|
|
31
|
+
TS/JS:
|
|
32
|
+
```
|
|
33
|
+
rg -n 'enable_thinking|reasoning_effort|reasoningEffort|budget_tokens|thinking:|reasoning_content|type !== "thinking"' -g '*.{ts,tsx,js,mjs}'
|
|
34
|
+
```
|
|
35
|
+
Shapes: `reasoning_effort: hard ? "high" : "low"`; `content.filter(b => b.type !== "thinking")`; `delete msg.reasoning_content`.
|
|
36
|
+
|
|
37
|
+
Go:
|
|
38
|
+
```
|
|
39
|
+
rg -n 'EnableThinking|ReasoningEffort|BudgetTokens|ReasoningContent|Thinking' -g '*.go'
|
|
40
|
+
```
|
|
41
|
+
Shapes: `ReasoningEffort: effortFor(turn)`; history rebuilt from `resp.Choices[0].Message.Content` only, dropping the reasoning field.
|
|
42
|
+
|
|
43
|
+
## Fix
|
|
44
|
+
Fix the setting on the session object, and store each assistant turn as it came back.
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
# before
|
|
48
|
+
kwargs = {"enable_thinking": is_hard(user_msg)}
|
|
49
|
+
history.append({"role": "assistant", "content": msg.content}) # reasoning dropped
|
|
50
|
+
|
|
51
|
+
# after
|
|
52
|
+
kwargs = {"enable_thinking": session.thinking} # chosen once, at session start
|
|
53
|
+
history.append(msg.model_dump(exclude_none=True)) # reasoning kept as returned
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
// before
|
|
58
|
+
reasoning_effort: isHard(input) ? "high" : "low",
|
|
59
|
+
// after
|
|
60
|
+
reasoning_effort: session.effort, // one value for the whole session
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
If some steps need thinking and others do not, run them as separate sessions (a subagent with its own fixed setting) instead of toggling inside one.
|
|
64
|
+
|
|
65
|
+
## Don't break meaning
|
|
66
|
+
A fixed setting changes the turns that used to differ. If hard turns needed thinking, turn it on for the whole session (quality first), or move hard steps into their own session; do not silently turn it off. Keeping reasoning in history uses more context: if context is the limit, compact (LP-PC-08) instead of stripping per turn. Compare answers and output tokens per task on a fixed set before and after.
|
|
67
|
+
|
|
68
|
+
## Verify
|
|
69
|
+
(a) On consecutive turns, `cached_tokens` or `cache_read_input_tokens` is close to the previous request's prompt size. A turn whose read drops to the system prompt alone, right after a setting change, is this rule.
|
|
70
|
+
|
|
71
|
+
(b) kvsig: each request's exact `nodes` starts with all of the previous request's exact `nodes`. Use exact ids here: the loose form ignores reasoning, so `loose_nodes` that continue while exact `nodes` do not mean the reasoning was stripped or rendered differently.
|
|
72
|
+
|
|
73
|
+
## Waste signal
|
|
74
|
+
Measured: the prefill side lowers S on every turn after a change. The generation side (E11) is not part of G; it shows as more output tokens per task in a before/after run (the `measure-loop` skill). Static: severity high, counted on both the prefill and the generation side (`saves: both`).
|
|
75
|
+
<!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: LP-PC-10
|
|
3
|
+
title: Stable image and attachment placement
|
|
4
|
+
skill: prefill-cache
|
|
5
|
+
applies_to: [anthropic, openai, gemini, openrouter, vllm, sglang]
|
|
6
|
+
saves: prefill
|
|
7
|
+
severity: medium
|
|
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
|
+
---
|
|
14
|
+
## Rule
|
|
15
|
+
Put each image, file or document in the message where it first appears and keep it there, with the same bytes or the same reference, for the rest of the session; never move it, re-encode it or re-upload it per call.
|
|
16
|
+
|
|
17
|
+
## Why
|
|
18
|
+
Images and attachments are often the largest part of a prompt, and they are part of the prefix like any text. On Anthropic, adding or removing images invalidates the message blocks ([providers/anthropic.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/anthropic.md)); on OpenAI images count toward the prefix that must match ([providers/openai.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openai.md)). Documented, not yet measured here.
|
|
19
|
+
|
|
20
|
+
The shapes that break it:
|
|
21
|
+
- "the current screenshot" attached to the newest message and removed from the older ones on every turn;
|
|
22
|
+
- a pre-signed URL generated on every call, so the same file has a new URL (its expiry query string) each time;
|
|
23
|
+
- an image resized or re-compressed on every call, which gives different base64 bytes;
|
|
24
|
+
- a file re-uploaded per call, which gives a new file id;
|
|
25
|
+
- attachments placed in the system prompt and swapped per request.
|
|
26
|
+
|
|
27
|
+
## Detect in code
|
|
28
|
+
Python:
|
|
29
|
+
```
|
|
30
|
+
rg -n 'generate_presigned_url\(|b64encode\(|\.thumbnail\(|\.resize\(|files\.(create|upload)\(' -g '*.py'
|
|
31
|
+
```
|
|
32
|
+
Shapes: `generate_presigned_url(...)` inside the function that builds messages; `base64.b64encode(resize(img))` on each call; `for m in history: m["content"] = [p for p in m["content"] if p["type"] != "image"]`.
|
|
33
|
+
|
|
34
|
+
TS/JS:
|
|
35
|
+
```
|
|
36
|
+
rg -n 'getSignedUrl\(|toString\("base64"\)|sharp\(|files\.create\(' -g '*.{ts,tsx,js,mjs}'
|
|
37
|
+
```
|
|
38
|
+
Shapes: `image_url: { url: await getSignedUrl(s3, cmd) }` in the request builder; `sharp(buf).resize(...)` per request.
|
|
39
|
+
|
|
40
|
+
Go:
|
|
41
|
+
```
|
|
42
|
+
rg -n 'PresignGetObject\(|base64\.StdEncoding\.EncodeToString\(|imaging\.Resize\(' -g '*.go'
|
|
43
|
+
```
|
|
44
|
+
Shapes: a presign call or a resize inside the loop that builds each request.
|
|
45
|
+
|
|
46
|
+
## Fix
|
|
47
|
+
Encode or upload once, when the attachment enters the conversation, and store the exact content part.
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
# before
|
|
51
|
+
def build(history, shot):
|
|
52
|
+
for m in history:
|
|
53
|
+
m["content"] = [p for p in m["content"] if p.get("type") != "image_url"]
|
|
54
|
+
url = s3.generate_presigned_url("get_object", Params=shot.key)
|
|
55
|
+
history[-1]["content"].append({"type": "image_url", "image_url": {"url": url}})
|
|
56
|
+
|
|
57
|
+
# after
|
|
58
|
+
def add_screenshot(history, shot, step):
|
|
59
|
+
part = {"type": "image_url", "image_url": {"url": to_data_url(shot)}} # encoded once
|
|
60
|
+
history.append({"role": "user", "content": [
|
|
61
|
+
{"type": "text", "text": f"Screenshot after step {step}; it supersedes earlier ones."}, part]})
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
If old images must leave the context to save space, drop them in a compaction step (LP-PC-08), not on every turn.
|
|
65
|
+
|
|
66
|
+
## Don't break meaning
|
|
67
|
+
If the app removed old images so the model would look only at the latest one, keep that intent with a label ("supersedes earlier ones") on the new image instead of deleting the old ones, and check that answers still refer to the latest image. Text that refers to an image stays next to it. Do not lower image resolution once to make bytes stable if the task needs the detail.
|
|
68
|
+
|
|
69
|
+
## Verify
|
|
70
|
+
(a) In a session with an image, the next turn reports `cached_tokens` or `cache_read_input_tokens` covering the message that holds the image.
|
|
71
|
+
|
|
72
|
+
(b) kvsig: `msgs[i]` of the message that carries the attachment is equal on every later request, and `nodes` continue (each request's `nodes` start with all of the previous one's).
|
|
73
|
+
|
|
74
|
+
## Waste signal
|
|
75
|
+
Measured: lowers S on every turn that moves or re-encodes an attachment. Static: severity medium for a per-call presign, re-encode or re-upload, or for attachments removed from older messages each turn.
|
|
76
|
+
<!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
|
|
@@ -0,0 +1,72 @@
|
|
|
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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/anthropic.md), [providers/openai.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openai.md), [providers/gemini.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/gemini.md), [providers/deepinfra.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/deepinfra.md)). Self-hosted engines have no lifetime but evict under memory pressure ([providers/vllm.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/vllm.md), [providers/sglang.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/sglang.md)). On OpenRouter, sticky routing to the provider that holds the cache has its own inactivity timer ([providers/openrouter.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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).
|
|
72
|
+
<!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
|
|
@@ -0,0 +1,73 @@
|
|
|
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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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.
|
|
73
|
+
<!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
|
|
@@ -0,0 +1,69 @@
|
|
|
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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/anthropic.md), [providers/openai.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openai.md)
|
|
39
|
+
- **Gemini.** Every function declaration is billed as input tokens on every request. [providers/gemini.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openrouter.md), [providers/deepinfra.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/vllm.md), [providers/sglang.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/sglang.md)
|
|
42
|
+
|
|
43
|
+
Evidence rows (E1 to E12) are in [docs/evidence.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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.
|
|
69
|
+
<!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
|