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,247 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join, resolve } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { parseArgs } from "node:util";
|
|
5
|
+
import { optionsFor } from "../help.js";
|
|
6
|
+
import { loadCacheFacts } from "../facts.js";
|
|
7
|
+
import { loadRuleIds, loadRules } from "../lint/rules.js";
|
|
8
|
+
import { parseUsageLog } from "../log/record.js";
|
|
9
|
+
import { effectiveFacts, loadProfile } from "../profile.js";
|
|
10
|
+
import { measuredScore, MIN_CALLS } from "./measured.js";
|
|
11
|
+
import { parseFindings, staticScore } from "./static.js";
|
|
12
|
+
// cli/src/score and cli/dist/score are the same depth below the package root.
|
|
13
|
+
export const PACKAGE_ROOT = fileURLToPath(new URL("../../../", import.meta.url));
|
|
14
|
+
const VERSION = JSON.parse(readFileSync(join(PACKAGE_ROOT, "package.json"), "utf8")).version;
|
|
15
|
+
// Display names: always "/" (join() still makes native paths where a file is opened).
|
|
16
|
+
export const USAGE_FILE = ".leanprompt/usage.jsonl";
|
|
17
|
+
export const FINDINGS_FILE = ".leanprompt/findings.json";
|
|
18
|
+
export const WEIGHTS_FILE = ".leanprompt/weights.json";
|
|
19
|
+
const SCORE_FILE = join(".leanprompt", "score.json");
|
|
20
|
+
/** shields.io colour for a score. Static scores are estimates from an audit, so they are always grey. */
|
|
21
|
+
export function badgeColor(score, kind) {
|
|
22
|
+
if (kind === "static")
|
|
23
|
+
return "lightgrey";
|
|
24
|
+
if (score >= 90)
|
|
25
|
+
return "brightgreen";
|
|
26
|
+
if (score >= 75)
|
|
27
|
+
return "green";
|
|
28
|
+
if (score >= 50)
|
|
29
|
+
return "yellow";
|
|
30
|
+
return "red";
|
|
31
|
+
}
|
|
32
|
+
/** Read and validate `.leanprompt/weights.json`. Null when absent; throws naming the file when invalid. */
|
|
33
|
+
export function loadWeights(file) {
|
|
34
|
+
if (!existsSync(file))
|
|
35
|
+
return null;
|
|
36
|
+
let doc;
|
|
37
|
+
try {
|
|
38
|
+
doc = JSON.parse(readFileSync(file, "utf8"));
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
throw new Error(`${file}: not valid JSON`);
|
|
42
|
+
}
|
|
43
|
+
const d = doc;
|
|
44
|
+
if (!d || typeof d !== "object" || Array.isArray(d))
|
|
45
|
+
throw new Error(`${file}: must be an object`);
|
|
46
|
+
if (d.v !== 1)
|
|
47
|
+
throw new Error(`${file}: v must be 1`);
|
|
48
|
+
for (const k of ["k_prefill", "k_gen"]) {
|
|
49
|
+
const x = d[k];
|
|
50
|
+
if (typeof x !== "number" || !Number.isFinite(x) || x < 0)
|
|
51
|
+
throw new Error(`${file}: ${k} must be a finite number >= 0`);
|
|
52
|
+
}
|
|
53
|
+
return d;
|
|
54
|
+
}
|
|
55
|
+
/** What to do about each reason a call was left unmeasured, printed with a refusal. */
|
|
56
|
+
const REASON_HINTS = {
|
|
57
|
+
no_usage: "no prompt token count: pass the provider response's usage object to the logger",
|
|
58
|
+
unknown_provider: "no cache facts for the record's provider: log a provider name leanprompt knows, or set target in leanprompt.yaml (see skills/measure-loop/SKILL.md)",
|
|
59
|
+
ambiguous_target: "the record's provider has no cache table and matches none of the several targets in leanprompt.yaml: log the backend's own name (vllm, lm-warden, openai...) or add a targets entry with that provider (see docs/profile.md)",
|
|
60
|
+
no_ids: "the request could not be identified (unsupported dialect, stateful or malformed body)",
|
|
61
|
+
};
|
|
62
|
+
/** `no_usage 60, no_ids 3`, nonzero reasons only. */
|
|
63
|
+
export function formatReasons(byReason) {
|
|
64
|
+
return Object.entries(byReason)
|
|
65
|
+
.filter(([, n]) => n > 0)
|
|
66
|
+
.map(([k, n]) => `${k} ${n}`)
|
|
67
|
+
.join(", ");
|
|
68
|
+
}
|
|
69
|
+
/** Drop findings the profile's `ignore:` list names (same rule and file). */
|
|
70
|
+
export function filterIgnored(findings, profile) {
|
|
71
|
+
const ignore = profile?.ignore ?? [];
|
|
72
|
+
return findings.filter((f) => !ignore.some((i) => i.rule === f.rule && i.file === f.file));
|
|
73
|
+
}
|
|
74
|
+
/** Escape for a GitHub Actions workflow command: the message, and (with `property`) a key=value property. */
|
|
75
|
+
export function ghEscape(s, property = false) {
|
|
76
|
+
let out = s.replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
|
|
77
|
+
if (property)
|
|
78
|
+
out = out.replace(/:/g, "%3A").replace(/,/g, "%2C");
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* One `::warning` line per open finding (not fixed, not on the ignore list), for GitHub Actions to show
|
|
83
|
+
* on the file and line. An `<external>` finding, or one with no line, is annotated without them.
|
|
84
|
+
*/
|
|
85
|
+
export function githubAnnotations(findings, rules) {
|
|
86
|
+
return findings
|
|
87
|
+
.filter((f) => f.fixed !== true)
|
|
88
|
+
.map((f) => {
|
|
89
|
+
const props = [];
|
|
90
|
+
if (f.file !== "<external>") {
|
|
91
|
+
props.push(`file=${ghEscape(f.file, true)}`);
|
|
92
|
+
if (f.line > 0)
|
|
93
|
+
props.push(`line=${f.line}`);
|
|
94
|
+
}
|
|
95
|
+
const title = rules.get(f.rule)?.title;
|
|
96
|
+
props.push(`title=${ghEscape(`leanprompt ${f.rule}${title ? `: ${title}` : ""}`, true)}`);
|
|
97
|
+
const where = f.file === "<external>" ? ` (${f.where ?? "outside the repository"})` : "";
|
|
98
|
+
const question = f.status === "needs-facts" ? ` Open question: ${f.confirm ?? "confirm before fixing"}` : "";
|
|
99
|
+
const msg = `${f.problem ?? title ?? f.rule}${where}${f.estimate ? ` Estimate: ${f.estimate}.` : ""}${question}`;
|
|
100
|
+
return `::warning ${props.join(",")}::${ghEscape(msg)}`;
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* `leanprompt score [--measured [<usage.jsonl>]] [--static [<findings.json>]] [--dir <project>]`.
|
|
105
|
+
* A bare `--measured` or `--static` means the project's own `.leanprompt/usage.jsonl` or `.leanprompt/findings.json`.
|
|
106
|
+
*/
|
|
107
|
+
export async function scoreCommand(args) {
|
|
108
|
+
let values;
|
|
109
|
+
// parseArgs has no optional-value strings: give a bare flag an empty value, resolved below.
|
|
110
|
+
const argv = args.map((a, i) => ((a === "--static" || a === "--measured") && (args[i + 1] === undefined || args[i + 1].startsWith("--")) ? `${a}=` : a));
|
|
111
|
+
try {
|
|
112
|
+
values = parseArgs({ args: argv, options: optionsFor("score"), strict: true }).values;
|
|
113
|
+
}
|
|
114
|
+
catch (e) {
|
|
115
|
+
process.stderr.write(`leanprompt: ${e.message}\n`);
|
|
116
|
+
return 2;
|
|
117
|
+
}
|
|
118
|
+
const dir = resolve(values.dir ?? ".");
|
|
119
|
+
let failUnder;
|
|
120
|
+
if (values["fail-under"] !== undefined) {
|
|
121
|
+
failUnder = Number(values["fail-under"]);
|
|
122
|
+
if (values["fail-under"].trim() === "" || !Number.isFinite(failUnder) || failUnder < 0 || failUnder > 100) {
|
|
123
|
+
process.stderr.write(`leanprompt: --fail-under needs a number from 0 to 100, not "${values["fail-under"]}"\n`);
|
|
124
|
+
return 2;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
if (values.measured !== undefined && values.static !== undefined) {
|
|
128
|
+
process.stderr.write("leanprompt: give --measured or --static, not both\n");
|
|
129
|
+
return 2;
|
|
130
|
+
}
|
|
131
|
+
let measuredPath = values.measured === undefined ? undefined : values.measured === "" ? join(dir, USAGE_FILE) : resolve(values.measured);
|
|
132
|
+
let staticPath = values.static === undefined ? undefined : values.static === "" ? join(dir, FINDINGS_FILE) : resolve(values.static);
|
|
133
|
+
if (measuredPath === undefined && staticPath === undefined) {
|
|
134
|
+
if (existsSync(join(dir, USAGE_FILE)))
|
|
135
|
+
measuredPath = join(dir, USAGE_FILE);
|
|
136
|
+
else if (existsSync(join(dir, FINDINGS_FILE)))
|
|
137
|
+
staticPath = join(dir, FINDINGS_FILE);
|
|
138
|
+
else {
|
|
139
|
+
process.stderr.write(`leanprompt: nothing to score: neither ${USAGE_FILE} nor ${FINDINGS_FILE} exists in ${dir}. Pass --measured or --static.\n`);
|
|
140
|
+
return 2;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
const profile = loadProfile(dir);
|
|
144
|
+
let kind;
|
|
145
|
+
let score;
|
|
146
|
+
let inputs;
|
|
147
|
+
let weights = "default";
|
|
148
|
+
let evidence;
|
|
149
|
+
if (measuredPath !== undefined) {
|
|
150
|
+
kind = "measured";
|
|
151
|
+
if (!existsSync(measuredPath))
|
|
152
|
+
throw new Error(`${measuredPath}: no such file`);
|
|
153
|
+
const { records, bad } = parseUsageLog(readFileSync(measuredPath, "utf8"));
|
|
154
|
+
if (bad > 0)
|
|
155
|
+
process.stderr.write(`leanprompt: skipped ${bad} unreadable line(s) in ${measuredPath}\n`);
|
|
156
|
+
const facts = loadCacheFacts(PACKAGE_ROOT);
|
|
157
|
+
const r = measuredScore(records, (provider) => effectiveFacts(profile, facts, provider));
|
|
158
|
+
if (!r.ok) {
|
|
159
|
+
const found = r.calls - r.unmeasured;
|
|
160
|
+
process.stderr.write(`measured score needs at least ${MIN_CALLS} calls; found ${found}. Run with --static to score from the audit's findings.\n`);
|
|
161
|
+
if (r.unmeasured > 0) {
|
|
162
|
+
process.stderr.write(`(${r.unmeasured} of ${r.calls} logged calls could not be measured and are not counted: ${formatReasons(r.unmeasured_by_reason)}.)\n`);
|
|
163
|
+
for (const [k, n] of Object.entries(r.unmeasured_by_reason)) {
|
|
164
|
+
if (n > 0 && REASON_HINTS[k])
|
|
165
|
+
process.stderr.write(` ${k}: ${REASON_HINTS[k]}\n`);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return 1;
|
|
169
|
+
}
|
|
170
|
+
const m = r;
|
|
171
|
+
score = m.score;
|
|
172
|
+
inputs = m.inputs;
|
|
173
|
+
evidence = {
|
|
174
|
+
calls: m.calls,
|
|
175
|
+
unmeasured: m.unmeasured,
|
|
176
|
+
diagnostics: { estimate: m.estimate, heads: m.heads, unmeasured_by_reason: m.unmeasured_by_reason },
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
else {
|
|
180
|
+
kind = "static";
|
|
181
|
+
const file = staticPath;
|
|
182
|
+
if (!existsSync(file))
|
|
183
|
+
throw new Error(`${file}: no such file`);
|
|
184
|
+
const parsed = parseFindings(readFileSync(file, "utf8"), loadRuleIds(PACKAGE_ROOT));
|
|
185
|
+
if (parsed.errors.length > 0)
|
|
186
|
+
throw new Error(`${file}: ${parsed.errors.join("; ")}`);
|
|
187
|
+
const findings = filterIgnored(parsed.findings, profile);
|
|
188
|
+
const w = loadWeights(join(dir, WEIGHTS_FILE));
|
|
189
|
+
const s = staticScore(findings, w ?? undefined);
|
|
190
|
+
score = s.score;
|
|
191
|
+
inputs = s.inputs;
|
|
192
|
+
weights = s.weights;
|
|
193
|
+
evidence = { diagnostics: { default_shares: s.default_shares.used, findings: s.default_shares.of } };
|
|
194
|
+
}
|
|
195
|
+
const out = {
|
|
196
|
+
schemaVersion: 1,
|
|
197
|
+
label: "leanprompt",
|
|
198
|
+
message: `${score} ${kind}${weights === "calibrated" ? ", calibrated" : ""}`,
|
|
199
|
+
color: badgeColor(score, kind),
|
|
200
|
+
v: 1,
|
|
201
|
+
score,
|
|
202
|
+
kind,
|
|
203
|
+
inputs,
|
|
204
|
+
weights,
|
|
205
|
+
...evidence,
|
|
206
|
+
date: new Date().toISOString().slice(0, 10),
|
|
207
|
+
leanprompt: VERSION,
|
|
208
|
+
};
|
|
209
|
+
const target = join(dir, SCORE_FILE);
|
|
210
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
211
|
+
writeFileSync(target, `${JSON.stringify(out, null, 2)}\n`);
|
|
212
|
+
const f = (x) => x.toFixed(2);
|
|
213
|
+
process.stdout.write(`leanprompt score: ${out.message}\n E prefill reuse ${f(inputs.E)}, S prefix stability ${f(inputs.S)}, G generation waste ${f(inputs.G)}\n`);
|
|
214
|
+
if (kind === "static") {
|
|
215
|
+
const d = evidence.diagnostics;
|
|
216
|
+
process.stdout.write(` default_shares: ${d.default_shares} of ${d.findings} findings used the severity default share, not an estimate\n`);
|
|
217
|
+
if (d.findings > 0 && d.default_shares === d.findings) {
|
|
218
|
+
process.stdout.write(` note: every share is a severity default, so this score says little about this app; give each finding a share from the audit's estimate (skills/llm-call-audit/SKILL.md, "The findings file")\n`);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
if (kind === "measured") {
|
|
222
|
+
const calls = evidence.calls;
|
|
223
|
+
const unmeasured = evidence.unmeasured;
|
|
224
|
+
process.stdout.write(` calls logged ${calls}, measured ${calls - unmeasured}, unmeasured ${unmeasured}\n`);
|
|
225
|
+
}
|
|
226
|
+
process.stdout.write(` wrote ${target}\n`);
|
|
227
|
+
if (values.github === true) {
|
|
228
|
+
// Annotations come from the findings file, whichever score was computed.
|
|
229
|
+
const file = staticPath ?? join(dir, FINDINGS_FILE);
|
|
230
|
+
let open = [];
|
|
231
|
+
if (existsSync(file)) {
|
|
232
|
+
const parsed = parseFindings(readFileSync(file, "utf8"), loadRuleIds(PACKAGE_ROOT));
|
|
233
|
+
if (parsed.errors.length > 0)
|
|
234
|
+
throw new Error(`${file}: ${parsed.errors.join("; ")}`);
|
|
235
|
+
open = githubAnnotations(filterIgnored(parsed.findings, profile), loadRules(PACKAGE_ROOT));
|
|
236
|
+
}
|
|
237
|
+
for (const line of open)
|
|
238
|
+
process.stdout.write(`${line}\n`);
|
|
239
|
+
const n = open.length;
|
|
240
|
+
process.stdout.write(`::notice title=leanprompt score::${ghEscape(`leanprompt score ${out.message}; ${n} open finding${n === 1 ? "" : "s"}${existsSync(file) ? "" : ` (no ${FINDINGS_FILE})`}`)}\n`);
|
|
241
|
+
}
|
|
242
|
+
if (failUnder !== undefined && score < failUnder) {
|
|
243
|
+
process.stderr.write(`leanprompt: score ${score} is below --fail-under ${failUnder}\n`);
|
|
244
|
+
return 3;
|
|
245
|
+
}
|
|
246
|
+
return 0;
|
|
247
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
<!-- leanprompt:begin -->
|
|
2
|
+
## leanprompt
|
|
3
|
+
|
|
4
|
+
Skills that get more from every LLM call: cacheable prompts, no dead weight, no wasted output.
|
|
5
|
+
Load a skill only
|
|
6
|
+
when its task comes up, and a rule file only when the skill points at it.
|
|
7
|
+
|
|
8
|
+
Skills live in `.claude/skills/<name>/`, `.agents/skills/<name>/` or `.cursor/skills/<name>/`:
|
|
9
|
+
|
|
10
|
+
- `leanprompt`: the entry point: `/leanprompt` lists the commands (init, audit, fix, measure, score, report, lesson)
|
|
11
|
+
- `llm-call-audit`: audit an app's LLM calls, rank the waste, write the report and findings
|
|
12
|
+
- `prefill-cache`: rules for prompts the provider's cache can reuse (LP-PC-*)
|
|
13
|
+
- `generation-economy`: rules for calls and output that are not wasted (LP-GE-*)
|
|
14
|
+
- `prompt-diet`: rules that cut dead weight from what each call sends (LP-PD-*)
|
|
15
|
+
- `measure-loop`: prove a fix with a before and after number; the score (CI test, logger)
|
|
16
|
+
- `lmwarden`: rules for self-hosted vLLM, SGLang and LM Warden servers (LP-LW-*)
|
|
17
|
+
|
|
18
|
+
- Start with the `leanprompt` skill (`/leanprompt audit`, or `$leanprompt audit` in Codex), which routes to `llm-call-audit`.
|
|
19
|
+
- Rules are in `<skill>/rules/LP-*.md`. Each ends with `Verify`; run it before calling a fix done.
|
|
20
|
+
- Provider and model facts (limits, minimums, TTLs) are in the `providers/` and `models/`
|
|
21
|
+
pages linked from each rule, and HTTP client defaults in `runtimes/`, each with a `checked:`
|
|
22
|
+
date. Do not quote them from memory.
|
|
23
|
+
- Ask before editing code, installing a package, or running anything that sends billed requests.
|
|
24
|
+
- Keep meaning: a fix that changes what the model is asked or answers is not a fix.
|
|
25
|
+
<!-- leanprompt:end -->
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: Audit this project's LLM calls with leanprompt and write leanprompt-report.md
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
Load the `llm-call-audit` skill and run it on this project. Find every LLM call, check it
|
|
6
|
+
against the leanprompt rules, rank the findings by tokens lost, and write
|
|
7
|
+
`leanprompt-report.md` and `.leanprompt/findings.json`. Do not edit code without asking.
|
|
8
|
+
|
|
9
|
+
Focus, if given: $ARGUMENTS
|
|
10
|
+
<!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: leanprompt commands for this app's LLM calls (init, audit, fix, measure, score, report, lesson)
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
Load the `leanprompt` skill and follow its routing for this command: $ARGUMENTS
|
|
6
|
+
|
|
7
|
+
With no command, show the skill's menu and suggest one next step. Do not edit code without asking.
|
|
8
|
+
<!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: generation-economy
|
|
3
|
+
description: Use when writing, reviewing or debugging code that calls an LLM and controls how much it generates or how often it calls — sample loops, per-question calls over one document, max_tokens and thinking or effort settings, timeouts, retries, response caching, bulk or nightly jobs, model choice for small calls, file edits, JSON parsing — for Anthropic, OpenAI, Gemini, OpenRouter, DeepInfra or a self-hosted vLLM or SGLang server, or when usage shows truncated answers (finish_reason length, stop_reason max_tokens), retries, repeated identical calls or parse failures. Stops paying to generate, or to prefill again, what one call could have produced.
|
|
4
|
+
license: CC-BY-4.0
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# generation-economy
|
|
8
|
+
|
|
9
|
+
Stops paying to generate, or to prefill again, what one call could have produced. Ten rules, `LP-GE-01` to `LP-GE-10`, each in its own file under `rules/`, each with a way to detect it in code, the smallest fix, what the fix must not break, and how to verify it.
|
|
10
|
+
|
|
11
|
+
The `prefill-cache` skill makes each prompt cheaper to read. This skill is about the calls themselves: how many there are, how much each one generates, and how many of them are thrown away (repeated, retried after a truncation or a timeout, or discarded after a parse failure).
|
|
12
|
+
|
|
13
|
+
## When to use
|
|
14
|
+
|
|
15
|
+
- You are writing or changing code that decides how many calls to make (sampling, one call per question, loops over a dataset), what each may generate (output limits, thinking or effort), or what happens when a call fails or is slow (timeouts, retries, parsing).
|
|
16
|
+
- Usage shows truncated answers, retries, identical repeated calls, parse failures, or output tokens far above what the answers need.
|
|
17
|
+
- The `llm-call-audit` skill sends you here for an `LP-GE-*` finding.
|
|
18
|
+
|
|
19
|
+
## Priority-aware advice
|
|
20
|
+
|
|
21
|
+
Read `priority` from `leanprompt.yaml` (`cost`, `speed`, `quality`, or weights). Without it, ask, or treat the priorities as equal. Rank findings for the priority, but never drop a finding that wastes tokens without buying anything (LP-GE-04, LP-GE-05, LP-GE-10 remove pure waste under every priority).
|
|
22
|
+
|
|
23
|
+
- **Cost first:** the batch API for anything that can wait (LP-GE-07), `n` samples instead of repeats (LP-GE-01), exact-response caching (LP-GE-06), batched questions (LP-GE-02), smaller models for small calls (LP-GE-08), cheaper service tiers where the provider offers them, and aggressive prefix caching (the `prefill-cache` skill).
|
|
24
|
+
- **Speed first:** streaming and idle timeouts (LP-GE-04), output and thinking budgets that fit the task, with thinking off or low effort where the answer check allows (LP-GE-03), smaller models for small steps (LP-GE-08), predicted outputs or changes-only edits (LP-GE-09).
|
|
25
|
+
- **Quality first:** keep thinking on, with budgets that never truncate a correct answer (LP-GE-03); larger models for hard steps; batch, route or shorten only where the answer check passes (LP-GE-02, LP-GE-08). Caching applies under every priority, because it never changes answers (LP-GE-06 for identical deterministic requests, and the `prefill-cache` skill).
|
|
26
|
+
|
|
27
|
+
Any change that can alter answers (fewer separate calls, a smaller model, less thinking, shorter outputs, a schema in place of prose) ships with an answer check: a fixed set of synthetic inputs, outputs compared before and after, pass/fail. Caching-only changes are exempt.
|
|
28
|
+
|
|
29
|
+
## Workflow
|
|
30
|
+
|
|
31
|
+
1. **Know the target and priority.** Read `leanprompt.yaml` if the project has one (`target`, `priority`). Otherwise infer the provider and model from the SDK, `base_url` and model names, and ask if it is unclear. Open that provider's table from the list below; each has a "Generation features" section.
|
|
32
|
+
2. **Find the calls.** List every LLM call and, for each, what wraps it: loops and gathers, retry decorators and SDK retry settings, timeouts, parsing, caches, scheduling (interactive, background, nightly), and the model and budget settings.
|
|
33
|
+
3. **Check each rule,** in the order of the index below. Each rule's "Detect in code" gives `rg` patterns and code shapes for Python, TS/JS and Go. Open a rule file when its pattern matches.
|
|
34
|
+
4. **Propose the fix.** Give the rule id, file and line, and the smallest change from the rule's "Fix", with its "Don't break meaning" check. When you are reviewing existing code, propose and ask before editing. When you are writing the call now, apply the rules directly.
|
|
35
|
+
5. **Verify.** Use the rule's "Verify": (a) the provider's usage fields (output tokens, `finish_reason` or `stop_reason`, number of calls), and (b) the leanprompt usage record (`finish: "length"`, `flags.retry_of`, `flags.parse_failed`, repeated ids with equal `params`). The `measure-loop` skill turns these into a before/after run.
|
|
36
|
+
|
|
37
|
+
## Provider facts, in brief
|
|
38
|
+
|
|
39
|
+
What each provider supports, with prices, limits and windows, lives only in the dated tables; read it there, not from memory.
|
|
40
|
+
|
|
41
|
+
- **Anthropic.** No sample count. `max_tokens` includes thinking; truncation is `stop_reason: "max_tokens"`. Message Batches, with prompt caching on a best-effort basis. Structured outputs and strict tools. Streaming advised for long requests; the SDK retries by default. Service tiers are legacy. No predicted outputs. [providers/anthropic.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/anthropic.md), [models/anthropic-thinking.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/models/anthropic-thinking.md)
|
|
42
|
+
- **OpenAI.** `n` on Chat Completions (newer models reject it; the Responses API has none). Output limits include reasoning; truncation is `finish_reason: "length"` or an `incomplete` response. Batch API and a `flex` tier at batch rates where still offered. Predicted outputs on some Chat Completions models. Structured outputs. The SDK retries timed-out requests by default. [providers/openai.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openai.md), [models/openai-reasoning.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/models/openai-reasoning.md)
|
|
43
|
+
- **Gemini.** `candidateCount`; `thinkingBudget` and `thinkingLevel`; truncation is `MAX_TOKENS`. Batch API with context caching. Structured output with values to validate in the app. [providers/gemini.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/gemini.md)
|
|
44
|
+
- **OpenRouter.** A router: features depend on the upstream provider. No `n` listed. Batch endpoint for models with a batch variant. Aborting a stream stops billing only on the providers it lists. [providers/openrouter.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openrouter.md)
|
|
45
|
+
- **DeepInfra.** `n` with a small maximum; `service_tier` including `flex`; a batch API with a smaller discount; structured output. [providers/deepinfra.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/deepinfra.md)
|
|
46
|
+
- **vLLM and SGLang (self-hosted).** `n`, structured output by constrained decoding; vLLM has a batch endpoint and n-gram speculative decoding set on the server. Savings are throughput and GPU time, not price. [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), [models/qwen.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/models/qwen.md)
|
|
47
|
+
|
|
48
|
+
Evidence rows (E1 to E12) are in [docs/evidence.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/docs/evidence.md). A rule whose only source is provider documentation says "documented, not yet measured here".
|
|
49
|
+
|
|
50
|
+
## Frontier generation economy
|
|
51
|
+
|
|
52
|
+
On hosted frontier models, generation is priced per token and the levers are mostly request options. Choose them per the project's priority:
|
|
53
|
+
|
|
54
|
+
- **Batch APIs** for non-interactive work: OpenAI, Anthropic, Gemini, OpenRouter and DeepInfra bill batched requests at a discount, with a completion window instead of an immediate answer (LP-GE-07). The discount and window for each are in [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), [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) and [providers/deepinfra.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/deepinfra.md).
|
|
55
|
+
- **Cheaper service tiers** where offered: OpenAI `flex` at batch rates on models that still have it, and DeepInfra `flex`. Anthropic's tiers are legacy and offer no cheaper interactive tier; Gemini reports a tier in the response, and how to request one is not in its table yet.
|
|
56
|
+
- **Reasoning effort and thinking budgets**: the largest lever on output tokens for reasoning models. Set them per kind of task, hold them fixed per session, and check answers when lowering them (LP-GE-03; [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)).
|
|
57
|
+
- **Predicted outputs** for edits that repeat most of a file, where the provider supports them (OpenAI Chat Completions on some models); elsewhere ask for the changes only (LP-GE-09).
|
|
58
|
+
|
|
59
|
+
Prices change: the tables record what each provider documents and when it was checked, and the report shows money separately from the score, with the price card's date.
|
|
60
|
+
|
|
61
|
+
## Rules
|
|
62
|
+
|
|
63
|
+
| Id | Rule | Severity | Evidence |
|
|
64
|
+
|---|---|---|---|
|
|
65
|
+
| [LP-GE-01](rules/LP-GE-01.md) | n samples in one request | medium | E12, provider docs |
|
|
66
|
+
| [LP-GE-02](rules/LP-GE-02.md) | Batch independent questions about one context | medium | provider docs |
|
|
67
|
+
| [LP-GE-03](rules/LP-GE-03.md) | Output and thinking budgets that fit the task | high | E11, provider docs |
|
|
68
|
+
| [LP-GE-04](rules/LP-GE-04.md) | Stream long outputs; timeouts that match generation time | high | provider docs |
|
|
69
|
+
| [LP-GE-05](rules/LP-GE-05.md) | Retry only retryable errors; never retry a truncation unchanged | high | provider docs |
|
|
70
|
+
| [LP-GE-06](rules/LP-GE-06.md) | Cache exact responses for deterministic requests | medium | provider docs |
|
|
71
|
+
| [LP-GE-07](rules/LP-GE-07.md) | Batch API for work that can wait | medium | provider docs |
|
|
72
|
+
| [LP-GE-08](rules/LP-GE-08.md) | Route trivially small calls to a small model | medium | provider docs |
|
|
73
|
+
| [LP-GE-09](rules/LP-GE-09.md) | Predicted outputs for mostly unchanged text | low | provider docs |
|
|
74
|
+
| [LP-GE-10](rules/LP-GE-10.md) | Structured output instead of parse-and-re-ask | high | provider docs |
|
|
75
|
+
|
|
76
|
+
## Reading the usage record
|
|
77
|
+
|
|
78
|
+
The score's generation waste is output tokens spent on calls that were repeated identically, retried after a truncation, or discarded after a parse failure, over all output tokens. In `.leanprompt/usage.jsonl` those are:
|
|
79
|
+
|
|
80
|
+
- **Repeated identically:** two records with equal exact `ids.nodes` for the last message and an equal `params` hash (LP-GE-01, LP-GE-06).
|
|
81
|
+
- **Retried after a truncation:** a record with `finish: "length"`, and a later record whose `flags.retry_of` points at it (LP-GE-03, LP-GE-05).
|
|
82
|
+
- **Discarded after a parse failure:** a record with `flags.parse_failed` (LP-GE-10).
|
|
83
|
+
|
|
84
|
+
Batch discounts (LP-GE-07) and model choice (LP-GE-08) change money, not tokens, so they do not move the score; the report shows them separately.
|
|
85
|
+
|
|
86
|
+
## What this skill does not do
|
|
87
|
+
|
|
88
|
+
It does not make prompts cache better (that is `prefill-cache`), it does not cut dead weight from the prompt (that is `prompt-diet`), it does not tune engine settings or replica routing on a self-hosted server (that is `lmwarden`), and it does not promise a saving for an app it has not measured.
|
|
89
|
+
<!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
|
|
@@ -0,0 +1,93 @@
|
|
|
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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openai.md)).
|
|
26
|
+
- **Gemini** takes `candidateCount` in the generation config ([providers/gemini.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/gemini.md)).
|
|
27
|
+
- **DeepInfra** takes `n` on its OpenAI-compatible endpoint, with a small upper limit ([providers/deepinfra.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/deepinfra.md)).
|
|
28
|
+
- **vLLM** and **SGLang** take `n` ([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)). 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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/anthropic.md), [providers/openrouter.md](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/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.
|
|
93
|
+
<!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
|
|
@@ -0,0 +1,82 @@
|
|
|
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](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)). 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](https://github.com/Podwarden/leanprompt/blob/v0.1.0-dev.8/providers/openrouter.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)).
|
|
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.
|
|
82
|
+
<!-- leanprompt:generated v0.1.0-dev.8: written by npx leanprompt install; npx leanprompt update replaces local edits -->
|