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,87 @@
|
|
|
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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/models/anthropic-thinking.md), [models/openai-reasoning.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openai.md)); Anthropic `max_tokens` and adaptive thinking with `effort` ([providers/anthropic.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/anthropic.md)); Gemini `maxOutputTokens`, `thinkingBudget`, `thinkingLevel` ([providers/gemini.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/gemini.md)); OpenRouter `max_tokens`, which covers reasoning and visible output together on most providers ([providers/openrouter.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openrouter.md)); vLLM and SGLang `max_tokens` plus the model's template kwargs ([providers/vllm.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/vllm.md), [providers/sglang.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/sglang.md)).
|
|
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.
|
|
87
|
+
<!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
|
|
@@ -0,0 +1,118 @@
|
|
|
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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/gemini.md), [providers/deepinfra.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/deepinfra.md), [providers/vllm.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/vllm.md), [providers/sglang.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/sglang.md)).
|
|
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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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).
|
|
118
|
+
<!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
|
|
@@ -0,0 +1,84 @@
|
|
|
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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openai.md), [providers/anthropic.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/anthropic.md)).
|
|
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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openai.md), [providers/anthropic.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/anthropic.md)).
|
|
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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openai.md), [providers/anthropic.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/anthropic.md)), 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.
|
|
84
|
+
<!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: LP-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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/anthropic.md), [providers/openai.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openai.md), [providers/gemini.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/gemini.md), [providers/deepinfra.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/deepinfra.md)). A self-hosted engine reuses the prefix but still spends the decode time ([providers/vllm.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/vllm.md), [providers/sglang.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/sglang.md)). 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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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.
|
|
76
|
+
<!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
|
|
@@ -0,0 +1,84 @@
|
|
|
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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/anthropic.md)).
|
|
28
|
+
- **Gemini** Batch API, with context caching supported for batch requests ([providers/gemini.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/gemini.md)).
|
|
29
|
+
- **OpenRouter** batch endpoint, for models with a batch variant ([providers/openrouter.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openrouter.md)).
|
|
30
|
+
- **DeepInfra** batch API, a smaller discount than the others, outside the real-time rate limits ([providers/deepinfra.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/vllm.md)). SGLang: no batch API on the pages read ([providers/sglang.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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.
|
|
84
|
+
<!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: LP-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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/models/openai-reasoning.md), [models/anthropic-thinking.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/anthropic.md), [providers/openai.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openai.md), [providers/gemini.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/gemini.md), [providers/openrouter.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openrouter.md), [providers/deepinfra.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/deepinfra.md)). On a self-hosted server a second model costs GPU memory; it pays only if the small calls are frequent ([providers/vllm.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/vllm.md), [providers/sglang.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/sglang.md)).
|
|
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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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.
|
|
71
|
+
<!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
|
|
@@ -0,0 +1,79 @@
|
|
|
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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/anthropic.md), [providers/gemini.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/gemini.md), [providers/openrouter.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openrouter.md), [providers/deepinfra.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/deepinfra.md), [providers/sglang.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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.
|
|
79
|
+
<!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
|