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.
Files changed (157) hide show
  1. package/LICENSE +202 -0
  2. package/LICENSE-DOCS +396 -0
  3. package/NOTICE +11 -0
  4. package/README.md +86 -3
  5. package/cli/dist/detect.d.ts +23 -0
  6. package/cli/dist/detect.js +219 -0
  7. package/cli/dist/evalAudit.d.ts +32 -0
  8. package/cli/dist/evalAudit.js +161 -0
  9. package/cli/dist/facts.d.ts +14 -0
  10. package/cli/dist/facts.js +43 -0
  11. package/cli/dist/forms.d.ts +23 -0
  12. package/cli/dist/forms.js +199 -0
  13. package/cli/dist/frontmatter.d.ts +10 -0
  14. package/cli/dist/frontmatter.js +32 -0
  15. package/cli/dist/help.d.ts +27 -0
  16. package/cli/dist/help.js +118 -0
  17. package/cli/dist/init.d.ts +78 -0
  18. package/cli/dist/init.js +358 -0
  19. package/cli/dist/install.d.ts +20 -0
  20. package/cli/dist/install.js +225 -0
  21. package/cli/dist/isMain.d.ts +6 -0
  22. package/cli/dist/isMain.js +18 -0
  23. package/cli/dist/lesson.d.ts +16 -0
  24. package/cli/dist/lesson.js +205 -0
  25. package/cli/dist/lint/facts.d.ts +7 -0
  26. package/cli/dist/lint/facts.js +163 -0
  27. package/cli/dist/lint/numbers.d.ts +26 -0
  28. package/cli/dist/lint/numbers.js +163 -0
  29. package/cli/dist/lint/rules.d.ts +20 -0
  30. package/cli/dist/lint/rules.js +170 -0
  31. package/cli/dist/log/logger.d.ts +49 -0
  32. package/cli/dist/log/logger.js +148 -0
  33. package/cli/dist/log/record.d.ts +56 -0
  34. package/cli/dist/log/record.js +117 -0
  35. package/cli/dist/main.d.ts +6 -0
  36. package/cli/dist/main.js +67 -0
  37. package/cli/dist/profile.d.ts +93 -0
  38. package/cli/dist/profile.js +372 -0
  39. package/cli/dist/report/cost.d.ts +55 -0
  40. package/cli/dist/report/cost.js +151 -0
  41. package/cli/dist/report/html.d.ts +81 -0
  42. package/cli/dist/report/html.js +555 -0
  43. package/cli/dist/report/template.html +269 -0
  44. package/cli/dist/score/calibrate.d.ts +65 -0
  45. package/cli/dist/score/calibrate.js +213 -0
  46. package/cli/dist/score/measured.d.ts +66 -0
  47. package/cli/dist/score/measured.js +191 -0
  48. package/cli/dist/score/static.d.ts +112 -0
  49. package/cli/dist/score/static.js +172 -0
  50. package/cli/dist/score/write.d.ts +29 -0
  51. package/cli/dist/score/write.js +247 -0
  52. package/forms/AGENTS.block.md +25 -0
  53. package/forms/opencode/commands/leanprompt-audit.md +10 -0
  54. package/forms/opencode/commands/leanprompt.md +8 -0
  55. package/forms/skills/generation-economy/SKILL.md +89 -0
  56. package/forms/skills/generation-economy/rules/LP-GE-01.md +93 -0
  57. package/forms/skills/generation-economy/rules/LP-GE-02.md +82 -0
  58. package/forms/skills/generation-economy/rules/LP-GE-03.md +87 -0
  59. package/forms/skills/generation-economy/rules/LP-GE-04.md +118 -0
  60. package/forms/skills/generation-economy/rules/LP-GE-05.md +84 -0
  61. package/forms/skills/generation-economy/rules/LP-GE-06.md +76 -0
  62. package/forms/skills/generation-economy/rules/LP-GE-07.md +84 -0
  63. package/forms/skills/generation-economy/rules/LP-GE-08.md +71 -0
  64. package/forms/skills/generation-economy/rules/LP-GE-09.md +79 -0
  65. package/forms/skills/generation-economy/rules/LP-GE-10.md +104 -0
  66. package/forms/skills/leanprompt/SKILL.md +48 -0
  67. package/forms/skills/leanprompt/fix.md +15 -0
  68. package/forms/skills/leanprompt/init.md +30 -0
  69. package/forms/skills/llm-call-audit/SKILL.md +169 -0
  70. package/forms/skills/llm-call-audit/call-shapes.md +99 -0
  71. package/forms/skills/llm-call-audit/presenting.md +72 -0
  72. package/forms/skills/llm-call-audit/report-template.md +113 -0
  73. package/forms/skills/lmwarden/SKILL.md +97 -0
  74. package/forms/skills/lmwarden/rules/LP-LW-01.md +73 -0
  75. package/forms/skills/lmwarden/rules/LP-LW-02.md +78 -0
  76. package/forms/skills/lmwarden/rules/LP-LW-03.md +73 -0
  77. package/forms/skills/measure-loop/SKILL.md +155 -0
  78. package/forms/skills/measure-loop/templates/stable-head.template.ts +38 -0
  79. package/forms/skills/measure-loop/templates/stable_head_template.py +40 -0
  80. package/forms/skills/prefill-cache/SKILL.md +66 -0
  81. package/forms/skills/prefill-cache/rules/LP-PC-01.md +103 -0
  82. package/forms/skills/prefill-cache/rules/LP-PC-02.md +80 -0
  83. package/forms/skills/prefill-cache/rules/LP-PC-03.md +75 -0
  84. package/forms/skills/prefill-cache/rules/LP-PC-04.md +79 -0
  85. package/forms/skills/prefill-cache/rules/LP-PC-05.md +68 -0
  86. package/forms/skills/prefill-cache/rules/LP-PC-06.md +71 -0
  87. package/forms/skills/prefill-cache/rules/LP-PC-07.md +97 -0
  88. package/forms/skills/prefill-cache/rules/LP-PC-08.md +67 -0
  89. package/forms/skills/prefill-cache/rules/LP-PC-09.md +75 -0
  90. package/forms/skills/prefill-cache/rules/LP-PC-10.md +76 -0
  91. package/forms/skills/prefill-cache/rules/LP-PC-11.md +72 -0
  92. package/forms/skills/prefill-cache/rules/LP-PC-12.md +73 -0
  93. package/forms/skills/prompt-diet/SKILL.md +69 -0
  94. package/forms/skills/prompt-diet/rules/LP-PD-01.md +79 -0
  95. package/forms/skills/prompt-diet/rules/LP-PD-02.md +73 -0
  96. package/forms/skills/prompt-diet/rules/LP-PD-03.md +65 -0
  97. package/forms/skills/prompt-diet/rules/LP-PD-04.md +77 -0
  98. package/forms/skills/prompt-diet/rules/LP-PD-05.md +71 -0
  99. package/forms/skills/prompt-diet/rules/LP-PD-06.md +68 -0
  100. package/models/anthropic-thinking.md +38 -0
  101. package/models/openai-reasoning.md +35 -0
  102. package/models/qwen.md +34 -0
  103. package/package.json +31 -8
  104. package/providers/anthropic.md +83 -0
  105. package/providers/deepinfra.md +46 -0
  106. package/providers/gemini.md +61 -0
  107. package/providers/openai.md +73 -0
  108. package/providers/openrouter.md +66 -0
  109. package/providers/sglang.md +41 -0
  110. package/providers/vllm.md +52 -0
  111. package/runtimes/http-clients.md +20 -0
  112. package/skills/_template/RULE.md +31 -0
  113. package/skills/generation-economy/SKILL.md +88 -0
  114. package/skills/generation-economy/rules/LP-GE-01.md +92 -0
  115. package/skills/generation-economy/rules/LP-GE-02.md +81 -0
  116. package/skills/generation-economy/rules/LP-GE-03.md +86 -0
  117. package/skills/generation-economy/rules/LP-GE-04.md +117 -0
  118. package/skills/generation-economy/rules/LP-GE-05.md +83 -0
  119. package/skills/generation-economy/rules/LP-GE-06.md +75 -0
  120. package/skills/generation-economy/rules/LP-GE-07.md +83 -0
  121. package/skills/generation-economy/rules/LP-GE-08.md +70 -0
  122. package/skills/generation-economy/rules/LP-GE-09.md +78 -0
  123. package/skills/generation-economy/rules/LP-GE-10.md +103 -0
  124. package/skills/leanprompt/SKILL.md +47 -0
  125. package/skills/leanprompt/fix.md +14 -0
  126. package/skills/leanprompt/init.md +29 -0
  127. package/skills/llm-call-audit/SKILL.md +168 -0
  128. package/skills/llm-call-audit/call-shapes.md +98 -0
  129. package/skills/llm-call-audit/presenting.md +71 -0
  130. package/skills/llm-call-audit/report-template.md +112 -0
  131. package/skills/lmwarden/SKILL.md +96 -0
  132. package/skills/lmwarden/rules/LP-LW-01.md +72 -0
  133. package/skills/lmwarden/rules/LP-LW-02.md +77 -0
  134. package/skills/lmwarden/rules/LP-LW-03.md +72 -0
  135. package/skills/measure-loop/SKILL.md +154 -0
  136. package/skills/measure-loop/templates/stable-head.template.ts +38 -0
  137. package/skills/measure-loop/templates/stable_head_template.py +40 -0
  138. package/skills/prefill-cache/SKILL.md +65 -0
  139. package/skills/prefill-cache/rules/LP-PC-01.md +102 -0
  140. package/skills/prefill-cache/rules/LP-PC-02.md +79 -0
  141. package/skills/prefill-cache/rules/LP-PC-03.md +74 -0
  142. package/skills/prefill-cache/rules/LP-PC-04.md +78 -0
  143. package/skills/prefill-cache/rules/LP-PC-05.md +67 -0
  144. package/skills/prefill-cache/rules/LP-PC-06.md +70 -0
  145. package/skills/prefill-cache/rules/LP-PC-07.md +96 -0
  146. package/skills/prefill-cache/rules/LP-PC-08.md +66 -0
  147. package/skills/prefill-cache/rules/LP-PC-09.md +74 -0
  148. package/skills/prefill-cache/rules/LP-PC-10.md +75 -0
  149. package/skills/prefill-cache/rules/LP-PC-11.md +71 -0
  150. package/skills/prefill-cache/rules/LP-PC-12.md +72 -0
  151. package/skills/prompt-diet/SKILL.md +68 -0
  152. package/skills/prompt-diet/rules/LP-PD-01.md +78 -0
  153. package/skills/prompt-diet/rules/LP-PD-02.md +72 -0
  154. package/skills/prompt-diet/rules/LP-PD-03.md +64 -0
  155. package/skills/prompt-diet/rules/LP-PD-04.md +76 -0
  156. package/skills/prompt-diet/rules/LP-PD-05.md +70 -0
  157. package/skills/prompt-diet/rules/LP-PD-06.md +67 -0
@@ -0,0 +1,79 @@
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](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)). 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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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.
79
+ <!-- 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-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](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)). 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).
73
+ <!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
@@ -0,0 +1,65 @@
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](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/vllm.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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.
65
+ <!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
@@ -0,0 +1,77 @@
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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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.
77
+ <!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
@@ -0,0 +1,71 @@
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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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.
71
+ <!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
@@ -0,0 +1,68 @@
1
+ ---
2
+ id: LP-PD-06
3
+ title: Compact serialisation for data in the prompt
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/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
+ Serialise the data the app puts into the prompt (tool results, records, retrieved rows, examples) compactly and the same way every time: no pretty-printing indentation, and a table or a list of rows instead of a list of objects that repeats every key.
17
+
18
+ ## Why
19
+ Whitespace and repeated keys are tokens. `json.dumps(rows, indent=2)` adds a line break and indentation for every field, and a list of objects writes every key name once per row; a hundred rows with eight keys write each key a hundred times. The model reads the data just as well in compact JSON, or as a header line followed by rows. Anthropic counts `tool_result` content as input tokens ([providers/anthropic.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/anthropic.md)); data in the history is sent again on every later call ([providers/openai.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openai.md)). Documented, not yet measured here; count the two forms with the provider's tokenizer before claiming a saving.
20
+
21
+ Serialisation is also a cache question. Whatever form you choose, produce it the same way every time (fixed key order, fixed separators), and never re-serialise data already in the history in a new form (LP-PC-04, LP-PC-06).
22
+
23
+ This rule is about data the app sends. Asking the model for a compact output format is about generated tokens, which the `generation-economy` skill covers (LP-GE-10 for structured output).
24
+
25
+ ## Detect in code
26
+ Python:
27
+ ```
28
+ rg -n 'json\.dumps\([^)]*indent\s*=|pprint\.pformat\(|yaml\.dump\(' -g '*.py'
29
+ ```
30
+ Shapes: `json.dumps(result, indent=2)` as a tool result or in a prompt template; `df.to_json(orient="records")` for a large table; `pformat(obj)` in a prompt.
31
+
32
+ TS/JS:
33
+ ```
34
+ rg -n 'JSON\.stringify\([^)]*,\s*(null|undefined)\s*,\s*\d' -g '*.{ts,tsx,js,mjs}'
35
+ ```
36
+ Shapes: `JSON.stringify(data, null, 2)` in a tool handler or prompt builder.
37
+
38
+ Go:
39
+ ```
40
+ rg -n 'json\.MarshalIndent\(' -g '*.go'
41
+ ```
42
+ Shapes: `json.MarshalIndent(v, "", " ")` for a value that goes into a message.
43
+
44
+ ## Fix
45
+ ```python
46
+ # before: pretty-printed, every key on every row
47
+ content = json.dumps(rows, indent=2)
48
+
49
+ # after: compact, fixed separators and key order; for many uniform rows, a header and rows
50
+ content = json.dumps(rows, separators=(",", ":"), sort_keys=True, ensure_ascii=False)
51
+
52
+ COLS = ["id", "status", "total"]
53
+ content = json.dumps({"columns": COLS, "rows": [[r[c] for c in COLS] for r in rows]}, separators=(",", ":"))
54
+ ```
55
+
56
+ `sort_keys=True` keeps the bytes the same for the same data; if the app's key order carries meaning (a priority, a display order), keep a fixed order of your own instead.
57
+
58
+ ## Don't break meaning
59
+ Compact JSON carries the same data; a header and rows changes the shape, so the prompt must say what the columns are, and the model must still be able to point at a row. Run the answer check with `measure-loop` on a fixed set of inputs, before and after: answers unchanged or better, including answers that quote or count the data. Data in the shared head (examples in the system prompt) is read from the cache, so change it there only if the saving outweighs one prefill of the head per route, once. Do not re-serialise or shorten data already in the history, and do not strip reasoning from it; stripping reasoning produced about 3x more generation (E11). What must stay byte-identical in the head and the history: [prefill-cache](../../prefill-cache/SKILL.md).
60
+
61
+ ## Verify
62
+ (a) Provider usage: `usage.input_tokens` or `usage.prompt_tokens` on the call that carries the data falls by about the difference between the two forms; on later turns of the conversation `prompt_tokens` stays lower by the same amount, and `cached_tokens` on the next turn still covers the earlier history.
63
+
64
+ (b) leanprompt usage record: `prompt_tokens` falls for the call site; for the same data, the message's `ids.nodes` entry is equal across two runs (the serialisation is deterministic).
65
+
66
+ ## Waste signal
67
+ Measured: the drop in `prompt_tokens` per call that carries the data, times those calls; the score does not count it, the report shows it as `tokens_per_1k.prompt`. Static: severity low for indented JSON or repeated keys in tool results or prompt data; medium when the data is large (hundreds of rows) and sits in an agent loop's history, where every later turn carries it.
68
+ <!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
@@ -0,0 +1,38 @@
1
+ ---
2
+ family: anthropic-thinking
3
+ checked: 2026-11-26
4
+ source: https://platform.claude.com/docs/en/build-with-claude/extended-thinking
5
+ ---
6
+
7
+ # Anthropic thinking and effort
8
+
9
+ Status: documented, not yet measured here. Cache facts are in `providers/anthropic.md`.
10
+
11
+ ## Modes (docs, checked 2026-11-26)
12
+
13
+ - Manual extended thinking (`thinking: {type: "enabled", budget_tokens: N}`) is deprecated. Claude 4.7 and later reject it with a 400 error. Models documented as extended-thinking-only (`type: "adaptive"` returns 400): Opus 4.5, Sonnet 4.5, Haiku 4.5, Opus 4.1, Sonnet 4, Opus 4.
14
+ - Adaptive thinking (`thinking: {type: "adaptive"}`) with `output_config: {effort: ...}` is the replacement. The model decides whether and how much to think per request; at lower effort it may skip thinking on easy inputs.
15
+ - Effort defaults: `medium` on Opus 5.5 and Haiku 5.5, `high` on other models that support effort (including Sonnet 4.6). Setting effort explicitly to the model default does not invalidate the cache.
16
+
17
+ ## Budget rules (manual mode)
18
+
19
+ - `budget_tokens` minimum 1,024 and less than `max_tokens`, except with interleaved thinking in manual mode where it can exceed `max_tokens`.
20
+ - The budget is a target, not a cap; `max_tokens` is the hard ceiling. Thinking tokens count toward `max_tokens` and are billed as output tokens; `usage.output_tokens_details.thinking_tokens` reports them.
21
+ - For budgets above 32k the docs advise the batch API.
22
+ - Manual thinking cannot be combined with `max_tokens: 0` cache pre-warming.
23
+
24
+ ## Cache interaction
25
+
26
+ - The thinking mode and `budget_tokens` are rendered into the prompt. Changing `budget_tokens` between requests invalidates message-level breakpoints; the docs' example re-created 1,370 tokens on the request after a 4,000 to 8,000 change. Switching modes does the same. Pick a budget and hold it for the life of a cached conversation.
27
+ - Thinking blocks across turns: Opus 4.5 and Claude 4.6 and later keep prior turns' thinking blocks in context and bill them as input; Sonnet 4.5, Haiku 4.5 and earlier strip them. Dropped thinking blocks invalidate message blocks from that position.
28
+ - `tool_choice` changes invalidate message blocks only.
29
+
30
+ ## Interleaved thinking
31
+
32
+ - Opus 4.5, Sonnet 4.5, Haiku 4.5, Opus 4.1, Sonnet 4, Opus 4: add the `interleaved-thinking-2025-05-14` beta header. Sonnet 4.6: header still works but is deprecated. Opus 4.6: manual mode has no interleaving; use adaptive. Adaptive thinking interleaves with no header.
33
+ - Manual mode needs the final assistant turn to start with a thinking block; adaptive drops that requirement.
34
+
35
+ ## Not stated in the docs
36
+
37
+ - Temperature restrictions with thinking, and tool-calling or JSON-output quirks: not stated on the page read (checked 2026-11-26).
38
+ - Only the Extended thinking page was read; the Thinking, Effort and Steering pages it links to were not.
@@ -0,0 +1,35 @@
1
+ ---
2
+ family: openai-reasoning
3
+ checked: 2026-11-26
4
+ source: https://developers.openai.com/api/docs/guides/reasoning
5
+ ---
6
+
7
+ # OpenAI reasoning models
8
+
9
+ Status: documented. The gpt-oss template facts are observed, not documented by OpenAI on that page. Not yet measured here except where an observation date is given.
10
+
11
+ ## Reasoning effort (docs, checked 2026-11-26)
12
+
13
+ - Values are model-dependent and can include `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`. The page warns that defaults are "model-dependent rather than universal".
14
+ - Defaults stated: `medium` for GPT-5.5, GPT-5.6 (both modes), GPT-6.1 Sol, GPT-6 Sol, GPT-6 Luna. GPT-6.1 Sol does not support `none` or `minimal`. GPT-6 Astra rejects `none` with HTTP 400 and no default is stated; GPT-6.2 Astra and GPT-6.2 Sol reject `none` with no default stated.
15
+ - Reasoning tokens occupy context and are billed as output tokens. The page recommends reserving at least 25,000 tokens for reasoning and output when starting out. Hitting `max_output_tokens` can end the response as `incomplete` before any visible output.
16
+ - Summaries are opt-in through `summary`; `auto` is "equivalent to `detailed` for most reasoning models today".
17
+
18
+ ## History and caching
19
+
20
+ - With function calling, pass back the reasoning items returned with the calls along with the tool outputs. With `previous_response_id` prior reasoning carries forward; with history managed by hand keep all output items in their original order. Stateless mode (`store` false or ZDR) returns `encrypted_content` to pass back.
21
+ - On newer models, editing history before a reasoning item can cause it to be dropped.
22
+ - Cache facts are in `providers/openai.md`.
23
+
24
+ ## Tools (observed, via OpenRouter, 2026-11-21)
25
+
26
+ - `tool_choice: "none"` drops the tools from the prompt (`prompt_tokens` halved).
27
+ - 128 tools per request at most; a request with 232 was rejected.
28
+
29
+ ## `openai/gpt-oss-20b` chat template (self-hosted)
30
+
31
+ Observed 2026-09-04 in the model's chat_template.jinja: default reasoning level "medium"; levels low, medium, high; no membership test, so an unknown value is written into the system prompt as `Reasoning: <value>` instead of raising. A typo changes the prompt prefix and the model's behaviour without an error.
32
+
33
+ ## Not stated in the docs
34
+
35
+ - JSON-output quirks for these models: not stated on the page read (checked 2026-11-26).
package/models/qwen.md ADDED
@@ -0,0 +1,34 @@
1
+ ---
2
+ family: qwen
3
+ checked: 2026-11-26
4
+ source: https://huggingface.co/Qwen/Qwen3.8-27B/blob/main/chat_template.jinja
5
+ ---
6
+
7
+ # Qwen (hybrid thinking models, self-hosted)
8
+
9
+ Status: template facts observed in each model's `chat_template.jinja` on 2026-09-04; the Qwen3.8-27B template was re-read at the source URL on 2026-11-26. The other two templates were not re-fetched on 2026-11-26. Documented, not yet measured here except E7.
10
+
11
+ ## Thinking and reasoning controls
12
+
13
+ | Model | `reasoning_effort` | `enable_thinking` | Basis |
14
+ |---|---|---|---|
15
+ | `Qwen/Qwen3.8-27B` | Default `'xhigh'`; allowed `('xhigh', 'medium', 'low')`; any other value raises an exception ("Supported types are xhigh (default), medium, and low"). The check runs only while thinking is enabled | Yes. Thinking is on when `enable_thinking` is undefined or true; when false the generation prompt emits an empty `<think>\n\n</think>\n\n` block | observed 2026-09-04 in the model's chat_template.jinja; re-read 2026-11-26 |
16
+ | `Qwen/Qwen3.6-35B-A3B` | No `reasoning_effort` in the template; the kwarg is ignored | Yes | observed 2026-09-04 in the model's chat_template.jinja |
17
+ | `Qwen/Qwen3.5-27B` | No `reasoning_effort` in the template; the kwarg is ignored | Yes | observed 2026-09-04 in the model's chat_template.jinja |
18
+
19
+ Passing `reasoning_effort` to a server that serves a template without it changes nothing and raises nothing. Check the template before relying on it.
20
+
21
+ ## Cache effects
22
+
23
+ - The chat template renders earlier assistant turns differently depending on the thinking flag, so toggling thinking between turns of one session changes the prefix. Measured loss: 47% of what those turns could have reused (329k tokens), E7. Fix the flag per session.
24
+ - Qwen3.8-27B: past reasoning is rendered by default. The template keeps an assistant turn's reasoning when `preserve_thinking` is undefined or true, or when the turn is after the last user query; otherwise only the answer is rendered. Stripping reasoning from history by hand produced about 3x more generation in agent loops (E11, one model).
25
+ - Hybrid models cache in large blocks; see `providers/vllm.md` (E9).
26
+
27
+ ## Cache markers
28
+
29
+ Self-hosted engines take no cache markers; reuse is by token prefix. Through OpenRouter, Alibaba Qwen endpoints take `cache_control: {"type": "ephemeral"}` only (5-minute TTL; snapshot endpoints do not support it), per OpenRouter's docs checked 2026-11-26.
30
+
31
+ ## Tool-calling and JSON quirks
32
+
33
+ - Served by vLLM, the thinking comes back in a separate `reasoning` field only when the server runs with a reasoning parser (`--reasoning-parser qwen3`); without one it arrives inside `content` as `<think>...</think>` before the answer. Check this before adding a JSON schema: see the structured-output rows in [providers/vllm.md](../providers/vllm.md) and LP-GE-10 (vLLM docs, checked 2026-11-26).
34
+ - Other tool-calling and JSON quirks: not stated in the sources read for this table (checked 2026-11-26).
package/package.json CHANGED
@@ -1,11 +1,34 @@
1
1
  {
2
2
  "name": "leanprompt",
3
- "version": "0.0.1",
4
- "description": "Stop paying for the same prompt twice: skills that teach AI coding assistants to make LLM-calling apps cache-friendly and cheaper. Coming soon.",
5
- "license": "Apache-2.0",
6
- "author": "PodWarden Team",
7
- "homepage": "https://github.com/Podwarden/leanprompt",
8
- "repository": {"type": "git", "url": "git+https://github.com/Podwarden/leanprompt.git"},
9
- "keywords": ["llm", "prompt-caching", "prefill", "kv-cache", "claude-code", "codex", "agents", "skills", "kvsig"],
10
- "files": ["README.md"]
3
+ "version": "0.1.0-dev.8",
4
+ "description": "Get more from every LLM call your app makes: skills that make prompts cacheable, cut dead weight, stop wasted output and speed up first tokens, without changing the answers, plus a CLI to measure the result.",
5
+ "type": "module",
6
+ "license": "Apache-2.0 AND CC-BY-4.0",
7
+ "author": "The LM Warden Team",
8
+ "bin": { "leanprompt": "cli/dist/main.js" },
9
+ "files": ["cli/dist", "skills", "providers", "models", "runtimes", "forms", "NOTICE", "LICENSE-DOCS", "!**/__pycache__"],
10
+ "exports": { "./log": { "types": "./cli/dist/log/logger.d.ts", "default": "./cli/dist/log/logger.js" } },
11
+ "engines": { "node": ">=20.19" },
12
+ "scripts": {
13
+ "prepare": "npm run build",
14
+ "test": "vitest run",
15
+ "build": "tsc && node -e \"require('fs').cpSync('cli/src/report/template.html','cli/dist/report/template.html')\"",
16
+ "typecheck": "tsc -p tsconfig.eval.json",
17
+ "eval": "tsx eval/run.ts",
18
+ "lint:rules": "tsx cli/src/lint/rules.ts",
19
+ "lint:facts": "tsx cli/src/lint/facts.ts",
20
+ "build:forms": "tsx scripts/build-forms.ts",
21
+ "build:diffs": "tsx scripts/readme-diffs.ts",
22
+ "check:numbers": "tsx cli/src/lint/numbers.ts"
23
+ },
24
+ "dependencies": {
25
+ "@kvsig/core": "0.1.0",
26
+ "yaml": "^2.6.0"
27
+ },
28
+ "devDependencies": {
29
+ "@types/node": "^20.19.0",
30
+ "tsx": "^4.19.0",
31
+ "typescript": "^5.6.0",
32
+ "vitest": "^2.1.0"
33
+ }
11
34
  }