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,92 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: LP-GE-01
|
|
3
|
+
title: n samples in one request
|
|
4
|
+
skill: generation-economy
|
|
5
|
+
applies_to: [openai, gemini, deepinfra, vllm, sglang]
|
|
6
|
+
saves: prefill
|
|
7
|
+
severity: medium
|
|
8
|
+
evidence:
|
|
9
|
+
- E12
|
|
10
|
+
- doc: https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create
|
|
11
|
+
checked: 2026-11-26
|
|
12
|
+
- doc: https://aistudio.google.com/api-reference/generate-content
|
|
13
|
+
checked: 2026-11-26
|
|
14
|
+
- doc: https://docs.deepinfra.com/api-reference/chat-completions/openai-chat-completions.md
|
|
15
|
+
checked: 2026-11-26
|
|
16
|
+
---
|
|
17
|
+
## Rule
|
|
18
|
+
When the app needs several samples of the same prompt (self-consistency votes, candidate answers to rank, an evaluation that scores spread), ask for them in one request with the API's sample-count parameter instead of sending the same request again for each sample.
|
|
19
|
+
|
|
20
|
+
## Why
|
|
21
|
+
Every request pays to prefill its prompt. A loop that sends one request per sample prefills the same context once per sample, and the samples gain nothing from it: they differ only in what is generated. A literary question-answering benchmark did exactly this, sending the same request repeatedly to collect several samples instead of one request with `n` samples, and paid prefill once per sample (E12). That case has not been measured before and after yet, so this rule gives no figure for it.
|
|
22
|
+
|
|
23
|
+
One request with a sample count prefills once and decodes the samples from that prefill. Where the parameter exists:
|
|
24
|
+
|
|
25
|
+
- **OpenAI** Chat Completions takes `n`, and bills generated tokens across all choices. Newer models reject an explicit `n`, even `n=1`, and the Responses API has no `n` ([providers/openai.md](../../../providers/openai.md)).
|
|
26
|
+
- **Gemini** takes `candidateCount` in the generation config ([providers/gemini.md](../../../providers/gemini.md)).
|
|
27
|
+
- **DeepInfra** takes `n` on its OpenAI-compatible endpoint, with a small upper limit ([providers/deepinfra.md](../../../providers/deepinfra.md)).
|
|
28
|
+
- **vLLM** and **SGLang** take `n` ([providers/vllm.md](../../../providers/vllm.md), [providers/sglang.md](../../../providers/sglang.md)). That the samples then share one prefill follows from their prefix caches; it is untested here.
|
|
29
|
+
- **Anthropic** has no sample-count parameter on the Messages API, and OpenRouter does not list one ([providers/anthropic.md](../../../providers/anthropic.md), [providers/openrouter.md](../../../providers/openrouter.md)).
|
|
30
|
+
|
|
31
|
+
Where `n` is not available, the repeats can still share a cached prefix: send the first request, wait for it, then send the rest, with a cache mark on the shared prompt where the provider needs one (LP-PC-01). Repeats fired all at once may all start before any cache entry exists. That ordering follows from how prefix caches work; it is untested here.
|
|
32
|
+
|
|
33
|
+
## Detect in code
|
|
34
|
+
Look for a loop or a gather that sends the same request body several times and collects the results.
|
|
35
|
+
|
|
36
|
+
Python:
|
|
37
|
+
```
|
|
38
|
+
rg -n 'for _ in range\(|asyncio\.gather\(|ThreadPoolExecutor|n_samples|num_samples|samples' -g '*.py'
|
|
39
|
+
rg -n 'chat\.completions\.create\(|generate_content\(|messages\.create\(' -g '*.py'
|
|
40
|
+
```
|
|
41
|
+
Shapes: `[client.chat.completions.create(model=M, messages=msgs, temperature=T) for _ in range(k)]`; `await asyncio.gather(*(ask(prompt) for _ in range(k)))`; a majority vote over answers from a repeated call.
|
|
42
|
+
|
|
43
|
+
TS/JS:
|
|
44
|
+
```
|
|
45
|
+
rg -n 'Array\.from\(\{ ?length|Promise\.all\(|for \(let i = 0; i < (k|n|samples)' -g '*.{ts,tsx,js,mjs}'
|
|
46
|
+
```
|
|
47
|
+
Shapes: `await Promise.all(Array.from({ length: k }, () => client.chat.completions.create(body)))`.
|
|
48
|
+
|
|
49
|
+
Go:
|
|
50
|
+
```
|
|
51
|
+
rg -n 'for i := 0; i < (k|n|samples)|errgroup|sync\.WaitGroup' -g '*.go'
|
|
52
|
+
```
|
|
53
|
+
Shapes: a `for` loop or an `errgroup` that calls `client.Chat.Completions.New(ctx, params)` with the same `params` each time.
|
|
54
|
+
|
|
55
|
+
Not a finding: repeats that deliberately change something per sample (a different seed, temperature, model or prompt), and a provider or model without a sample-count parameter (then check the ordering advice above).
|
|
56
|
+
|
|
57
|
+
## Fix
|
|
58
|
+
```python
|
|
59
|
+
# before: one request, and one prefill, per sample
|
|
60
|
+
answers = [
|
|
61
|
+
client.chat.completions.create(model=MODEL, messages=msgs, temperature=TEMP)
|
|
62
|
+
.choices[0].message.content
|
|
63
|
+
for _ in range(N_SAMPLES)
|
|
64
|
+
]
|
|
65
|
+
|
|
66
|
+
# after: one request, N_SAMPLES choices
|
|
67
|
+
resp = client.chat.completions.create(model=MODEL, messages=msgs, temperature=TEMP, n=N_SAMPLES)
|
|
68
|
+
answers = [c.message.content for c in resp.choices]
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
// Gemini: candidateCount in the generation config
|
|
73
|
+
const resp = await ai.models.generateContent({
|
|
74
|
+
model: MODEL,
|
|
75
|
+
contents,
|
|
76
|
+
config: { temperature: TEMP, candidateCount: N_SAMPLES },
|
|
77
|
+
});
|
|
78
|
+
const answers = resp.candidates?.map((c) => c.content?.parts?.[0]?.text ?? "") ?? [];
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Keep the provider's upper limit on the count in mind; split into a few requests when it is lower than the number of samples needed.
|
|
82
|
+
|
|
83
|
+
## Don't break meaning
|
|
84
|
+
The samples must stay independent draws from the same settings: keep the same temperature and other sampling parameters as the repeated calls. If the repeats used a different seed or temperature on purpose, `n` is not the same experiment; keep them, and use the ordering advice instead. At temperature zero, several samples are pointless in either form. Code that reads `choices[0]` only must be changed to read every choice.
|
|
85
|
+
|
|
86
|
+
## Verify
|
|
87
|
+
(a) Provider usage: before, the app makes one call per sample, each reporting the full prompt in `prompt_tokens`; after, one call reports the prompt once, and `completion_tokens` (OpenAI), or `candidatesTokenCount` across all candidates (Gemini), covers every sample.
|
|
88
|
+
|
|
89
|
+
(b) leanprompt usage record: before, the log holds several records per question with equal `ids.nodes` and equal `params`, sent close together; after, one record per question whose `output_tokens` covers all samples. kvsig: the repeated requests have equal exact `nodes[i]` for the last message, which is how the audit finds them.
|
|
90
|
+
|
|
91
|
+
## Waste signal
|
|
92
|
+
Measured: the score's generation waste counts output tokens on calls that were repeated identically (same ids, same `params`); repeated sampling calls count there, and after the fix they are one call. Static: severity medium for a loop or gather that sends one unchanged request body several times to a provider that supports a sample count; low where the provider has none.
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: LP-GE-02
|
|
3
|
+
title: Batch independent questions about one context
|
|
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://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
|
+
---
|
|
14
|
+
## Rule
|
|
15
|
+
When the app asks several questions about the same context and no answer depends on another, ask them in one call with a structured output that has one field per question, and keep it only if the answer check passes.
|
|
16
|
+
|
|
17
|
+
## Why
|
|
18
|
+
Each separate call sends the context again: a document with five extraction questions is five prefills of the document, five copies of the instructions, and five answer preambles. A prefix cache makes the repeated context cheaper but not free (cached tokens are still billed at a reduced rate, and only above the provider's minimum and within its lifetime; see LP-PC-01 and the cache rows in [providers/anthropic.md](../../../providers/anthropic.md), [providers/openai.md](../../../providers/openai.md), [providers/gemini.md](../../../providers/gemini.md), [providers/deepinfra.md](../../../providers/deepinfra.md)). One call with one field per question prefills the context once.
|
|
19
|
+
|
|
20
|
+
A structured output keeps the answers apart and parseable. Structured output is supported by every provider in the tables (LP-GE-10): OpenAI, Anthropic, Gemini, OpenRouter (on models with the capability), DeepInfra, vLLM and SGLang ([providers/openrouter.md](../../../providers/openrouter.md), [providers/vllm.md](../../../providers/vllm.md), [providers/sglang.md](../../../providers/sglang.md)).
|
|
21
|
+
|
|
22
|
+
The saving has a price that this rule makes you check: one model call answering many questions can answer some of them worse than a call that sees one question, and one truncated output loses every answer at once. Untested here: the cited pages document structured output, not this trade-off.
|
|
23
|
+
|
|
24
|
+
## Detect in code
|
|
25
|
+
Look for a loop over questions, fields or checks that sends the same context each time.
|
|
26
|
+
|
|
27
|
+
Python:
|
|
28
|
+
```
|
|
29
|
+
rg -n 'for (q|question|field|check) in|QUESTIONS|FIELDS' -g '*.py'
|
|
30
|
+
```
|
|
31
|
+
Shapes: `for field in FIELDS: ask(f"{doc}\n\nWhat is the {field}?")`; `[classify(doc, label) for label in LABELS]` with one yes/no call per label; `asyncio.gather(*(ask(doc, q) for q in questions))`.
|
|
32
|
+
|
|
33
|
+
TS/JS:
|
|
34
|
+
```
|
|
35
|
+
rg -n 'questions\.map\(|fields\.map\(|for \(const (q|field) of' -g '*.{ts,tsx,js,mjs}'
|
|
36
|
+
```
|
|
37
|
+
Shapes: `await Promise.all(questions.map((q) => ask(doc, q)))`.
|
|
38
|
+
|
|
39
|
+
Go:
|
|
40
|
+
```
|
|
41
|
+
rg -n 'for _, (q|field|question) := range' -g '*.go'
|
|
42
|
+
```
|
|
43
|
+
Shapes: a loop that builds a prompt from the same `doc` and a different question and calls the model each time.
|
|
44
|
+
|
|
45
|
+
Not a finding: questions where a later one needs an earlier answer (a chain), and questions that need different tools, models or settings.
|
|
46
|
+
|
|
47
|
+
## Fix
|
|
48
|
+
```python
|
|
49
|
+
# before: one call, and one prefill of the document, per question
|
|
50
|
+
answers = {f: ask(f"{DOC}\n\nQuestion: What is the {f}?") for f in FIELDS}
|
|
51
|
+
|
|
52
|
+
# after: one call, one field per question
|
|
53
|
+
schema = {
|
|
54
|
+
"type": "object",
|
|
55
|
+
"properties": {f: {"type": ["string", "null"]} for f in FIELDS},
|
|
56
|
+
"required": FIELDS,
|
|
57
|
+
"additionalProperties": False,
|
|
58
|
+
}
|
|
59
|
+
resp = client.responses.create(
|
|
60
|
+
model=MODEL,
|
|
61
|
+
input=f"{DOC}\n\nAnswer each field from the document. Use null when the document does not say.",
|
|
62
|
+
text={"format": {"type": "json_schema", "name": "fields", "strict": True, "schema": schema}},
|
|
63
|
+
max_output_tokens=OUTPUT_LIMIT, # sized for all fields together (LP-GE-03)
|
|
64
|
+
)
|
|
65
|
+
answers = json.loads(resp.output_text)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Group a small number of related questions per call rather than every question at once, and size the output limit for all answers together.
|
|
69
|
+
|
|
70
|
+
## Don't break meaning
|
|
71
|
+
Batching changes what the model sees in one call, so it can change answers. Each question must still be answerable on its own: keep its wording, allow "not stated" (`null`) for each field so the model does not invent an answer to fill it, and never batch questions whose answers depend on each other.
|
|
72
|
+
|
|
73
|
+
Run an answer check before keeping the change: a fixed set of synthetic inputs (documents with known answers), run through the old form (one call per question) and the new form (one batched call), compare the outputs field by field (exact match or schema match), and record pass/fail per field. Keep the batched form only if it passes on at least as many fields as the old form; otherwise make the groups smaller or keep separate calls.
|
|
74
|
+
|
|
75
|
+
## Verify
|
|
76
|
+
(a) Provider usage: before, one call per question, each with the context in `prompt_tokens` (or `cached_tokens` / `cache_read_input_tokens` when the cache hits); after, one call with the context once and `output_tokens` / `completion_tokens` for all answers. Check `finish_reason` (`stop_reason` on Anthropic) is never `length` / `max_tokens`.
|
|
77
|
+
|
|
78
|
+
(b) leanprompt usage record: before, several records per document that share `ids.nodes` up to the context and differ only in the last message; after, one record per document, `finish: "length"` absent and `flags.parse_failed` absent.
|
|
79
|
+
|
|
80
|
+
## Waste signal
|
|
81
|
+
Measured: not counted directly in the score (separate questions are not identical calls); it shows as fewer calls and fewer prompt tokens per document in a before/after run (the `measure-loop` skill). Static: severity medium for a loop that sends the same long context with a different question each time and does not chain the answers.
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: LP-GE-03
|
|
3
|
+
title: Output and thinking budgets that fit the task
|
|
4
|
+
skill: generation-economy
|
|
5
|
+
applies_to: [anthropic, openai, gemini, openrouter, deepinfra, vllm, sglang, any]
|
|
6
|
+
saves: generation
|
|
7
|
+
severity: high
|
|
8
|
+
evidence:
|
|
9
|
+
- E11
|
|
10
|
+
- doc: https://developers.openai.com/api/docs/guides/reasoning
|
|
11
|
+
checked: 2026-11-26
|
|
12
|
+
- doc: https://platform.claude.com/docs/en/build-with-claude/extended-thinking
|
|
13
|
+
checked: 2026-11-26
|
|
14
|
+
- doc: https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons
|
|
15
|
+
checked: 2026-11-26
|
|
16
|
+
- doc: https://docs.vllm.ai/en/latest/features/reasoning_outputs.html
|
|
17
|
+
checked: 2026-11-26
|
|
18
|
+
---
|
|
19
|
+
## Rule
|
|
20
|
+
Set an output limit and a thinking or effort level on every call, sized from the outputs the task really produces: high enough that a correct answer is never cut off, low enough that a runaway output stops.
|
|
21
|
+
|
|
22
|
+
## Why
|
|
23
|
+
Output tokens are the slow and expensive part of a call, and three mistakes waste them.
|
|
24
|
+
|
|
25
|
+
- **No limit, or a limit far above the task.** A reasoning model with thinking on by default and no output limit can think until it reaches the token ceiling and return no answer at all: every token is billed and the app gets nothing. Thinking and reasoning tokens count toward the output limit and are billed as output on Anthropic and OpenAI ([models/anthropic-thinking.md](../../../models/anthropic-thinking.md), [models/openai-reasoning.md](../../../models/openai-reasoning.md)); OpenAI notes that hitting the limit can end a response as `incomplete` before any visible output. Self-hosted Qwen hybrid models think unless `enable_thinking` is set to false, and one template defaults to its highest effort ([models/qwen.md](../../../models/qwen.md)).
|
|
26
|
+
- **A limit below the task.** The answer is cut off (`finish_reason: "length"`, `stop_reason: "max_tokens"`, `finishReason: "MAX_TOKENS"`), the app throws it away and asks again, often with the same limit (LP-GE-05). The truncated tokens were paid for and are lost.
|
|
27
|
+
- **Reasoning twice.** The prompt or the schema asks for a written reasoning, rationale or explanation field while the model's own thinking is also on. The model reasons in its thinking and again in the visible answer, and both count against one output limit, so outputs grow and truncations become more likely (LP-GE-05). This follows from thinking tokens counting toward the output limit; not yet measured here. Keep one: thinking on and no reasoning field, or thinking off and a reasoning field before the answer (LP-GE-10).
|
|
28
|
+
|
|
29
|
+
Thinking effort is the larger lever. Pick the effort or budget per kind of task (a title needs none, a multi-step plan may need a lot), and keep it fixed within a session, since changing it changes the cached prefix (LP-PC-09). Do not save thinking tokens by stripping earlier reasoning from the history: in agent loops that produced about 3x more generation (E11).
|
|
30
|
+
|
|
31
|
+
Where the controls are: OpenAI `max_output_tokens` / `max_completion_tokens` and `reasoning_effort` ([providers/openai.md](../../../providers/openai.md)); Anthropic `max_tokens` and adaptive thinking with `effort` ([providers/anthropic.md](../../../providers/anthropic.md)); Gemini `maxOutputTokens`, `thinkingBudget`, `thinkingLevel` ([providers/gemini.md](../../../providers/gemini.md)); OpenRouter `max_tokens`, which covers reasoning and visible output together on most providers ([providers/openrouter.md](../../../providers/openrouter.md)); vLLM and SGLang `max_tokens` plus the model's template kwargs ([providers/vllm.md](../../../providers/vllm.md), [providers/sglang.md](../../../providers/sglang.md)).
|
|
32
|
+
|
|
33
|
+
## Detect in code
|
|
34
|
+
Python:
|
|
35
|
+
```
|
|
36
|
+
rg -n 'chat\.completions\.create\(|responses\.create\(|messages\.create\(|generate_content\(' -g '*.py'
|
|
37
|
+
rg -n 'max_tokens|max_completion_tokens|max_output_tokens|reasoning_effort|budget_tokens|effort|enable_thinking|thinking_budget' -g '*.py'
|
|
38
|
+
```
|
|
39
|
+
Shapes: a call to a reasoning or hybrid-thinking model with no output limit; a prompt or schema that asks for a `"reasoning"`, `"rationale"` or `"explanation"` field, or says "think step by step", on a call whose model thinking is on (reasoning twice; for a self-hosted Qwen model, thinking is on unless `enable_thinking` is false in the request or in the server's `--default-chat-template-kwargs`, [vLLM reasoning outputs](https://docs.vllm.ai/en/latest/features/reasoning_outputs.html), checked 2026-11-26); `max_tokens=MODEL_MAX` (the model's maximum used as a default for every call); one effort level, usually the highest, for every call including titles and labels; a small fixed limit on a call that produces long outputs (summaries, code).
|
|
40
|
+
|
|
41
|
+
TS/JS:
|
|
42
|
+
```
|
|
43
|
+
rg -n 'max_tokens|maxTokens|max_completion_tokens|max_output_tokens|maxOutputTokens|reasoning_effort|reasoningEffort|budget_tokens|thinkingBudget' -g '*.{ts,tsx,js,mjs}'
|
|
44
|
+
```
|
|
45
|
+
Shapes: Vercel AI SDK `generateText({ model, prompt })` with no `maxOutputTokens`; `reasoningEffort: "high"` in a shared default options object.
|
|
46
|
+
|
|
47
|
+
Go:
|
|
48
|
+
```
|
|
49
|
+
rg -n 'MaxTokens|MaxCompletionTokens|MaxOutputTokens|ReasoningEffort|BudgetTokens' -g '*.go'
|
|
50
|
+
```
|
|
51
|
+
Shapes: `MaxTokens: 0` or unset on a reasoning model; one package-level params value reused for every kind of call.
|
|
52
|
+
|
|
53
|
+
## Fix
|
|
54
|
+
Measure first: log `output_tokens` per kind of call for a few days, or run the answer-check inputs, then set each limit above the longest correct output seen, with headroom, and pick the lowest effort that passes the answer check.
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
# before: every call, from titles to plans, at the model maximum and the highest effort
|
|
58
|
+
resp = client.responses.create(model=MODEL, input=msgs, reasoning={"effort": "high"})
|
|
59
|
+
|
|
60
|
+
# after: budgets per kind of task, from measured outputs
|
|
61
|
+
BUDGETS = {
|
|
62
|
+
"title": {"max_output_tokens": TITLE_LIMIT, "reasoning": {"effort": "low"}},
|
|
63
|
+
"answer": {"max_output_tokens": ANSWER_LIMIT, "reasoning": {"effort": "medium"}},
|
|
64
|
+
"plan": {"max_output_tokens": PLAN_LIMIT, "reasoning": {"effort": "high"}},
|
|
65
|
+
}
|
|
66
|
+
resp = client.responses.create(model=MODEL, input=msgs, **BUDGETS[kind])
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Self-hosted Qwen, where a call needs no thinking:
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
extra_body={"chat_template_kwargs": {"enable_thinking": False}} # fixed for the whole session (LP-PC-09)
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
The allowed effort values differ by model; take them from the model tables, not from memory.
|
|
76
|
+
|
|
77
|
+
## Don't break meaning
|
|
78
|
+
Less thinking and shorter outputs can change answers. Lower an effort level or a limit only after an answer check on a fixed set of inputs passes with the new value, and never set a limit below the longest correct answer in that set. When quality is the priority, keep thinking on and raise limits until no correct answer is truncated; caching still applies. Do not change thinking per turn inside a cached session (LP-PC-09). Before dropping a reasoning field to end reasoning twice, check whether the app reads or shows that field; if it does, keep the field and turn thinking off instead, or show the thinking where the server returns it separately. Either way, run the answer check.
|
|
79
|
+
|
|
80
|
+
## Verify
|
|
81
|
+
(a) Provider usage: the share of calls ending with `finish_reason: "length"` (Chat Completions), `status: "incomplete"` (Responses), `stop_reason: "max_tokens"` (Anthropic) or `finishReason: "MAX_TOKENS"` (Gemini) falls to zero on calls that should finish; `output_tokens` per kind of call falls where the limit or effort was above the task. Thinking tokens show in `usage.output_tokens_details.thinking_tokens` (Anthropic) or `thoughtsTokenCount` (Gemini).
|
|
82
|
+
|
|
83
|
+
(b) leanprompt usage record: no records with `finish: "length"` for that kind of call, and the spread of `output_tokens` sits below the limit. Records with `finish: "length"` followed by a record with `flags.retry_of` pointing at them are the waste this rule removes.
|
|
84
|
+
|
|
85
|
+
## Waste signal
|
|
86
|
+
Measured: output tokens of calls with `finish: "length"` that were retried count as generation waste; output spent on a runaway call with no answer shows as `finish: "length"` too. Static: severity high for a reasoning or thinking model called with no output limit, medium for one effort level on every kind of call, low for a fixed limit far above the measured outputs. A limit below the task: medium for a fixed limit below outputs the task produces (truncations in the log, or a limit smaller than the output the task asks for); when those truncations are retried or re-run unchanged, that is also a high LP-GE-05 finding. Reasoning twice: medium.
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: LP-GE-04
|
|
3
|
+
title: Stream long outputs; timeouts that match generation time
|
|
4
|
+
skill: generation-economy
|
|
5
|
+
applies_to: [anthropic, openai, gemini, openrouter, deepinfra, vllm, sglang, any]
|
|
6
|
+
saves: both
|
|
7
|
+
severity: high
|
|
8
|
+
evidence:
|
|
9
|
+
- doc: https://openrouter.ai/docs/api/reference/streaming
|
|
10
|
+
checked: 2026-11-26
|
|
11
|
+
- doc: https://platform.claude.com/docs/en/api/errors
|
|
12
|
+
checked: 2026-11-26
|
|
13
|
+
- doc: https://github.com/openai/openai-python/blob/main/README.md
|
|
14
|
+
checked: 2026-11-26
|
|
15
|
+
- doc: runtimes/http-clients.md
|
|
16
|
+
checked: 2026-11-26
|
|
17
|
+
---
|
|
18
|
+
## Rule
|
|
19
|
+
Stream any call whose output can be long, and set timeouts from the expected generation time (a time to first token, then a gap between tokens) instead of a short total timeout that gives up on, and then repeats, a request the server is still generating.
|
|
20
|
+
|
|
21
|
+
## Why
|
|
22
|
+
A client timeout stops the client from waiting; it does not stop the server from generating. OpenRouter documents this for its routes: "For non-streaming requests or unsupported providers, the model will continue processing and you will be billed for the complete response" ([providers/openrouter.md](../../../providers/openrouter.md)). For direct calls the providers' pages read here do not say either way, so treat the abandoned answer as still running and billed.
|
|
23
|
+
|
|
24
|
+
A retry after that timeout pays for the prompt again (prefill) while the abandoned answer is still being generated and billed (generation), and if the timeout is shorter than the generation time, the retry times out the same way. Client libraries make this easy to hit: the OpenAI Python SDK retries a timed-out request twice by default ([providers/openai.md](../../../providers/openai.md)), so one short timeout can pay for three generations and deliver none.
|
|
25
|
+
|
|
26
|
+
A call that sets no timeout of its own gets the HTTP client's default, and the defaults differ by runtime, from a wait shorter than many generations to no limit at all. Look up your client's default in [runtimes/http-clients.md](../../../runtimes/http-clients.md) (Node's built-in `fetch`, Python `httpx` and `requests`, Go `net/http`), not from memory. A non-streaming completion usually sends nothing, headers included, until the whole answer is ready, so a default wait for headers or for the first byte applies to the whole generation, and when it fires the client gives up while the server goes on generating. Not yet measured here.
|
|
27
|
+
|
|
28
|
+
A default that is too short for the generation behaves like a short explicit timeout, and the failure is often filed as retryable and sent again (LP-GE-05). A missing timeout repeats nothing, but a stalled call ties up the worker and hides the failure.
|
|
29
|
+
|
|
30
|
+
Streaming fixes the measurement problem: the first token arrives early, so the client can tell "slow but working" from "dead" with an idle timeout instead of a total one. It also allows stopping early on purpose; on OpenRouter, aborting a stream stops processing and billing on the providers it lists as supported (OpenAI, Anthropic, DeepInfra and others; not Google) ([providers/openrouter.md](../../../providers/openrouter.md)). Anthropic advises streaming or the batch API for long requests, and its SDK checks that a non-streaming request is not expected to exceed its timeout ([providers/anthropic.md](../../../providers/anthropic.md)). Whether a client disconnect stops generation on a direct Gemini, DeepInfra, vLLM or SGLang call is not stated on the pages read; through OpenRouter, Google does not stop on abort ([providers/gemini.md](../../../providers/gemini.md), [providers/deepinfra.md](../../../providers/deepinfra.md), [providers/vllm.md](../../../providers/vllm.md), [providers/sglang.md](../../../providers/sglang.md)).
|
|
31
|
+
|
|
32
|
+
## Detect in code
|
|
33
|
+
Python:
|
|
34
|
+
```
|
|
35
|
+
rg -n 'timeout\s*=|httpx\.Timeout\(|max_retries\s*=|tenacity|backoff\.on_exception|@retry' -g '*.py'
|
|
36
|
+
rg -n 'stream\s*=\s*True|\.stream\(' -g '*.py'
|
|
37
|
+
```
|
|
38
|
+
Shapes: `OpenAI(timeout=SHORT)` or `requests.post(..., timeout=SHORT)` on calls with large output limits; a retry decorator around a non-streaming call that retries on `Timeout`; SDK retries left on and an app-level retry loop around them.
|
|
39
|
+
|
|
40
|
+
TS/JS:
|
|
41
|
+
```
|
|
42
|
+
rg -n 'timeout:|AbortSignal\.timeout\(|maxRetries|p-retry|stream:\s*true' -g '*.{ts,tsx,js,mjs}'
|
|
43
|
+
```
|
|
44
|
+
Shapes: `AbortSignal.timeout(SHORT)` on a `fetch` to a completions endpoint; `new OpenAI({ timeout: SHORT })` with default retries.
|
|
45
|
+
|
|
46
|
+
Go:
|
|
47
|
+
```
|
|
48
|
+
rg -n 'http\.Client\{[^}]*Timeout|context\.WithTimeout\(|WithRequestTimeout|WithMaxRetries' -g '*.go'
|
|
49
|
+
```
|
|
50
|
+
Shapes: `http.Client{Timeout: short}` shared by LLM calls; `context.WithTimeout(ctx, short)` around a non-streaming `Chat.Completions.New`.
|
|
51
|
+
|
|
52
|
+
No timeout set at all (the runtime default applies):
|
|
53
|
+
```
|
|
54
|
+
rg -n 'requests\.(post|request)\(|httpx\.(post|request|Client|AsyncClient)\(' -g '*.py'
|
|
55
|
+
rg -n 'fetch\(|signal:|dispatcher:|setGlobalDispatcher|headersTimeout|bodyTimeout' -g '*.{ts,tsx,js,mjs}'
|
|
56
|
+
rg -n 'http\.DefaultClient|http\.(Post|Get)\(|&?http\.Client\{\s*\}' -g '*.go'
|
|
57
|
+
```
|
|
58
|
+
Shape: a non-streaming completion call with a large output limit and no timeout of its own, neither in its arguments nor on its client (a `fetch` with no `signal` or `dispatcher`, `requests.post(...)` or `httpx.post(...)` with no `timeout=`, `http.Post` or `&http.Client{}` with no `Timeout`). Look up the client's default timeouts in [runtimes/http-clients.md](../../../runtimes/http-clients.md) and compare them with the longest generation the call can produce; then check what the app does when the default fires (a generic error that a retry path or a person sends again is LP-GE-05).
|
|
59
|
+
|
|
60
|
+
Not a finding: a short timeout on a call whose output limit is small enough to finish within it.
|
|
61
|
+
|
|
62
|
+
## Fix
|
|
63
|
+
```python
|
|
64
|
+
# before: a short total timeout, retried, on a long non-streaming answer
|
|
65
|
+
client = OpenAI(timeout=SHORT_TIMEOUT_S)
|
|
66
|
+
resp = client.chat.completions.create(model=MODEL, messages=msgs, max_completion_tokens=LONG_LIMIT)
|
|
67
|
+
|
|
68
|
+
# after: stream; time out on silence, not on total length; one retry layer
|
|
69
|
+
client = OpenAI(timeout=httpx.Timeout(connect=CONNECT_S, read=IDLE_S, write=WRITE_S, pool=POOL_S), max_retries=0)
|
|
70
|
+
stream = client.chat.completions.create(
|
|
71
|
+
model=MODEL, messages=msgs, max_completion_tokens=LONG_LIMIT,
|
|
72
|
+
stream=True, stream_options={"include_usage": True},
|
|
73
|
+
)
|
|
74
|
+
parts, usage = [], None
|
|
75
|
+
for chunk in stream:
|
|
76
|
+
if chunk.choices and chunk.choices[0].delta.content:
|
|
77
|
+
parts.append(chunk.choices[0].delta.content)
|
|
78
|
+
if chunk.usage:
|
|
79
|
+
usage = chunk.usage
|
|
80
|
+
text = "".join(parts)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
For a raw `fetch` in Node, the same change: stream, and abort only when no chunk arrives for a while.
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
// before: non-streaming, no timeout of its own, so undici's default header wait applies
|
|
87
|
+
const res = await fetch(`${BASE}/chat/completions`, { method: "POST", headers, body: JSON.stringify({ model: MODEL, messages, max_tokens: LONG_LIMIT }) });
|
|
88
|
+
|
|
89
|
+
// after: stream; an idle timer that restarts on every chunk
|
|
90
|
+
const ctrl = new AbortController();
|
|
91
|
+
let idle = setTimeout(() => ctrl.abort(), IDLE_MS);
|
|
92
|
+
const res = await fetch(`${BASE}/chat/completions`, {
|
|
93
|
+
method: "POST", headers, signal: ctrl.signal,
|
|
94
|
+
body: JSON.stringify({ model: MODEL, messages, max_tokens: LONG_LIMIT, stream: true, stream_options: { include_usage: true } }),
|
|
95
|
+
});
|
|
96
|
+
for await (const chunk of res.body!) {
|
|
97
|
+
clearTimeout(idle);
|
|
98
|
+
idle = setTimeout(() => ctrl.abort(), IDLE_MS);
|
|
99
|
+
parser.feed(chunk); // collect deltas and the final usage chunk
|
|
100
|
+
}
|
|
101
|
+
clearTimeout(idle);
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
A Node call that must stay non-streaming passes a `dispatcher` (an undici `Agent` with `headersTimeout` and `bodyTimeout` set above the longest generation time) instead of relying on the default ([runtimes/http-clients.md](../../../runtimes/http-clients.md)).
|
|
105
|
+
|
|
106
|
+
With httpx, `read` is the longest wait between two received chunks, so it acts as an idle timeout on a stream. If a call must stay non-streaming, set its total timeout above the output limit divided by the slowest decode rate you observe, and keep one retry layer (the SDK's or the app's, not both).
|
|
107
|
+
|
|
108
|
+
## Don't break meaning
|
|
109
|
+
Streaming does not change the answer, but the code that assembles it must: collect every delta, including tool-call argument deltas, read the final usage chunk (`stream_options.include_usage` on OpenAI), and treat a stream that ends with an error event as failed, not as a short answer. On OpenRouter a cancelled stream usually gets no cache discount because the final usage never arrives ([providers/openrouter.md](../../../providers/openrouter.md)), so do not cancel streams to save money unless the answer is no longer needed.
|
|
110
|
+
|
|
111
|
+
## Verify
|
|
112
|
+
(a) Provider usage: compare the provider's request count and `output_tokens` / `completion_tokens` (billing page, OpenRouter's `/api/v1/generation`) with the calls the app saw complete. Timed-out calls appear on the provider side with full output although the app received nothing; after the fix the two counts match and `finish_reason` is `stop` on the calls that completed. For a call with no timeout of its own, write down the default that applies ([runtimes/http-clients.md](../../../runtimes/http-clients.md)) next to the longest generation time seen; a generation longer than the default shows as an app-side timeout while the provider or server logs a completed request.
|
|
113
|
+
|
|
114
|
+
(b) leanprompt usage record: before, records with `finish: "error"` followed by a record with `flags.retry_of` pointing at them and equal `params`; after, none for timeouts. The stream's final usage gives `output_tokens` for each record.
|
|
115
|
+
|
|
116
|
+
## Waste signal
|
|
117
|
+
Measured: output tokens of a call repeated after a timeout count as generation waste (a retry of an identical call). Static: severity high for a total timeout shorter than the expected generation time on a non-streaming call with a large output limit, or for stacked retry layers around one; the same when no timeout is set and the client's default ([runtimes/http-clients.md](../../../runtimes/http-clients.md)) is shorter than that generation time. Medium for a long-output call that does not stream, and for one with no timeout at all where the runtime has none (a hung worker, not a repeated generation).
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: LP-GE-05
|
|
3
|
+
title: Retry only retryable errors; never retry a truncation unchanged
|
|
4
|
+
skill: generation-economy
|
|
5
|
+
applies_to: [anthropic, openai, gemini, openrouter, deepinfra, vllm, sglang, any]
|
|
6
|
+
saves: both
|
|
7
|
+
severity: high
|
|
8
|
+
evidence:
|
|
9
|
+
- doc: https://platform.claude.com/docs/en/api/errors
|
|
10
|
+
checked: 2026-11-26
|
|
11
|
+
- doc: https://developers.openai.com/api/docs/guides/error-codes
|
|
12
|
+
checked: 2026-11-26
|
|
13
|
+
- doc: https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons
|
|
14
|
+
checked: 2026-11-26
|
|
15
|
+
---
|
|
16
|
+
## Rule
|
|
17
|
+
Retry a failed call only when the error says a retry can succeed (rate limits, overload, transient server errors), with backoff and a limit; never resend a cut-off answer with the same output limit.
|
|
18
|
+
|
|
19
|
+
## Why
|
|
20
|
+
A retry pays for the whole prompt again and for whatever is generated again. That is worth it for a transient failure and pure waste for one that will repeat.
|
|
21
|
+
|
|
22
|
+
- **Retryable:** rate limits that clear, overload (OpenAI 503, Anthropic 529) and transient server errors. Both providers say to follow `Retry-After` (and on Anthropic `x-should-retry`) and to back off ([providers/openai.md](../../../providers/openai.md), [providers/anthropic.md](../../../providers/anthropic.md)).
|
|
23
|
+
- **Not retryable:** invalid requests (400), authentication (401, 403), a request too large (413), and a 429 caused by exhausted credit or a spend cap, which keeps failing until access resumes ([providers/openai.md](../../../providers/openai.md), [providers/anthropic.md](../../../providers/anthropic.md)).
|
|
24
|
+
- **A truncation is not an error.** The call succeeded and stopped at the output limit: `finish_reason: "length"`, `stop_reason: "max_tokens"`, `finishReason: "MAX_TOKENS"` ([providers/gemini.md](../../../providers/gemini.md)). Sent again unchanged, it usually stops at the same limit, and the tokens of both attempts are billed. A reasoning model that spent the whole limit thinking does the same on every attempt. Anthropic's advice for this stop reason is to raise `max_tokens` or continue the response.
|
|
25
|
+
|
|
26
|
+
Retry layers multiply: the OpenAI and Anthropic SDKs each retry by default ([providers/openai.md](../../../providers/openai.md), [providers/anthropic.md](../../../providers/anthropic.md)), so an app-level retry loop around them multiplies the attempts.
|
|
27
|
+
|
|
28
|
+
## Detect in code
|
|
29
|
+
Python:
|
|
30
|
+
```
|
|
31
|
+
rg -n '@retry|tenacity|backoff\.on_exception|except Exception|while True|for attempt in range\(' -g '*.py'
|
|
32
|
+
rg -n 'finish_reason|stop_reason|finishReason|incomplete' -g '*.py'
|
|
33
|
+
```
|
|
34
|
+
Shapes: `@retry(stop=stop_after_attempt(K))` with no exception filter; `except Exception: continue` inside a loop around the call; `if resp.choices[0].finish_reason == "length": return call(same_args)`; code that ignores the finish reason and retries when parsing fails on a truncated answer; a client error raised for an empty answer or empty thinking (often a truncation inside the thinking) that a generic error classifier files as retryable.
|
|
35
|
+
|
|
36
|
+
TS/JS:
|
|
37
|
+
```
|
|
38
|
+
rg -n 'p-retry|retry\(|catch \(e\)|maxRetries|finish_reason|stop_reason' -g '*.{ts,tsx,js,mjs}'
|
|
39
|
+
```
|
|
40
|
+
Shapes: `pRetry(() => call(body), { retries: K })` with no `shouldRetry`; `catch { return call(body) }`.
|
|
41
|
+
|
|
42
|
+
Go:
|
|
43
|
+
```
|
|
44
|
+
rg -n 'for attempt := |backoff\.|retry\.|FinishReason|StopReason' -g '*.go'
|
|
45
|
+
```
|
|
46
|
+
Shapes: a retry loop that treats every `err != nil` as retryable; a loop that resends when `FinishReason == "length"` with the same params.
|
|
47
|
+
|
|
48
|
+
## Fix
|
|
49
|
+
```python
|
|
50
|
+
RETRYABLE = {408, 409, 429, 500, 503, 504, 529} # from the tables; check `x-should-retry` where sent
|
|
51
|
+
|
|
52
|
+
def call_with_policy(body):
|
|
53
|
+
for attempt in range(MAX_ATTEMPTS):
|
|
54
|
+
try:
|
|
55
|
+
resp = client.chat.completions.create(**body)
|
|
56
|
+
except APIStatusError as e:
|
|
57
|
+
if e.status_code not in RETRYABLE or is_quota_error(e): # spend cap, no credit: stop
|
|
58
|
+
raise
|
|
59
|
+
sleep(retry_after(e) or backoff(attempt))
|
|
60
|
+
continue
|
|
61
|
+
if resp.choices[0].finish_reason == "length":
|
|
62
|
+
if body["max_completion_tokens"] >= HARD_CEILING:
|
|
63
|
+
raise Truncated(resp) # fix the budget (LP-GE-03), do not loop
|
|
64
|
+
body = {**body, "max_completion_tokens": min(body["max_completion_tokens"] * GROWTH, HARD_CEILING)}
|
|
65
|
+
continue # changed, so it may finish this time
|
|
66
|
+
return resp
|
|
67
|
+
raise GaveUp()
|
|
68
|
+
|
|
69
|
+
client = OpenAI(max_retries=0) # one retry layer: this one
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
On Anthropic, the stop-reason page gives continuing the response as the alternative to a larger limit; follow that page for how. For a reasoning model that never got to the answer, lower the effort or raise the limit; resending the same request does neither.
|
|
73
|
+
|
|
74
|
+
## Don't break meaning
|
|
75
|
+
A retry policy changes which calls get a second chance, not what they say. Raising the limit on a retry must not change anything else in the request (same prompt, same settings). A continued answer must be joined exactly where it stopped, with no text added between the parts. Do not turn a refusal, a content filter stop or a schema error into a retry.
|
|
76
|
+
|
|
77
|
+
## Verify
|
|
78
|
+
(a) Provider usage: the retried calls' `finish_reason` / `stop_reason` and status codes. Before, retries follow 400s, quota 429s or `length` stops with unchanged limits; after, retries follow only retryable codes, and each retry after a `length` stop has a larger limit. Total `output_tokens` per completed task falls.
|
|
79
|
+
|
|
80
|
+
(b) leanprompt usage record: a record with `flags.retry_of` whose original has `finish: "length"` and an equal `params` hash is a truncation retried unchanged; after the fix there are none. Records with `finish: "error"` followed by retries should match retryable errors only.
|
|
81
|
+
|
|
82
|
+
## Waste signal
|
|
83
|
+
Measured: output tokens spent on calls retried after a truncation count as generation waste; so do repeated identical calls after a failure. Static: severity high for a retry on `length` with unchanged parameters or a retry on every exception. A truncation filed under a generic "retryable" or "failed, try again" status counts as the same finding when the re-run sends the same parameters: high when a job, a queue or a loop re-runs it, medium when only a person re-runs it on demand. Medium for stacked retry layers or a missing backoff.
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: LP-GE-06
|
|
3
|
+
title: Cache exact responses for deterministic requests
|
|
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/prompt-caching
|
|
12
|
+
checked: 2026-11-26
|
|
13
|
+
---
|
|
14
|
+
## Rule
|
|
15
|
+
When the app sends the same request again and wants the same answer (classifying a label set, extracting fields from a document it has seen, summarising an unchanged file), store the response in the app keyed by the exact request, and serve it from there instead of calling the model.
|
|
16
|
+
|
|
17
|
+
## Why
|
|
18
|
+
A provider's prompt cache only makes the prompt cheaper. The repeated call still pays for cached input at a reduced rate, pays the full price for every output token, and waits for the model to generate again ([providers/anthropic.md](../../../providers/anthropic.md), [providers/openai.md](../../../providers/openai.md), [providers/gemini.md](../../../providers/gemini.md), [providers/deepinfra.md](../../../providers/deepinfra.md)). A self-hosted engine reuses the prefix but still spends the decode time ([providers/vllm.md](../../../providers/vllm.md), [providers/sglang.md](../../../providers/sglang.md)). None of the provider tables lists a response cache; it belongs in the app, and OpenRouter forwards each call to a provider like any other ([providers/openrouter.md](../../../providers/openrouter.md)).
|
|
19
|
+
|
|
20
|
+
The shapes: a pipeline that re-runs over every document each night although most did not change; a page that classifies the same product text on every view; a retry wrapper that resends a request that already succeeded; tests and evaluation runs that call the live model with fixed inputs.
|
|
21
|
+
|
|
22
|
+
## Detect in code
|
|
23
|
+
Python:
|
|
24
|
+
```
|
|
25
|
+
rg -n 'lru_cache|functools\.cache|diskcache|redis|@cache' -g '*.py'
|
|
26
|
+
rg -n 'def (classify|extract|summari[sz]e|label|tag)\w*\(' -g '*.py'
|
|
27
|
+
```
|
|
28
|
+
Shapes: `def classify(text): return client.chat.completions.create(...)` called from a view or a loop, with no cache in front; a nightly job that processes all rows instead of changed rows; a test suite that hits the API.
|
|
29
|
+
|
|
30
|
+
TS/JS:
|
|
31
|
+
```
|
|
32
|
+
rg -n 'async function (classify|extract|summari[sz]e|label)\w*\(|new Map\(|lru-cache|keyv' -g '*.{ts,tsx,js,mjs}'
|
|
33
|
+
```
|
|
34
|
+
Shapes: a request handler that calls the model with the same inputs on every page view.
|
|
35
|
+
|
|
36
|
+
Go:
|
|
37
|
+
```
|
|
38
|
+
rg -n 'func (Classify|Extract|Summari[sz]e|Label)\w*\(|groupcache|ristretto|bigcache' -g '*.go'
|
|
39
|
+
```
|
|
40
|
+
Shapes: a handler that calls the model for an entity whose text has not changed since the last call.
|
|
41
|
+
|
|
42
|
+
Not a finding: requests that are meant to vary (sampling, chat replies), and requests whose prompt carries time-relative or changing content.
|
|
43
|
+
|
|
44
|
+
## Fix
|
|
45
|
+
Key the cache on everything that can change the answer: the model, every sampling and output parameter, the tools and the full prompt. A canonical JSON of the request body works. kvsig gives most of a ready-made key: the exact `nodes` id of the last message (the whole prompt), plus the model and a hash of the parameters.
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
# before
|
|
49
|
+
def classify(text: str) -> str:
|
|
50
|
+
resp = client.chat.completions.create(model=MODEL, messages=build(text), temperature=0)
|
|
51
|
+
return resp.choices[0].message.content
|
|
52
|
+
|
|
53
|
+
# after
|
|
54
|
+
def classify(text: str) -> str:
|
|
55
|
+
body = {"model": MODEL, "messages": build(text), "temperature": 0}
|
|
56
|
+
key = sha256(json.dumps(body, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
|
|
57
|
+
if (hit := store.get(key)) is not None:
|
|
58
|
+
return hit
|
|
59
|
+
out = client.chat.completions.create(**body).choices[0].message.content
|
|
60
|
+
store.set(key, out, ttl=RESULT_TTL) # expire when the prompt, model or data version changes
|
|
61
|
+
return out
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
For batch pipelines, the cheaper form is often to skip unchanged inputs: store a hash of each input with its result and process only rows whose hash changed.
|
|
65
|
+
|
|
66
|
+
## Don't break meaning
|
|
67
|
+
Serve a stored answer only when a fresh call would be expected to give the same answer: the request is identical, the app treats one answer as the answer (temperature zero or a fixed choice), and nothing outside the request changed (the date, a tool result, a database row). Put the model and prompt version in the key, so a prompt change misses the cache instead of serving old answers. Never share cached answers across users or tenants when the request carries their data. Do not cache refusals, errors or truncated answers.
|
|
68
|
+
|
|
69
|
+
## Verify
|
|
70
|
+
(a) Provider usage: the number of calls and their `prompt_tokens` and `output_tokens` / `completion_tokens` fall by the hit count; for the requests that remain, `cached_tokens` behaviour is unchanged.
|
|
71
|
+
|
|
72
|
+
(b) leanprompt usage record: before, several records with equal exact `ids.nodes` for the last message and an equal `params` hash; after, one record per distinct request within the cache lifetime. The `output_tokens` of the duplicates is the waste removed. kvsig: equal exact `nodes[i]` for the last message plus equal `params` is the duplicate the audit looks for.
|
|
73
|
+
|
|
74
|
+
## Waste signal
|
|
75
|
+
Measured: output tokens on calls repeated identically (same exact ids, same `params`) count as generation waste. Static: severity medium for a deterministic call (temperature zero, a classification or extraction prompt) on a path that runs repeatedly for the same input with no cache in front; low for tests that call the live model.
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: LP-GE-07
|
|
3
|
+
title: Batch API for work that can wait
|
|
4
|
+
skill: generation-economy
|
|
5
|
+
applies_to: [openai, anthropic, gemini, openrouter, deepinfra]
|
|
6
|
+
saves: both
|
|
7
|
+
severity: medium
|
|
8
|
+
evidence:
|
|
9
|
+
- doc: https://developers.openai.com/api/docs/guides/batch
|
|
10
|
+
checked: 2026-11-26
|
|
11
|
+
- doc: https://platform.claude.com/docs/en/build-with-claude/batch-processing
|
|
12
|
+
checked: 2026-11-26
|
|
13
|
+
- doc: https://aistudio.google.com/docs/batch-api
|
|
14
|
+
checked: 2026-11-26
|
|
15
|
+
- doc: https://openrouter.ai/docs/guides/features/batch-api
|
|
16
|
+
checked: 2026-11-26
|
|
17
|
+
- doc: https://docs.deepinfra.com/batch/introduction.md
|
|
18
|
+
checked: 2026-11-26
|
|
19
|
+
---
|
|
20
|
+
## Rule
|
|
21
|
+
Send work that no user is waiting for (backfills, nightly jobs, evaluations, bulk extraction, embeddings of a corpus) through the provider's batch API instead of the interactive endpoint.
|
|
22
|
+
|
|
23
|
+
## Why
|
|
24
|
+
Batch APIs bill the same requests at a discount in exchange for asynchronous completion within a window. The discount, the window and the limits differ per provider and are in the tables:
|
|
25
|
+
|
|
26
|
+
- **OpenAI** Batch API, and a `flex` service tier priced at batch rates for calls that can tolerate slow responses and occasional unavailability ([providers/openai.md](../../../providers/openai.md)).
|
|
27
|
+
- **Anthropic** Message Batches; prompt caching works in batches on a best-effort basis, and the docs suggest the longer cache lifetime for shared context ([providers/anthropic.md](../../../providers/anthropic.md)).
|
|
28
|
+
- **Gemini** Batch API, with context caching supported for batch requests ([providers/gemini.md](../../../providers/gemini.md)).
|
|
29
|
+
- **OpenRouter** batch endpoint, for models with a batch variant ([providers/openrouter.md](../../../providers/openrouter.md)).
|
|
30
|
+
- **DeepInfra** batch API, a smaller discount than the others, outside the real-time rate limits ([providers/deepinfra.md](../../../providers/deepinfra.md)).
|
|
31
|
+
- **vLLM** has a batch endpoint that takes many conversations in one request; on your own server the saving is throughput, not a price ([providers/vllm.md](../../../providers/vllm.md)). SGLang: no batch API on the pages read ([providers/sglang.md](../../../providers/sglang.md)).
|
|
32
|
+
|
|
33
|
+
The tokens are the same; the price per token is lower. Batch jobs also do not compete with interactive traffic for rate limits on providers that say so.
|
|
34
|
+
|
|
35
|
+
## Detect in code
|
|
36
|
+
Python:
|
|
37
|
+
```
|
|
38
|
+
rg -n 'for (row|doc|item|record) in .*(tqdm|df\.|rows|records|dataset)|asyncio\.Semaphore|ThreadPoolExecutor' -g '*.py'
|
|
39
|
+
rg -n 'schedule|cron|airflow|@task|backfill|evaluate|eval_' -g '*.py'
|
|
40
|
+
```
|
|
41
|
+
Shapes: a script or scheduled task that loops over a dataset and calls `chat.completions.create` / `messages.create` per row; an evaluation harness that runs a fixed suite against the live endpoint; an embeddings backfill one request at a time.
|
|
42
|
+
|
|
43
|
+
TS/JS:
|
|
44
|
+
```
|
|
45
|
+
rg -n 'p-limit|p-map|Bottleneck|for await \(const (row|doc|item)|cron' -g '*.{ts,tsx,js,mjs}'
|
|
46
|
+
```
|
|
47
|
+
Shapes: a job runner that rate-limits interactive calls over thousands of items.
|
|
48
|
+
|
|
49
|
+
Go:
|
|
50
|
+
```
|
|
51
|
+
rg -n 'for _, (row|doc|item|rec) := range|errgroup|semaphore\.NewWeighted|cron\.' -g '*.go'
|
|
52
|
+
```
|
|
53
|
+
Shapes: a worker pool over a table, each worker calling the completions endpoint.
|
|
54
|
+
|
|
55
|
+
Not a finding: anything a user waits for, and jobs whose next step needs each answer before the next request can be built (agent loops).
|
|
56
|
+
|
|
57
|
+
## Fix
|
|
58
|
+
```python
|
|
59
|
+
# before: thousands of interactive calls from a nightly job
|
|
60
|
+
for row in rows:
|
|
61
|
+
save(row.id, client.chat.completions.create(**build_request(row)))
|
|
62
|
+
|
|
63
|
+
# after: one batch, collected when it completes
|
|
64
|
+
lines = [{"custom_id": str(r.id), "method": "POST", "url": "/v1/chat/completions", "body": build_request(r)} for r in rows]
|
|
65
|
+
batch_file = client.files.create(file=to_jsonl(lines), purpose="batch")
|
|
66
|
+
batch = client.batches.create(input_file_id=batch_file.id, endpoint="/v1/chat/completions", completion_window="24h")
|
|
67
|
+
# later, from a scheduled poll
|
|
68
|
+
for result in read_results(client, batch.id):
|
|
69
|
+
save(result["custom_id"], result["response"]["body"])
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
The same request bodies go into the batch. Keep the shared prefix first and identical (the `prefill-cache` rules), so batch requests can also hit the cache where the provider supports it. On OpenAI, `service_tier: "flex"` on the same synchronous call is a smaller change where flex is still offered for the model.
|
|
73
|
+
|
|
74
|
+
## Don't break meaning
|
|
75
|
+
The request bodies are unchanged, so answers do not change. What changes is delivery: results arrive later and in any order (match them by `custom_id`), some requests can fail or expire (resubmit those, and only those), and a batch is no place for anything interactive. Log the batch results as usage records like any other call.
|
|
76
|
+
|
|
77
|
+
## Verify
|
|
78
|
+
(a) Provider usage: each batch result carries its own usage (`output_tokens` or `completion_tokens`, `finish_reason` or `stop_reason`); the billing page shows the batch rate for those tokens. Token counts per item stay the same as the interactive form.
|
|
79
|
+
|
|
80
|
+
(b) leanprompt usage record: one record per batch result, with its `finish`; resubmitted expired or failed lines carry `flags.retry_of`. Money is not in the score, so the score does not move; the report shows the price change separately with the price card's date.
|
|
81
|
+
|
|
82
|
+
## Waste signal
|
|
83
|
+
Not in the score (the score counts tokens, not price). Static: severity medium for a scheduled or bulk job that sends many independent calls to the interactive endpoint of a provider with a batch API; reported with the provider's discount from its table.
|