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,70 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: LP-GE-08
|
|
3
|
+
title: Route trivially small calls to a small model
|
|
4
|
+
skill: generation-economy
|
|
5
|
+
applies_to: [anthropic, openai, gemini, openrouter, deepinfra, vllm, sglang, any]
|
|
6
|
+
saves: both
|
|
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/reasoning
|
|
12
|
+
checked: 2026-11-26
|
|
13
|
+
---
|
|
14
|
+
## Rule
|
|
15
|
+
Send calls whose task is small and checkable (a conversation title, a label, a yes/no classification, a short rewrite) to a small, fast model instead of the app's main model, and keep the change only where an answer check passes.
|
|
16
|
+
|
|
17
|
+
## Why
|
|
18
|
+
Apps often send every call to the model chosen for the hardest task, at its default effort. A title or a label then pays the large model's price for every input and output token, waits for its slower decode, and on a reasoning model may spend more tokens thinking than answering ([models/openai-reasoning.md](../../../models/openai-reasoning.md), [models/anthropic-thinking.md](../../../models/anthropic-thinking.md)). Smaller models and their prices are on each provider's model and pricing pages; the tables here record what changes caching and generation for them ([providers/anthropic.md](../../../providers/anthropic.md), [providers/openai.md](../../../providers/openai.md), [providers/gemini.md](../../../providers/gemini.md), [providers/openrouter.md](../../../providers/openrouter.md), [providers/deepinfra.md](../../../providers/deepinfra.md)). On a self-hosted server a second model costs GPU memory; it pays only if the small calls are frequent ([providers/vllm.md](../../../providers/vllm.md), [providers/sglang.md](../../../providers/sglang.md)).
|
|
19
|
+
|
|
20
|
+
Two cache effects to account for. A model has its own cache, so a small call that repeats the main conversation's long prefix on another model pays for that prefix again, cold (LP-PC-12): send the small model only what the small task needs. And a small model can have a different minimum cacheable length (per-model table in [providers/anthropic.md](../../../providers/anthropic.md)).
|
|
21
|
+
|
|
22
|
+
Untested here: the cited pages document the cache minimums and reasoning effort, not the size of the saving.
|
|
23
|
+
|
|
24
|
+
## Detect in code
|
|
25
|
+
Python:
|
|
26
|
+
```
|
|
27
|
+
rg -n '(title|label|classif|tag|summary|is_|should_)\w*\(' -g '*.py'
|
|
28
|
+
rg -n 'model\s*=\s*(MODEL|settings\.\w*model|DEFAULT_MODEL)' -g '*.py'
|
|
29
|
+
```
|
|
30
|
+
Shapes: `generate_title(history)` calling the main model with the whole history; `is_spam(text)` or `classify(text, LABELS)` using the same `MODEL` constant as the agent; a reasoning model at high effort for a yes/no question.
|
|
31
|
+
|
|
32
|
+
TS/JS:
|
|
33
|
+
```
|
|
34
|
+
rg -n '(generateTitle|classify|label|isSpam|shouldReply)\w*\(|model:\s*(MODEL|config\.model)' -g '*.{ts,tsx,js,mjs}'
|
|
35
|
+
```
|
|
36
|
+
Shapes: one `model` in a shared client config used for every call.
|
|
37
|
+
|
|
38
|
+
Go:
|
|
39
|
+
```
|
|
40
|
+
rg -n 'func (GenerateTitle|Classify|Label|Is\w+)\(|Model:\s*(cfg\.Model|DefaultModel)' -g '*.go'
|
|
41
|
+
```
|
|
42
|
+
Shapes: a single `Model` field in the client options used for agent turns and for titles alike.
|
|
43
|
+
|
|
44
|
+
Not a finding: small calls where the answer check fails on the small model, and calls whose input needs the large model's context window.
|
|
45
|
+
|
|
46
|
+
## Fix
|
|
47
|
+
```python
|
|
48
|
+
# before: titles from the main model, with the whole conversation
|
|
49
|
+
title = client.chat.completions.create(model=MAIN_MODEL, messages=history + [TITLE_ASK])
|
|
50
|
+
|
|
51
|
+
# after: a small model, the input the task needs, a small output limit
|
|
52
|
+
title = client.chat.completions.create(
|
|
53
|
+
model=SMALL_MODEL,
|
|
54
|
+
messages=[{"role": "user", "content": TITLE_PROMPT + first_user_message}],
|
|
55
|
+
max_completion_tokens=TITLE_LIMIT,
|
|
56
|
+
)
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Keep the model choice in configuration per kind of call (`models: {agent: ..., title: ..., label: ...}`), so it can change without code edits when the answer check says so.
|
|
60
|
+
|
|
61
|
+
## Don't break meaning
|
|
62
|
+
A smaller model can give different, worse answers. Run an answer check before switching each kind of call: a fixed set of synthetic inputs for that call (with expected labels, or titles a fixed judge prompt accepts), run through the large model and the small one, compare the outputs (exact match for labels and yes/no, a schema match or the judge for free text), and record pass/fail per input. Switch only the kinds of call where the small model passes at least as many inputs as the large one, and rerun the check when either model changes.
|
|
63
|
+
|
|
64
|
+
## Verify
|
|
65
|
+
(a) Provider usage: per model, `prompt_tokens` and `output_tokens` / `completion_tokens` for the small calls move to the small model; with the price card, the cost per small call falls. The main conversation's `cached_tokens` stays the same (the small calls must not change its prefix).
|
|
66
|
+
|
|
67
|
+
(b) leanprompt usage record: records for the small calls show the small `model`; `flags.parse_failed` and `flags.retry_of` on them do not rise after the switch (a rising rate means the small model is failing the task and the saving is being spent on retries).
|
|
68
|
+
|
|
69
|
+
## Waste signal
|
|
70
|
+
Not in the score (model choice is outside it). Static: severity medium for a label, title or yes/no call on the app's main or reasoning model; reported with the answer-check requirement.
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: LP-GE-09
|
|
3
|
+
title: Predicted outputs for mostly unchanged text
|
|
4
|
+
skill: generation-economy
|
|
5
|
+
applies_to: [openai, vllm, anthropic, gemini, openrouter, deepinfra, sglang]
|
|
6
|
+
saves: generation
|
|
7
|
+
severity: low
|
|
8
|
+
evidence:
|
|
9
|
+
- doc: https://developers.openai.com/api/docs/guides/predicted-outputs
|
|
10
|
+
checked: 2026-11-26
|
|
11
|
+
- doc: https://docs.vllm.ai/en/latest/features/speculative_decoding/
|
|
12
|
+
checked: 2026-11-26
|
|
13
|
+
---
|
|
14
|
+
## Rule
|
|
15
|
+
When a call returns a long text that is mostly the input unchanged (editing a file, fixing a few lines, updating a document), either pass the current text as a predicted output where the provider supports it, or ask for only the changes (a diff or search-and-replace edits) and apply them in code.
|
|
16
|
+
|
|
17
|
+
## Why
|
|
18
|
+
Regenerating a whole file to change three lines pays for, and waits for, every unchanged token. There are two ways out.
|
|
19
|
+
|
|
20
|
+
- **Predicted outputs** (speed). OpenAI Chat Completions takes a `prediction` with the expected text, on the models listed in [providers/openai.md](../../../providers/openai.md). The docs say it improves response times when large parts of the output are known ahead of time. Rejected prediction tokens are billed as completion tokens, so a poor prediction adds cost (this follows from that billing rule); and the feature does not work with `n` > 1, tools, `logprobs` and a few other parameters. The Responses API and reasoning models are not mentioned on the page. Anthropic, Gemini, OpenRouter, DeepInfra and SGLang list no prediction parameter on the pages read ([providers/anthropic.md](../../../providers/anthropic.md), [providers/gemini.md](../../../providers/gemini.md), [providers/openrouter.md](../../../providers/openrouter.md), [providers/deepinfra.md](../../../providers/deepinfra.md), [providers/sglang.md](../../../providers/sglang.md)). On a self-hosted vLLM, n-gram speculative decoding is the nearest engine-side feature: it is set on the server, not per request. With MTP speculative decoding on a hybrid model, one more cache block was dropped (E9); whether n-gram speculation does the same is untested here ([providers/vllm.md](../../../providers/vllm.md)).
|
|
21
|
+
- **Ask for the changes only** (tokens and speed, any provider). The output shrinks from the whole text to the edits. This works everywhere and saves output tokens, at the cost of code that applies the edits and fails loudly when one does not apply.
|
|
22
|
+
|
|
23
|
+
Documented, not yet measured here.
|
|
24
|
+
|
|
25
|
+
## Detect in code
|
|
26
|
+
Python:
|
|
27
|
+
```
|
|
28
|
+
rg -n 'Return the (full|entire|complete|whole) (file|document|text|code)|rewrite the (file|document)|write_text\(.*choices\[0\]' -g '*.py'
|
|
29
|
+
rg -n 'prediction\s*=' -g '*.py'
|
|
30
|
+
```
|
|
31
|
+
Shapes: a prompt that sends a file and asks for the whole file back with a small change; `path.write_text(resp.choices[0].message.content)` after an edit request; an edit loop with no `prediction` on a provider and model that support it.
|
|
32
|
+
|
|
33
|
+
TS/JS:
|
|
34
|
+
```
|
|
35
|
+
rg -n 'full (file|document)|entire (file|document)|writeFile\(.*(content|text)|prediction:' -g '*.{ts,tsx,js,mjs}'
|
|
36
|
+
```
|
|
37
|
+
Shapes: `await fs.writeFile(path, completion.choices[0].message.content)` on an edit task.
|
|
38
|
+
|
|
39
|
+
Go:
|
|
40
|
+
```
|
|
41
|
+
rg -n 'os\.WriteFile\(|Prediction|full file|entire file' -g '*.go'
|
|
42
|
+
```
|
|
43
|
+
Shapes: a handler that overwrites a file with the model's whole output after a small edit request.
|
|
44
|
+
|
|
45
|
+
## Fix
|
|
46
|
+
OpenAI Chat Completions, on a supported model:
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
resp = client.chat.completions.create(
|
|
50
|
+
model=EDIT_MODEL,
|
|
51
|
+
messages=[{"role": "user", "content": EDIT_INSTRUCTIONS + "\n\n" + current_text}],
|
|
52
|
+
prediction={"type": "content", "content": current_text},
|
|
53
|
+
)
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Any provider, changes only:
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
# before: "Return the full file with the fix applied."
|
|
60
|
+
# after
|
|
61
|
+
EDIT_FORMAT = (
|
|
62
|
+
"Return only the edits, as blocks:\n"
|
|
63
|
+
"<<<<<<< SEARCH\n(exact lines from the file)\n=======\n(replacement lines)\n>>>>>>> REPLACE"
|
|
64
|
+
)
|
|
65
|
+
edits = parse_edits(resp_text)
|
|
66
|
+
new_text = apply_edits(current_text, edits) # raise if a SEARCH block is not found exactly once
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Don't break meaning
|
|
70
|
+
The page presents predicted outputs as a latency feature; whether the output is identical with and without a prediction is not stated, so run the answer check on a fixed set of edits before and after. For the changes-only form, an edit that does not apply must fail, never be skipped or applied fuzzily; check the result with the same tests or answer check that judged the full-text form. Keep the file's unchanged parts byte-identical.
|
|
71
|
+
|
|
72
|
+
## Verify
|
|
73
|
+
(a) Provider usage: with predictions, `completion_tokens` and `rejected_prediction_tokens` in `usage` (the rejected count should be small; a large one means the prediction costs more than it saves) and the response time. With changes-only, `output_tokens` / `completion_tokens` per edit falls to roughly the size of the edits.
|
|
74
|
+
|
|
75
|
+
(b) leanprompt usage record: `output_tokens` per edit call falls (changes-only); an edit that failed to apply and was re-asked shows as `flags.parse_failed` followed by a record with `flags.retry_of`, and should be rare.
|
|
76
|
+
|
|
77
|
+
## Waste signal
|
|
78
|
+
Not in the score directly (the full-text output is not a repeat). It shows as fewer output tokens per edit in a before/after run (the `measure-loop` skill). Static: severity low for a whole-file rewrite prompt on edit tasks; with the provider's prediction support noted from the tables.
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: LP-GE-10
|
|
3
|
+
title: Structured output instead of parse-and-re-ask
|
|
4
|
+
skill: generation-economy
|
|
5
|
+
applies_to: [openai, anthropic, gemini, openrouter, deepinfra, vllm, sglang, any]
|
|
6
|
+
saves: generation
|
|
7
|
+
severity: high
|
|
8
|
+
evidence:
|
|
9
|
+
- doc: https://developers.openai.com/api/docs/guides/structured-outputs
|
|
10
|
+
checked: 2026-11-26
|
|
11
|
+
- doc: https://platform.claude.com/docs/en/build-with-claude/structured-outputs
|
|
12
|
+
checked: 2026-11-26
|
|
13
|
+
- doc: https://aistudio.google.com/docs/structured-output
|
|
14
|
+
checked: 2026-11-26
|
|
15
|
+
- doc: https://docs.deepinfra.com/chat/structured-outputs.md
|
|
16
|
+
checked: 2026-11-26
|
|
17
|
+
- doc: https://docs.vllm.ai/en/latest/features/structured_outputs.html
|
|
18
|
+
checked: 2026-11-26
|
|
19
|
+
- doc: https://docs.vllm.ai/en/latest/features/reasoning_outputs.html
|
|
20
|
+
checked: 2026-11-26
|
|
21
|
+
- doc: https://docs.sglang.io/advanced_features/structured_outputs.html
|
|
22
|
+
checked: 2026-11-26
|
|
23
|
+
---
|
|
24
|
+
## Rule
|
|
25
|
+
When code needs to parse the model's answer, request structured output with a schema (or a strict tool call) instead of asking for JSON in prose, parsing it, and asking again when parsing fails.
|
|
26
|
+
|
|
27
|
+
## Why
|
|
28
|
+
A parse failure throws away a whole generated answer and pays for another, and the re-ask usually carries the failed answer and an error message too. Constrained decoding prevents the failure instead of repairing it. What each provider offers ([providers/openai.md](../../../providers/openai.md), [providers/anthropic.md](../../../providers/anthropic.md), [providers/gemini.md](../../../providers/gemini.md), [providers/openrouter.md](../../../providers/openrouter.md), [providers/deepinfra.md](../../../providers/deepinfra.md), [providers/vllm.md](../../../providers/vllm.md), [providers/sglang.md](../../../providers/sglang.md)):
|
|
29
|
+
|
|
30
|
+
- **OpenAI:** `json_schema` with `strict: true` (Responses `text.format`, Chat Completions `response_format`). Only Structured Outputs ensure schema adherence; JSON mode only ensures valid JSON. Refusals come back in a separate `refusal` field.
|
|
31
|
+
- **Anthropic:** `output_config.format` with a JSON schema, and `strict: true` on tools; the docs say no retries are needed for schema violations. Some schema features are not supported (400). Changing the format invalidates the prompt cache for that conversation.
|
|
32
|
+
- **Gemini:** a JSON schema with `application/json`; output is valid JSON, but some constraints are stripped rather than enforced, and the docs say to validate values in the app.
|
|
33
|
+
- **OpenRouter:** `response_format` `json_schema` on models with the structured-outputs capability.
|
|
34
|
+
- **DeepInfra:** `json_object` or `json_schema` with `strict`; the docs warn that a `length` stop can leave the JSON incomplete.
|
|
35
|
+
- **vLLM, SGLang:** `response_format` `json_schema`, plus regex, choice and grammar constraints.
|
|
36
|
+
|
|
37
|
+
Documented, not yet measured here.
|
|
38
|
+
|
|
39
|
+
## Detect in code
|
|
40
|
+
Python:
|
|
41
|
+
```
|
|
42
|
+
rg -n 'json\.loads\(|JSONDecodeError|ValidationError|model_validate_json|re\.search\(r?["'"'"']```json' -g '*.py'
|
|
43
|
+
rg -n 'response_format|output_config|json_schema|strict' -g '*.py'
|
|
44
|
+
```
|
|
45
|
+
Shapes: `try: json.loads(text) except JSONDecodeError: ask again with "That was not valid JSON"`; `re.sub(r"<think>.*?</think>", "", text, flags=re.S)` before parsing, which means the server returns thinking inside the answer (no reasoning parser; see Don't break meaning); a regex that strips a ```` ```json ```` fence before parsing; a prompt line "Respond only with JSON in this format: ..." and no `response_format`; `response_format={"type": "json_object"}` where the code depends on specific fields.
|
|
46
|
+
|
|
47
|
+
TS/JS:
|
|
48
|
+
```
|
|
49
|
+
rg -n 'JSON\.parse\(|SyntaxError|safeParse\(|zod|response_format|json_schema' -g '*.{ts,tsx,js,mjs}'
|
|
50
|
+
```
|
|
51
|
+
Shapes: `try { JSON.parse(text) } catch { return retryWithError(...) }`; a zod `safeParse` failure that triggers a re-ask; `text.replace(/<think>[\s\S]*?<\/think>/, "")` before `JSON.parse` (thinking inside the answer).
|
|
52
|
+
|
|
53
|
+
Thinking inside the answer, any language:
|
|
54
|
+
```
|
|
55
|
+
rg -n '<think>|</think>|reasoning_content' .
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Go:
|
|
59
|
+
```
|
|
60
|
+
rg -n 'json\.Unmarshal\(|ResponseFormat|JSONSchema' -g '*.go'
|
|
61
|
+
```
|
|
62
|
+
Shapes: `if err := json.Unmarshal([]byte(content), &out); err != nil { /* re-ask */ }`.
|
|
63
|
+
|
|
64
|
+
## Fix
|
|
65
|
+
```python
|
|
66
|
+
# before
|
|
67
|
+
resp = client.chat.completions.create(model=MODEL, messages=msgs + [{"role": "user", "content": "Reply only with JSON: {\"label\": ..., \"confidence\": ...}"}])
|
|
68
|
+
try:
|
|
69
|
+
out = json.loads(resp.choices[0].message.content)
|
|
70
|
+
except json.JSONDecodeError:
|
|
71
|
+
out = reask(msgs, resp) # pays for another answer
|
|
72
|
+
|
|
73
|
+
# after
|
|
74
|
+
schema = {
|
|
75
|
+
"type": "object",
|
|
76
|
+
"properties": {"label": {"type": "string", "enum": LABELS}, "confidence": {"type": "number"}},
|
|
77
|
+
"required": ["label", "confidence"],
|
|
78
|
+
"additionalProperties": False,
|
|
79
|
+
}
|
|
80
|
+
resp = client.chat.completions.create(
|
|
81
|
+
model=MODEL, messages=msgs,
|
|
82
|
+
response_format={"type": "json_schema", "json_schema": {"name": "label", "strict": True, "schema": schema}},
|
|
83
|
+
)
|
|
84
|
+
msg = resp.choices[0].message
|
|
85
|
+
if msg.refusal:
|
|
86
|
+
handle_refusal(msg.refusal)
|
|
87
|
+
out = json.loads(msg.content) # schema-constrained
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Keep validating the values in code (ranges, cross-field rules) where the provider does not enforce them, and keep the schema fixed for the life of a cached conversation.
|
|
91
|
+
|
|
92
|
+
## Don't break meaning
|
|
93
|
+
The schema must let the model say what it would have said in prose: allow `null` or an "unknown" value where the answer can be missing, and include a reasoning field before the answer field if the prose form relied on the model explaining first and model thinking is off. With thinking on, a reasoning field makes the model reason twice into one output limit; decide which one stays under LP-GE-03. A schema that forbids those forces an answer that may be wrong.
|
|
94
|
+
|
|
95
|
+
**A self-hosted reasoning model whose thinking arrives inside the answer.** vLLM can keep a schema off the thinking only when it knows where the thinking ends: a server started with a reasoning parser (`--reasoning-parser`) returns the thinking in a separate `reasoning` field, and the structured-output manager starts the constraint after the end of reasoning ([vLLM reasoning outputs](https://docs.vllm.ai/en/latest/features/reasoning_outputs.html), [vLLM structured outputs](https://docs.vllm.ai/en/latest/features/structured_outputs.html), checked 2026-11-26; [providers/vllm.md](../../../providers/vllm.md)). Without a reasoning parser the thinking comes back inside `content` (`<think>...</think>` before the answer), nothing marks where it ends, and it follows that the schema applies to the thinking as well: the model cannot write the thinking it would have written, which can change its answers. Not yet measured here. So, before adding a schema on such a server, either confirm that the server splits reasoning out (a test request returns a non-empty `reasoning` field and `content` without thinking text), or decide under LP-GE-03 to turn thinking off for this call and run the answer check on the fixed inputs with thinking off before adding the schema. Do not add a schema while thinking still arrives in `content`. Size the output limit for the whole object (LP-GE-03), since a cut-off object is still invalid. Run the answer check on a fixed set of inputs before and after.
|
|
96
|
+
|
|
97
|
+
## Verify
|
|
98
|
+
(a) Provider usage: on a self-hosted reasoning model, first send one test request with the schema and check that the response carries the thinking in a separate `reasoning` field and none in `content`; if the thinking is in `content`, the server has no reasoning parser and the fix waits for the LP-GE-03 thinking decision (Don't break meaning). Then: `finish_reason` / `stop_reason` is `stop` / `end_turn` and the content parses on every call; no follow-up call after a parse failure; `output_tokens` / `completion_tokens` per task falls by the re-asks removed. On OpenAI, read `refusal` separately.
|
|
99
|
+
|
|
100
|
+
(b) leanprompt usage record: no records with `flags.parse_failed`, and no `flags.retry_of` records following one. Before the fix, each parse failure shows as a record with `flags.parse_failed` and a re-ask record pointing at it.
|
|
101
|
+
|
|
102
|
+
## Waste signal
|
|
103
|
+
Measured: output tokens of answers discarded after a parse failure (`flags.parse_failed`) count as generation waste. Static: severity high for a parse-and-re-ask loop; medium for JSON requested in the prompt with no schema on a provider that supports one. On a self-hosted server that returns thinking inside `content`, the finding stands, but record the fix as waiting on the LP-GE-03 thinking decision.
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: leanprompt
|
|
3
|
+
description: Use when the user types /leanprompt or $leanprompt, alone or with a command (init, audit, fix, measure, score, report, lesson), or asks what leanprompt can do for an app's LLM calls. The entry point to the leanprompt skills; it lists the commands and routes each one to the skill or CLI command that does the work.
|
|
4
|
+
argument-hint: "[init | audit | fix | measure | score | report | lesson] [target]"
|
|
5
|
+
license: CC-BY-4.0
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
# leanprompt
|
|
9
|
+
|
|
10
|
+
One command for the leanprompt skills. Each subcommand routes to the skill that does the work; this file holds no rules of its own, so read the file the table points at and follow it.
|
|
11
|
+
|
|
12
|
+
## Commands
|
|
13
|
+
|
|
14
|
+
| Command | What it does | Read |
|
|
15
|
+
|---|---|---|
|
|
16
|
+
| `init` | Reads the code, asks only what it cannot infer (targets, priority, monthly volume, prices with source and date), and writes `leanprompt.yaml` on a yes | [init.md](init.md) |
|
|
17
|
+
| `audit [path]` | Finds every LLM call, checks it against the rules, ranks the findings, writes `leanprompt-report.md` and `.leanprompt/findings.json` | [llm-call-audit](../llm-call-audit/SKILL.md) |
|
|
18
|
+
| `fix [rule or file]` | Works through the open findings one at a time: checks each against the code first, shows the diff, applies it only on a yes | [fix.md](fix.md) |
|
|
19
|
+
| `measure` | Proves a fix with a before and after on the same scenario; sets up the usage logger and the stable-head test | [measure-loop](../measure-loop/SKILL.md) |
|
|
20
|
+
| `score` | Runs `npx leanprompt score` and explains the number and its kind (measured or static) | [llm-call-audit](../llm-call-audit/SKILL.md#the-score) |
|
|
21
|
+
| `report` | Runs `npx leanprompt report --html` and gives the path of the page to read and share | [presenting.md](../llm-call-audit/presenting.md#the-page-the-hand-off-and-sharing) |
|
|
22
|
+
| `lesson` | Drafts a lesson-learned issue on this machine with `npx leanprompt lesson`; sends nothing | [llm-call-audit](../llm-call-audit/SKILL.md#sharing-a-lesson) |
|
|
23
|
+
|
|
24
|
+
The rules themselves live in [prefill-cache](../prefill-cache/SKILL.md), [generation-economy](../generation-economy/SKILL.md), [prompt-diet](../prompt-diet/SKILL.md) and [lmwarden](../lmwarden/SKILL.md). Load a rule file only when a command points at it.
|
|
25
|
+
|
|
26
|
+
## Routing
|
|
27
|
+
|
|
28
|
+
- **No command.** Show this menu, one line per command, and nothing else:
|
|
29
|
+
|
|
30
|
+
```
|
|
31
|
+
leanprompt: get more from every LLM call your app makes
|
|
32
|
+
init set up leanprompt.yaml: targets, priority, volume, prices
|
|
33
|
+
audit find where the app's LLM calls lose tokens and time
|
|
34
|
+
fix work through the findings, one diff at a time, with your yes
|
|
35
|
+
measure prove a fix with a before and after number
|
|
36
|
+
score the score, measured from usage or static from the findings
|
|
37
|
+
report a local page with the findings in plain English
|
|
38
|
+
lesson draft a lesson-learned issue; nothing is sent
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Then suggest one next command, with a one-line reason, from what is in the project: no `leanprompt.yaml` means `init`; no `.leanprompt/findings.json` means `audit`; open findings (not `fixed`) mean `fix`; a fixed finding with no before and after means `measure`. Never run a command the user did not ask for.
|
|
42
|
+
- **A command.** Read the file in its row and follow it. Text after the command is its target (a folder, a file, a rule id such as `LP-PC-03`).
|
|
43
|
+
- **A question or a plain request.** "Why does this app pay for the same prompt twice" is `audit`; "is this fix working" is `measure`. If two commands fit, ask once which one.
|
|
44
|
+
|
|
45
|
+
## Running the CLI
|
|
46
|
+
|
|
47
|
+
The commands above call the leanprompt CLI as `npx leanprompt <command>`. Until the npm package is published, run it as `npx github:Podwarden/leanprompt <command>`. `score`, `report --html` and `calibrate` only read and write files under `.leanprompt/` and make no network calls. Ask before editing code, installing a package, or running anything that sends requests to a provider, which are billed.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# /leanprompt fix
|
|
2
|
+
|
|
3
|
+
Works through the open findings in `.leanprompt/findings.json`, largest first. With a target (a rule id or a file), only the findings that match it. If there is no findings file, say so and offer `/leanprompt audit` first.
|
|
4
|
+
|
|
5
|
+
These are the same hand-off rules as the "Fix it with your coding agent" block on the report page:
|
|
6
|
+
|
|
7
|
+
1. **Check each finding against the code first.** Open the file and line, read the rule's "Detect in code", and confirm the finding still holds. The audit can be wrong, and code changes after it. If it does not hold, say why, leave the code alone, and offer to remove the finding from the file.
|
|
8
|
+
2. **One finding at a time.** Present it as a decision with the four choices in [presenting.md](../llm-call-audit/presenting.md#one-finding-at-a-time): `fix now`, `explain more`, `skip`, `don't flag this again`.
|
|
9
|
+
3. **Show the diff.** One fix per finding, the smallest one in the rule's "Fix", as a small diff ([presenting.md](../llm-call-audit/presenting.md#fixes-and-proofs)). Before a fix that moves or removes content, ask the reorder or trim question first.
|
|
10
|
+
4. **Apply only on a yes.** A yes covers that one diff, nothing more.
|
|
11
|
+
5. **Prove it.** Hand the fix to [measure-loop](../measure-loop/SKILL.md): a before and after on the same scenario. Ask before running anything that sends billed requests. A fix that can change answers needs its answer check to pass first.
|
|
12
|
+
6. **Record it.** When a fix is proved, set `"fixed": true` on its finding and run `npx leanprompt score` again.
|
|
13
|
+
|
|
14
|
+
After the last finding, say what changed: fixed, skipped and ignored counts, and the new score with its kind.
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# /leanprompt init
|
|
2
|
+
|
|
3
|
+
Writes `leanprompt.yaml` at the project root, so later commands do not ask the same questions again. The schema is in [docs/profile.md](../../docs/profile.md). Ask one question at a time, as [presenting.md](../llm-call-audit/presenting.md#asking-questions) describes, and write the file only on a yes.
|
|
4
|
+
|
|
5
|
+
## 1. Read first
|
|
6
|
+
|
|
7
|
+
Before asking anything, read what the code already says ([call-shapes.md](../llm-call-audit/call-shapes.md), "Which provider and model"):
|
|
8
|
+
|
|
9
|
+
- the SDK or HTTP client, the base URL and the model names of every call site;
|
|
10
|
+
- whether some calls go to a self-hosted engine (vLLM, SGLang, LM Warden) and others to a hosted API: then each backend is its own `targets` entry, with its call sites under `files:`;
|
|
11
|
+
- launch files, compose files and engine flags, for the `engine:` facts;
|
|
12
|
+
- an existing `leanprompt.yaml`: keep every key and comment it has, and ask only for what is missing.
|
|
13
|
+
|
|
14
|
+
For an LM Warden server, offer `npx leanprompt profile detect --lmwarden <url>` instead of asking for the engine facts ([lmwarden](../lmwarden/SKILL.md)).
|
|
15
|
+
|
|
16
|
+
## 2. Ask only what the code cannot tell
|
|
17
|
+
|
|
18
|
+
1. **Targets**, only when the code reads the provider or model from the environment at run time and nothing else names it.
|
|
19
|
+
2. **Priority:** cost, speed or quality, or weights. It decides the order of the advice; caching applies whatever the answer.
|
|
20
|
+
3. **Monthly volume:** how many calls the app makes a month, and where the number comes from. With a usage log, infer it from the log instead and say so.
|
|
21
|
+
4. **Prices:** offer to look up the current price of each model on the provider's pricing page, or take the user's own price. Every price needs a `source` and a `checked` date; a price without them is rejected. The fields are in [llm-call-audit](../llm-call-audit/SKILL.md#volume-and-prices).
|
|
22
|
+
|
|
23
|
+
A user may skip volume and prices: the report then shows tokens only.
|
|
24
|
+
|
|
25
|
+
## 3. Show, then write
|
|
26
|
+
|
|
27
|
+
Show the exact lines that would be written, then ask whether to write them. Answering a question is not consent to writing the file. On a yes, write the file and say which keys were added. On a no, keep the answers for this session only.
|
|
28
|
+
|
|
29
|
+
Then suggest `/leanprompt audit`.
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: llm-call-audit
|
|
3
|
+
description: Use when asked to audit, review or reduce the cost or latency of an app that calls LLMs (chatbots, agents, RAG, extraction pipelines, evals, batch jobs) through Anthropic, OpenAI, Gemini, OpenRouter, DeepInfra, LangChain, LlamaIndex, LiteLLM, the Vercel AI SDK, raw HTTP, or a self-hosted vLLM, SGLang or LM Warden server; when someone asks "where does this app pay for the same tokens twice", wants a leanprompt score or badge, or wants a ranked list of LLM-call fixes. Finds every LLM call, checks it against the leanprompt rules, ranks the findings by tokens lost, and writes leanprompt-report.md and .leanprompt/findings.json.
|
|
4
|
+
license: CC-BY-4.0
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# llm-call-audit
|
|
8
|
+
|
|
9
|
+
Finds every place an app calls an LLM and every place it pays for tokens it does not need: prompts the provider's cache could have reused and did not, dead weight the call did not need to send, and output the app generated and then threw away. Each finding is tied to a rule, a file and line, an estimate of the tokens it loses per 1,000 calls, one fix, and a way to verify the fix. The result is a report, `leanprompt-report.md`, a findings file, `.leanprompt/findings.json`, and a score from the leanprompt CLI.
|
|
10
|
+
|
|
11
|
+
The audit owns no rules of its own. It finds the calls and applies the rules of the other five skills:
|
|
12
|
+
|
|
13
|
+
- [prefill-cache](../prefill-cache/SKILL.md): `LP-PC-*`, prompts the cache can reuse.
|
|
14
|
+
- [generation-economy](../generation-economy/SKILL.md): `LP-GE-*`, calls and output that are not wasted.
|
|
15
|
+
- [prompt-diet](../prompt-diet/SKILL.md): `LP-PD-*`, dead weight in what each call sends.
|
|
16
|
+
- [lmwarden](../lmwarden/SKILL.md): `LP-LW-*`, self-hosted servers.
|
|
17
|
+
- [measure-loop](../measure-loop/SKILL.md): how each fix is proved, and the score.
|
|
18
|
+
|
|
19
|
+
The audit never edits code without asking. It proposes one fix per finding, the user decides, and each applied fix is handed to `measure-loop` to prove.
|
|
20
|
+
|
|
21
|
+
Ask first: before you edit the app's code, install a package, add a file outside `.leanprompt/`, or run anything that sends requests to a provider (they are billed), show the change or the command and ask. The user may prefer to run it themselves. No ask is needed for the audit's own `leanprompt-report.md` and `.leanprompt/findings.json`, or for `npx leanprompt score`, `npx leanprompt report --html` and `npx leanprompt calibrate`, which only read and write files under `.leanprompt/` and make no network calls (`calibrate` still writes `.leanprompt/weights.json` only after `y` or `--yes`). Offering to share a lesson (below) needs no ask, but running `npx leanprompt lesson` does: it writes `.leanprompt/lesson.md`, so run it only after the user says yes.
|
|
22
|
+
|
|
23
|
+
## When to use
|
|
24
|
+
|
|
25
|
+
- The user asks to audit an LLM-calling app, to cut its token bill or latency, or to find out why its provider reports few cached tokens.
|
|
26
|
+
- The user wants a leanprompt score or the README badge.
|
|
27
|
+
- A new codebase arrives and you want to know what it calls, with which model, and how.
|
|
28
|
+
|
|
29
|
+
For a single change you are writing right now (a new prompt builder, a new retry), use `prefill-cache`, `generation-economy` or `prompt-diet` directly; the audit is for the whole app.
|
|
30
|
+
|
|
31
|
+
## Workflow
|
|
32
|
+
|
|
33
|
+
1. **Know the target and priority.** Read `leanprompt.yaml` at the project root ([docs/profile.md](../../docs/profile.md)): `target` (provider or self-hosted engine, model family, context length), `engine` (self-hosted cache facts), `priority` (cost, speed, quality or weights) and `ignore`. If the file is absent, infer the target from the code ([call-shapes.md](call-shapes.md), "Which provider and model") and ask for what the code cannot tell you, above all the priority; then offer to save the answers to `leanprompt.yaml` so they are not asked again, show the lines that would be written, and write them only on a yes ([presenting.md](presenting.md)). When the app has more than one backend (a self-hosted engine and a hosted API chosen at run time, or one per call site), record each as its own `targets` entry, with the call sites' files under `files:` when they are known; the same offer applies: show the lines and write them only on a yes. For an LM Warden server, offer `npx leanprompt profile detect --lmwarden <url>`, which reads the engine facts from the server instead of asking (the [lmwarden](../lmwarden/SKILL.md) skill describes it).
|
|
34
|
+
2. **Inventory the calls.** Find every call site with [call-shapes.md](call-shapes.md): SDKs, frameworks, raw HTTP (search the path without the version too, `chat/completions`, `/messages`, `/responses`, because the base URL usually ends in `/v1`, and the request body with a `messages` list near the HTTP call), and the app's own wrappers. A search hit is a candidate: open it and confirm it is a request the app really sends before listing it (a doc comment or a test string is not a call). For each, record file and line, provider, model and call kind (chat, agent loop, one-shot, batch), and follow it back to where its system prompt, tools, history and request options are built.
|
|
35
|
+
3. **Check the rules.** For each call site, walk the parts of the request through the rule map below and open a rule file when its "Detect in code" pattern matches. With several backends, evaluate the rules per backend: a call site that can go to either is checked once for each, and `applies_to` is checked against each finding's backend, not against the app as a whole. Raise a rule when its `applies_to` frontmatter includes the target, or includes `any`: a rule marked `any` is provider-independent (the fix is the same on every target) and applies to every call, including calls to a host with no provider table (DeepSeek, Groq, Together, Azure and other OpenAI-compatible hosts); `applies_to` restricts only the provider-specific rules. For a provider-specific rule on a host with no table, raise it only if that host's own documentation shows the feature (say which page); otherwise write "unknown, check the provider's docs" and do not assume. Drop any finding whose rule and file are on the `ignore:` list.
|
|
36
|
+
4. **Read the usage, if there is any.** If `.leanprompt/usage.jsonl` exists, run `npx leanprompt score` first and read its inputs and its heads diagnostic (below); they confirm, correct or add to what the code shows.
|
|
37
|
+
5. **Estimate and rank.** Give each finding an estimate of the tokens it loses per 1,000 calls (below), labelled as an estimate or as measured, and rank by it. Turn each estimate into the finding's `share` and `tokens_per_1k`, and write its plain-English `problem`, `change`, `why`, `estimate`, `assumptions` and `verify` ("The findings file", below). Before proposing any cache mark, apply the break-even rule (below).
|
|
38
|
+
6. **Ask for volume and prices.** Ask how many calls the app makes a month and offer to look up the current price ("Volume and prices", below), so the report can say what the findings cost. Skip it if the user declines: the report then shows tokens only.
|
|
39
|
+
7. **Write the files.** Write `.leanprompt/findings.json` (format below), run `npx leanprompt score`, write `leanprompt-report.md` at the project root from [report-template.md](report-template.md), and run `npx leanprompt report --html` for the page the user reads and shares.
|
|
40
|
+
8. **Present and decide.** Show the summary first, then one finding at a time as a decision, as [presenting.md](presenting.md) describes. For each finding the user wants fixed, show one fix as a small diff and apply it only after the user says yes.
|
|
41
|
+
9. **Prove each fix.** Ask before running anything that sends requests or adds files, then hand over to `measure-loop` (below), mark the finding `fixed` and rescore.
|
|
42
|
+
10. **Offer calibration** after a static score (below).
|
|
43
|
+
11. **Offer to share a lesson** after a measured result or a rule that misled (below).
|
|
44
|
+
|
|
45
|
+
## Rule map: where each rule looks
|
|
46
|
+
|
|
47
|
+
| Part of the request | Rules |
|
|
48
|
+
|---|---|
|
|
49
|
+
| Cache marks (Anthropic, and Anthropic or Gemini models behind a router) | [LP-PC-01](../prefill-cache/rules/LP-PC-01.md), [LP-PC-11](../prefill-cache/rules/LP-PC-11.md) |
|
|
50
|
+
| System prompt: what comes first, what varies per call, user or session, what is said twice | [LP-PC-02](../prefill-cache/rules/LP-PC-02.md), [LP-PC-03](../prefill-cache/rules/LP-PC-03.md), [LP-PC-07](../prefill-cache/rules/LP-PC-07.md), [LP-PD-02](../prompt-diet/rules/LP-PD-02.md) |
|
|
51
|
+
| Tool list and JSON serialisation | [LP-PC-04](../prefill-cache/rules/LP-PC-04.md), [LP-PC-05](../prefill-cache/rules/LP-PC-05.md), [LP-PD-01](../prompt-diet/rules/LP-PD-01.md), [LP-PD-06](../prompt-diet/rules/LP-PD-06.md) |
|
|
52
|
+
| What each turn adds: per-turn reminders, tool results, retrieved context | [LP-PD-03](../prompt-diet/rules/LP-PD-03.md), [LP-PD-04](../prompt-diet/rules/LP-PD-04.md), [LP-PD-06](../prompt-diet/rules/LP-PD-06.md) |
|
|
53
|
+
| History, compaction, attachments | [LP-PC-06](../prefill-cache/rules/LP-PC-06.md), [LP-PC-08](../prefill-cache/rules/LP-PC-08.md), [LP-PC-10](../prefill-cache/rules/LP-PC-10.md), [LP-PD-05](../prompt-diet/rules/LP-PD-05.md) |
|
|
54
|
+
| Thinking, reasoning effort, output limits | [LP-PC-09](../prefill-cache/rules/LP-PC-09.md), [LP-GE-03](../generation-economy/rules/LP-GE-03.md) |
|
|
55
|
+
| Model, key and route per request | [LP-PC-12](../prefill-cache/rules/LP-PC-12.md), [LP-GE-08](../generation-economy/rules/LP-GE-08.md) |
|
|
56
|
+
| Loops and fan-out over calls | [LP-GE-01](../generation-economy/rules/LP-GE-01.md), [LP-GE-02](../generation-economy/rules/LP-GE-02.md), [LP-GE-06](../generation-economy/rules/LP-GE-06.md), [LP-GE-07](../generation-economy/rules/LP-GE-07.md) |
|
|
57
|
+
| Timeouts, retries, streaming, parsing, edits | [LP-GE-04](../generation-economy/rules/LP-GE-04.md), [LP-GE-05](../generation-economy/rules/LP-GE-05.md), [LP-GE-09](../generation-economy/rules/LP-GE-09.md), [LP-GE-10](../generation-economy/rules/LP-GE-10.md) |
|
|
58
|
+
| Self-hosted server: launch flags, replicas, keys | [LP-LW-01](../lmwarden/rules/LP-LW-01.md), [LP-LW-02](../lmwarden/rules/LP-LW-02.md), [LP-LW-03](../lmwarden/rules/LP-LW-03.md) |
|
|
59
|
+
|
|
60
|
+
An `lm-warden` target counts as `vllm` when you match `applies_to`, as it does for the cache tables. With no known target, check every rule and say which ones depend on the provider. A known target with no table of its own is not an unknown target: apply the `any` rules, and treat the provider-specific ones as above.
|
|
61
|
+
|
|
62
|
+
The priority changes the order and the advice, not what counts as waste: follow the priority-aware advice in [generation-economy](../generation-economy/SKILL.md). Caching never changes answers, so the `LP-PC-*` findings apply under every priority. Dead weight costs under every priority too, but a trim can change answers, so every `LP-PD-*` fix carries an answer check, and a trim of the shared head is weighed against the cache it breaks ([prompt-diet](../prompt-diet/SKILL.md), "Three things every trim must respect"). Findings that change price or latency but not tokens (a batch API, LP-GE-07; a smaller model, LP-GE-08) have no tokens lost to rank by; list them after the token findings, in the order the priority gives them.
|
|
63
|
+
|
|
64
|
+
## Estimating tokens lost per 1,000 calls
|
|
65
|
+
|
|
66
|
+
Findings are ranked by the tokens each one loses per 1,000 calls of the whole app, so a large leak on a rare call ranks below a small leak on every call. Write each number with its kind: "(estimate)" when it comes from the code, "(measured, N calls)" when it comes from the usage log.
|
|
67
|
+
|
|
68
|
+
With no usage log, estimate it from the code, as the product of three things, and say it is an estimate:
|
|
69
|
+
|
|
70
|
+
1. **Tokens lost on an affected call.** For a prefill finding, the size of the part of the prompt the cache could have reused and now recomputes: everything from the first byte that changes to the end of the otherwise stable part, in the provider's render order (the "Why" of each rule gives the order). For a generation finding, the output tokens of the call that is repeated, retried or thrown away, or the prompt tokens of a context sent once per question or sample (LP-GE-01, LP-GE-02). For a dead-weight finding (LP-PD-*), the tokens of what the call need not send: the unused tool definitions, the repeated instruction or reminder, the part of a tool result or retrieved context that was cut, the stale history; count it on every later call that carries it, and say in the assumptions how much of it was read from the cache. Count tokens with the provider's tokenizer or token-counting endpoint when you can; otherwise estimate from the text's length and say so.
|
|
71
|
+
2. **How often a call is affected.** A value that changes on every call (a timestamp, a request id) affects every call; a value that changes per session or per user affects the first call of each session or user; a history rewrite affects every turn after it; a retry on truncation affects the calls that hit the limit.
|
|
72
|
+
3. **This call site's share of the app's calls,** from the call kind: an agent loop makes many calls per task, a title or label call one per conversation. When you cannot tell, treat the call sites as equal and say so.
|
|
73
|
+
|
|
74
|
+
Apply the provider's limits before you multiply: a prefix shorter than the provider's minimum cacheable size loses nothing, and a self-hosted engine reuses only whole blocks. Those numbers are in [providers/](../../providers/) and in `leanprompt.yaml`'s `engine:` block; read them there.
|
|
75
|
+
|
|
76
|
+
With a usage log, measure instead. `.leanprompt/usage.jsonl` holds `prompt_tokens`, `cached_tokens` and `output_tokens` per call and no file or line, so match records to a call site by provider, model and `ids.head`, and count the prompt tokens that were not cached on calls that continue a conversation, and the output tokens of repeated, retried and parse-failed calls ([generation-economy](../generation-economy/SKILL.md), "Reading the usage record"). Where a record cannot be matched to one call site, keep the code estimate for that finding.
|
|
77
|
+
|
|
78
|
+
## Volume and prices
|
|
79
|
+
|
|
80
|
+
The tokens a finding loses per 1,000 calls become money only with two facts the code does not hold: how many calls the app makes, and what a token costs. leanprompt never invents either, and the page and the report show tokens only until both are known.
|
|
81
|
+
|
|
82
|
+
- **Volume.** Ask how many calls the app makes a month. With a usage log, infer it from the log instead (records over the days the log covers, scaled to a month) and say that is where it came from. Record it as `volume: {calls_per_month: N, source: "..."}`; with `targets:`, give each entry its own `volume:`.
|
|
83
|
+
- **Prices.** Offer to look up the current price of each model on the provider's pricing page, and give the date you read it; or take the user's own price (a contract, a reseller). Record it under `prices:` by model name, in US dollars per million tokens: `input`, `output`, `cached_input` (needed to price tokens the cache could have served) and `cache_write` when the provider charges for it, with `source` (the page's URL, or where the user's price comes from) and `checked` (the date, `YYYY-MM-DD`). A price without a source and a date is rejected.
|
|
84
|
+
- **Self-hosted.** There is no token price; offer `prefill_tokens_per_second` under `engine:` (or the entry's `engine_facts:`), the engine's measured prefill throughput, so the page can show GPU prefill time a month and the first-token time a finding adds.
|
|
85
|
+
|
|
86
|
+
Show the lines that would be written and offer to save them to `leanprompt.yaml`; write them only on a yes, as for the other answers ([docs/profile.md](../../docs/profile.md)). If a finding's calls go to one of several priced models, set its `model` to that model's name in `prices:`.
|
|
87
|
+
|
|
88
|
+
## The break-even rule for cache marks
|
|
89
|
+
|
|
90
|
+
Before recommending a cache mark, apply the break-even rule in [LP-PC-01](../prefill-cache/rules/LP-PC-01.md): where the provider charges a premium for cache writes, a prefix that is not read again within the cache lifetime costs more marked than unmarked. Estimate how often each marked prefix returns within the lifetime: from the usage log, by the time between records with the same `ids.head` or `ids.nodes` prefix; from the code, by the call kind (a chat or agent loop returns within seconds, a one-shot prompt may never return, a nightly job returns once a day). Then advise one of four things: mark, don't mark, longer lifetime, restructure (move the varying part after the stable one so a mark can cover more). The write and read prices and the lifetimes are in [providers/anthropic.md](../../providers/anthropic.md) and the other provider tables; LP-PC-11 covers pauses longer than the lifetime.
|
|
91
|
+
|
|
92
|
+
## The heads diagnostic
|
|
93
|
+
|
|
94
|
+
After `npx leanprompt score` writes a measured score, read `diagnostics.heads` in `.leanprompt/score.json`: `distinct_head` is how many distinct heads (system prompt and tools together) the log holds, and `conversations` how many distinct conversations. An app whose call sites each send one fixed head should show about as many distinct heads as it has distinct prompts (roles, agents, call sites), however many conversations it logged. Many distinct heads for the conversation count, growing as `conversations` grows, means something per session, per user or per compaction is in the head. The score cannot see this: its stability figure counts only requests that continue a conversation, so a head that differs between conversations costs reuse on every first request without lowering it (E4, E5). Look for LP-PC-03 (a per-session value at the top of the prompt), LP-PC-07 (per-user context before shared context) and LP-PC-08 (compaction that rewrites the system prompt and starts a new conversation), and raise the one the code shows, with the counts as its evidence.
|
|
95
|
+
|
|
96
|
+
## The findings file
|
|
97
|
+
|
|
98
|
+
`.leanprompt/findings.json` is what `npx leanprompt score --static` reads. Write it from the code as it is now, one entry per finding (the same rule in two files is two entries):
|
|
99
|
+
|
|
100
|
+
```json
|
|
101
|
+
{
|
|
102
|
+
"v": 1,
|
|
103
|
+
"average_call": { "prompt_tokens": 4500, "output_tokens": 900 },
|
|
104
|
+
"findings": [
|
|
105
|
+
{ "rule": "LP-PC-03", "file": "src/agent/prompt.ts", "line": 12, "saves": "prefill", "severity": "high", "share": 0.42,
|
|
106
|
+
"tokens_per_1k": { "uncached": 1890000 },
|
|
107
|
+
"problem": "The system prompt starts with the current time, so it is different on every call and the provider cannot reuse any of it.",
|
|
108
|
+
"change": "Move the time out of the system prompt into the newest user message.",
|
|
109
|
+
"why": "Every call pays full price for the whole 1,900-token system prompt instead of the cached price.",
|
|
110
|
+
"estimate": "about 1.9M prompt tokens per 1,000 calls not served from cache",
|
|
111
|
+
"assumptions": "every call goes through this prompt; the system prompt is about 1,900 tokens",
|
|
112
|
+
"verify": "On the second of two requests a minute apart, cached tokens rise from 0 to about the size of the system prompt." },
|
|
113
|
+
{ "rule": "LP-GE-05", "file": "app/llm.py", "line": 40, "saves": "generation", "severity": "high", "fixed": true },
|
|
114
|
+
{ "rule": "LP-PD-04", "file": "app/tools.py", "line": 18, "saves": "prefill", "severity": "high", "share": 0.12,
|
|
115
|
+
"tokens_per_1k": { "prompt": 540000 } },
|
|
116
|
+
{ "rule": "LP-LW-01", "file": "<external>", "where": "vLLM launch flags on the inference host", "saves": "prefill", "severity": "high",
|
|
117
|
+
"status": "needs-facts", "confirm": "the engine's block size and whether --prefix-match-unit is set" }
|
|
118
|
+
]
|
|
119
|
+
}
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
The numbers in this example are illustrative, not from a real app.
|
|
123
|
+
|
|
124
|
+
- `rule`: an existing rule id. An unknown id, or any malformed entry, makes `score` stop with an error that names it.
|
|
125
|
+
- `file`: the path relative to the project root, with forward slashes. The `ignore:` list matches on this exact string. For a finding that lives outside the repository (an engine's launch flags, a gateway's config, a server you only call), write `"<external>"` and say where in `where`.
|
|
126
|
+
- `line`: the line the fix changes, a positive integer. For `"<external>"` it is optional (0 or left out).
|
|
127
|
+
- `where` (required with `"<external>"`): free text naming the place, for example "engine launch flags".
|
|
128
|
+
- `status` (optional): `needs-facts` when whether the finding holds depends on a fact the code cannot show (the engine's block size, the share of traffic on a path). It then needs `confirm`: the fact that would confirm or dismiss it, written as something the user can check.
|
|
129
|
+
- `saves`: `prefill`, `generation` or `both`, from the rule's frontmatter.
|
|
130
|
+
- `severity`: `high`, `medium` or `low`, as the rule's "Waste signal" assigns it for the shape you found (several rules give different severities for different shapes).
|
|
131
|
+
- `share` (required for every finding): the fraction, from 0 to 1, of the app's prompt tokens (prefill) or output tokens (generation) this finding wastes, derived from its tokens-lost-per-1,000-calls estimate above: share = estimated tokens lost on the affected side per 1,000 calls ÷ that side's tokens for the same 1,000 calls (prompt tokens for `prefill`, output tokens for `generation`, over all the app's calls, not only the affected ones). Write the assumptions behind both numbers in the report (call mix, tokens per call, how often the affected path runs). For a `both` finding the score applies the one share on each side: compute it for both, record the larger, and give both in the report. Fall back to the severity default (leave `share` out) only when no estimate is possible, and say so in the report, with the reason. `npx leanprompt score --static` prints how many findings used a default (`default_shares: N of M`). `leanprompt calibrate` does not rescale a share you set.
|
|
132
|
+
- `fixed` (optional): `true` once the fix is applied and proved. The score skips fixed findings.
|
|
133
|
+
- `tokens_per_1k` (on every finding you can estimate): the tokens it loses per 1,000 calls of the whole app, split by how they are billed: `uncached` (prompt tokens the cache could have served), `prompt` (prompt tokens sent that need not be sent at all, such as a retry's, or the dead weight of an `LP-PD-*` finding), `output` (output tokens thrown away), and `measured_calls` when the numbers come from a usage log of that many calls. The page sums them, ranks by them, and with a volume and prices turns them into money ("Volume and prices", above).
|
|
134
|
+
- `model` (optional): the model name in `prices:` this finding's calls use, when there are several.
|
|
135
|
+
- The plain-English fields, on every finding: `problem` (what is wrong, in one or two sentences a person who has not read the rule follows; no rule ids or jargon), `change` (what to change), `why` (why it costs tokens or time), `estimate` (the number as words, for example `"about 138k tokens per 1,000 calls"`), `assumptions` (what the estimate assumes) and `verify` (how to prove the fix). Plain text, each at most 600 characters: the page and the hand-off block for the user's coding agent are built from them. Older files without them stay valid.
|
|
136
|
+
- `average_call` (top level, optional): the average call's `prompt_tokens` and `output_tokens` you assumed for the shares, so the page can give the saving as a share of the bill.
|
|
137
|
+
|
|
138
|
+
Record every finding you have grounds for, even when it is outside the repository or waits on a fact: leaving it out because it has no file and line hides what may be the largest item. `"<external>"` and `needs-facts` findings count in the static score with their share and severity like any other; the report lists them under "Open questions" with their `confirm` text, so the user can settle each one.
|
|
139
|
+
|
|
140
|
+
## The score
|
|
141
|
+
|
|
142
|
+
`npx leanprompt score` scores the project and writes `.leanprompt/score.json`, which is also the source of the README badge (shields.io's endpoint badge reads that file). With no flags it picks the measured score when `.leanprompt/usage.jsonl` exists and the static score from `.leanprompt/findings.json` otherwise; `--measured <file>` or `--static <file>` chooses, and `--dir <project>` points at another project. It prints `leanprompt score: <score> <kind>` with the inputs E, S and G.
|
|
143
|
+
|
|
144
|
+
- **Measured** needs at least 50 measured calls. With fewer, `score` writes nothing, prints how many measured calls it found and suggests `--static`; then run `npx leanprompt score --static`. A measured score.json records the calls it used, the unmeasured ones, and the diagnostics above.
|
|
145
|
+
- **Static** scores the findings file, leaving out the findings the `ignore:` list names and the ones marked `fixed`. It is an estimate from code, labelled `static` and shown with a grey badge.
|
|
146
|
+
|
|
147
|
+
Always quote the score with its kind. How the score is computed, and where the measured one stops, is in [measure-loop](../measure-loop/SKILL.md) ("Where the measured score stops").
|
|
148
|
+
|
|
149
|
+
## Calibrating a static score
|
|
150
|
+
|
|
151
|
+
After a static score, offer a trial run with `npx leanprompt calibrate` to fit the static weights to this app. The trial run needs the usage logger in the app ([measure-loop](../measure-loop/SKILL.md), "Log every call"; propose it as a diff and add it only on a yes) and a fixed set of realistic inputs sent through the app (several sessions with follow-up turns, at least 50 calls in total). Those are real, billed requests, so the user runs them, or you ask before running them. Then run `npx leanprompt calibrate --synthetic`, which itself makes no calls and only marks the log as a trial run; with a log of real traffic instead, run `npx leanprompt calibrate` without `--synthetic`. It compares the findings with the measured score of that log, prints the static score before and after and the two scale factors, and asks before it writes `.leanprompt/weights.json`; nothing is written without `y`, or `--yes`. Run from a tool with no terminal, it prints the comparison and writes nothing: show the user the result, and run it again with `--yes` only if they agree. Static scores computed after that say `calibrated`. Calibration scales only the default shares, so once every finding carries an estimated share it matters less, and with no default share left it has nothing to scale. Once a usage log exists, plain `npx leanprompt score` gives the measured score; pass `--static` to see the calibrated static one. Method and limits: [docs/calibration.md](../../docs/calibration.md).
|
|
152
|
+
|
|
153
|
+
## Proving each fix
|
|
154
|
+
|
|
155
|
+
Each fix is handed over to `measure-loop`, which runs the rule's "Verify" step as a before and after on the same scenario (the provider's usage fields across two requests, and the kvsig ids that must stay equal) and rescores. The user's `fix now` covers the one diff you showed, nothing more, so ask before each of the other steps:
|
|
156
|
+
|
|
157
|
+
- **The before and after run.** Ask the user to run the scenario, or ask whether you may run it yourself, and say that it sends real requests to the provider, which are billed. Do not start it without a yes.
|
|
158
|
+
- **The stable-head test.** Offer it separately, as its own small diff (the new test file), and add it only after the user says yes. It keeps the fix from quietly coming undone, and it runs offline. Report the proof as one before and after line per field ([presenting.md](presenting.md)), then set `fixed: true` on the finding and run `npx leanprompt score` again. A fix that can change answers (a reorder, a smaller model, less thinking, shorter outputs) needs its answer check to pass first; the rule's "Don't break meaning" says which check (E6 is why).
|
|
159
|
+
|
|
160
|
+
## Sharing a lesson
|
|
161
|
+
|
|
162
|
+
After a fix has a measured before and after, or when a rule misled the user (it did not fit their app, or the fix changed answers), offer once to share what happened as a "lesson learned". It is an offer, not a step: say what it is, and never run it unasked. Only after the user says yes, run `npx leanprompt lesson --rule <id>` (add `--before <an older score.json>` when they kept one). It writes a draft to `.leanprompt/lesson.md` on their machine from the rule id, the target and the current score; it contains no code, paths, prompts or model output, and nothing is sent anywhere.
|
|
163
|
+
|
|
164
|
+
The user reads the exact text, edits it, and opens the issue themselves: the command prints a link to the "Lesson learned" form on GitHub, which carries no text from the draft, and the user pastes the draft into the form. A maintainer reads every submission before it informs a rule, and credit is optional ([THANKYOU.md](../../docs/THANKYOU.md)). If `lesson` reports something to remove (a key, an email, a path, a host name), help the user remove it and run it again; do not paste the removed text anywhere. Do not offer after a static score alone: there is no before and after to share.
|
|
165
|
+
|
|
166
|
+
## What this skill does not do
|
|
167
|
+
|
|
168
|
+
It does not edit code on its own, it does not change answers to save tokens, it does not judge model choice beyond routing obviously small calls, and it does not promise a saving for an app it has not measured. Money is not in the score; when the report shows it, it uses the prices in [providers/](../../providers/) with their checked date. Prompt Lens, an LM Warden view of where reuse broke, is planned; until it ships, the kvsig ids and the provider's usage fields are the tools.
|