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,98 @@
|
|
|
1
|
+
# Call shapes: how to find every LLM call
|
|
2
|
+
|
|
3
|
+
The first step of the audit is a complete inventory. An LLM call hides behind an SDK, a framework, a wrapper the app wrote itself, or a plain HTTP request. Search for all of them, then follow each hit to the line that sends the request.
|
|
4
|
+
|
|
5
|
+
Skip vendored and generated code (`node_modules/`, `.venv/`, `vendor/`, `dist/`, `build/`). List calls in tests separately: a test that calls a live model on every run is itself a finding candidate (LP-GE-06).
|
|
6
|
+
|
|
7
|
+
## SDKs and frameworks
|
|
8
|
+
|
|
9
|
+
| Shape | Language | What to search for | Provider |
|
|
10
|
+
|---|---|---|---|
|
|
11
|
+
| `anthropic` | Python | `import anthropic`, `from anthropic import`, `Anthropic(`, `AsyncAnthropic(`, `AnthropicBedrock(`, `AnthropicVertex(`, `messages.create(`, `messages.stream(` | Anthropic, or Bedrock or Vertex when those clients are used |
|
|
12
|
+
| `@anthropic-ai/sdk` | TS/JS | `from "@anthropic-ai/sdk"`, `new Anthropic(`, `messages.create(`, `messages.stream(` | Anthropic |
|
|
13
|
+
| `anthropic-sdk-go` | Go | `github.com/anthropics/anthropic-sdk-go`, `Messages.New(`, `Messages.NewStreaming(` | Anthropic |
|
|
14
|
+
| `openai` | Python | `from openai import`, `OpenAI(`, `AsyncOpenAI(`, `AzureOpenAI(`, `chat.completions.create(`, `responses.create(`, `batches.create(` | Whatever `base_url` points at (below) |
|
|
15
|
+
| `openai` | TS/JS | `from "openai"`, `new OpenAI(`, `chat.completions.create(`, `responses.create(`, `batches.create(` | Whatever `baseURL` points at |
|
|
16
|
+
| `openai-go`, `go-openai` | Go | `github.com/openai/openai-go`, `github.com/sashabaranov/go-openai`, `Chat.Completions.New(`, `CreateChatCompletion(` | Whatever the base URL points at |
|
|
17
|
+
| `google-genai` | Python | `from google import genai`, `genai.Client(`, `models.generate_content(`, `models.generate_content_stream(`, `caches.create(`; the older `google.generativeai` package too | Gemini |
|
|
18
|
+
| `@google/genai` | TS/JS | `from "@google/genai"`, `new GoogleGenAI(`, `models.generateContent(` | Gemini |
|
|
19
|
+
| `google.golang.org/genai` | Go | `genai.NewClient(`, `Models.GenerateContent(` | Gemini |
|
|
20
|
+
| LangChain | Python, TS/JS | `langchain_openai`, `langchain_anthropic`, `langchain_google_genai`, `@langchain/openai`, `@langchain/anthropic`, `ChatOpenAI(`, `ChatAnthropic(`, `.invoke(`, `.ainvoke(`, `.stream(`, `.batch(`, `create_react_agent(`, `AgentExecutor(` | The chat model class and its `base_url` |
|
|
21
|
+
| LangChain (Go) | Go | `github.com/tmc/langchaingo`, `llms.GenerateFromSinglePrompt(`, `GenerateContent(` | The model package imported |
|
|
22
|
+
| LlamaIndex | Python, TS/JS | `llama_index.llms`, `from llama_index.core import Settings`, `Settings.llm`, `llamaindex`, `.complete(`, `.chat(`, `as_query_engine(`, `as_chat_engine(` | The LLM class configured in `Settings` |
|
|
23
|
+
| LiteLLM | Python | `import litellm`, `litellm.completion(`, `litellm.acompletion(`, `litellm.batch_completion(`, `Router(`; a LiteLLM proxy is reached through the `openai` SDK with a `base_url` on the proxy | The `model` string prefix (`anthropic/`, `openai/`, `gemini/`, `hosted_vllm/` ...) |
|
|
24
|
+
| Vercel AI SDK | TS/JS | `from "ai"`, `generateText(`, `streamText(`, `generateObject(`, `streamObject(`, `@ai-sdk/openai`, `@ai-sdk/anthropic`, `@ai-sdk/google`, `@openrouter/ai-sdk-provider` | The provider package and model passed to `model:` |
|
|
25
|
+
|
|
26
|
+
Agent frameworks built on these (CrewAI, AutoGen, the OpenAI Agents SDK, Mastra, Pydantic AI and others) end in one of the shapes above; search for the framework's agent or model class, then find where it sets the model and the base URL.
|
|
27
|
+
|
|
28
|
+
## Raw HTTP
|
|
29
|
+
|
|
30
|
+
A raw HTTP client rarely writes the whole endpoint in one string. The base URL usually already ends in `/v1` (or another version prefix), and the code appends only the rest: `${base}/chat/completions`, `base + "/chat/completions"`, `f"{base}/chat/completions"`, `urljoin(base, "chat/completions")`. A search for the full literals (`/v1/chat/completions`, `/v1/responses`, `/v1/messages`) finds only the rarer, fully written form. Search for the path without the version, and for the request body, as well.
|
|
31
|
+
|
|
32
|
+
| Endpoint path | Dialect | Typical callers |
|
|
33
|
+
|---|---|---|
|
|
34
|
+
| `chat/completions` | OpenAI Chat Completions | OpenAI, OpenRouter, DeepInfra, DeepSeek, Groq, Together, Azure, vLLM, SGLang, LiteLLM proxy, LM Warden |
|
|
35
|
+
| `/responses` | OpenAI Responses | OpenAI |
|
|
36
|
+
| `/messages` | Anthropic Messages | Anthropic, and routers that accept the Anthropic dialect |
|
|
37
|
+
| `/completions` | OpenAI legacy completions | self-hosted engines, older code |
|
|
38
|
+
| `:generateContent`, `:streamGenerateContent` | Gemini native | Gemini |
|
|
39
|
+
| `/batches`, `/messages/batches`, `:batchGenerateContent` | Batch APIs | bulk jobs (LP-GE-07 is about the jobs that do not use them) |
|
|
40
|
+
|
|
41
|
+
Each path can sit behind a version (`/v1/chat/completions`) or not (`${base}/chat/completions`), inside a string literal, a template literal (`${base}/messages`), a concatenation (`base + "/responses"`) or a URL builder.
|
|
42
|
+
|
|
43
|
+
Run both searches (the second has one pattern per language). In the patterns, `\x27` stands for a single quote, so a pattern can sit inside single quotes in a shell.
|
|
44
|
+
|
|
45
|
+
1. The path, in any language: the full literal and the versionless suffix.
|
|
46
|
+
|
|
47
|
+
```
|
|
48
|
+
rg -n 'chat/completions|/(responses|completions|batches|messages(/batches)?)["`\x27?]|/v1/(responses|messages|completions|batches)|:(stream|batch)?[gG]enerateContent' -g '!{node_modules,.venv,vendor,dist,build}/**'
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
2. The request body near the call, when the URL is in a variable and the path never appears next to the call. Shapes: Python `requests.post(`, `httpx.post(`, `httpx.AsyncClient(`, `aiohttp`; TS/JS `fetch(`, `axios.post(`, `got.post(`, `ky.post(`, `undici.request(`; Go `http.NewRequest(`, `http.Post(`, `resty`. A `messages` list in the JSON body, next to one of them, confirms an LLM call.
|
|
52
|
+
|
|
53
|
+
```
|
|
54
|
+
rg -n -U '(?s)(fetch|axios|got|ky|undici)[.(].{0,600}["`\x27]?messages["`\x27]?\s*[:,}]' -g '*.{ts,tsx,js,jsx,mjs,cjs}' -g '!{node_modules,dist,build}/**'
|
|
55
|
+
rg -n -U '(?s)(requests|httpx|aiohttp|session|client)\.(post|request|stream)\(.{0,600}["\x27]messages["\x27]\s*:' -g '*.py' -g '!{.venv,venv,dist,build}/**'
|
|
56
|
+
rg -n -U '(?s)http\.(NewRequest|Post)\w*\(.{0,600}"messages"' -g '*.go' -g '!vendor/**'
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
The patterns are for `rg`. With plain `grep -E`, search for the paths of the first pattern only, typing a single quote in place of `\x27`, and read each file that imports an HTTP client for the body.
|
|
60
|
+
|
|
61
|
+
A hit is a candidate, not a call. A doc comment, a test string, a log line, or a route the app serves itself (`app.get("/messages")`) also matches. Open each hit and confirm it is a request the app sends to a model (a URL it calls, a body with `messages` and `model`) before it goes into the inventory; and when the only hit in a file is a comment, search the file's HTTP calls by hand, since the real call may be written another way.
|
|
62
|
+
|
|
63
|
+
## The app's own wrapper
|
|
64
|
+
|
|
65
|
+
Most apps call the SDK in one or two helper functions (`call_llm`, `askModel`, `client.ts`). When a hit is inside such a helper, the call site the user cares about is each caller of the helper: list the callers (`rg -n 'call_llm\('`) and audit each one, because each passes its own system prompt, tools and history. Record the helper's line as well, since retry, timeout and parsing findings (LP-GE-04, LP-GE-05, LP-GE-10) usually live there.
|
|
66
|
+
|
|
67
|
+
## Which provider and model
|
|
68
|
+
|
|
69
|
+
1. The SDK or provider package, from the table above.
|
|
70
|
+
2. The base URL: `base_url`, `baseURL`, `OPENAI_BASE_URL`, `ANTHROPIC_BASE_URL`, or a URL constant in config. A host such as `api.openai.com`, `api.anthropic.com`, `openrouter.ai`, `api.deepinfra.com` or `generativelanguage.googleapis.com` names the provider. A URL on the user's own hosts (localhost, a private name or address) is a self-hosted engine; read the launch files (`docker-compose.yml`, Kubernetes manifests, `vllm serve`, `python -m sglang.launch_server`) to tell vLLM, SGLang, llama.cpp or LM Warden apart.
|
|
71
|
+
3. The model string: a router prefix such as `anthropic/` or `google/` means the upstream is that provider even though the SDK is `openai` (the cache marks then matter: LP-PC-01).
|
|
72
|
+
4. Environment and config files (`.env.example`, `settings.py`, `config.ts`) when the model or URL is read from a variable.
|
|
73
|
+
|
|
74
|
+
When these disagree, or the value comes only from the environment at run time, write "unknown" in the inventory and ask (see [presenting.md](presenting.md)); `leanprompt.yaml` settles it for the next run ([docs/profile.md](../../docs/profile.md)).
|
|
75
|
+
|
|
76
|
+
## Call kind
|
|
77
|
+
|
|
78
|
+
Each inventory row gets one kind. The kind decides which rules apply and how many calls share a prefix.
|
|
79
|
+
|
|
80
|
+
| Kind | How it looks in code | What it means for reuse |
|
|
81
|
+
|---|---|---|
|
|
82
|
+
| chat | A message list kept per user or session and appended to on each turn; a request handler that loads history, adds the new message and calls the model | Each turn should extend the last one; the prefix grows. History rules (LP-PC-06, LP-PC-08) apply. |
|
|
83
|
+
| agent loop | A `while`/`for` loop that calls the model, runs the tool calls it returns (`stop_reason == "tool_use"`, `finish_reason == "tool_calls"`, `tool_calls` in the response) and calls again; framework agents (`AgentExecutor`, `create_react_agent`, `maxSteps` or `stopWhen` in the Vercel AI SDK) | Many calls per task with a long fixed head of system prompt and tools; head and tool rules (LP-PC-03, LP-PC-04, LP-PC-05, LP-PC-09) matter most. |
|
|
84
|
+
| one-shot | One call per input, no history: classify, extract, summarise, title | Reuse only across inputs, through a shared head; small calls may suit a smaller model (LP-GE-08). |
|
|
85
|
+
| batch | A loop, `map`, `gather` or `Promise.all` over a dataset; a scheduled or nightly job; a batch API | Many calls with the same head in a short time; batch APIs and sample counts apply (LP-GE-01, LP-GE-02, LP-GE-07). |
|
|
86
|
+
|
|
87
|
+
A call can be several kinds at once (an agent loop run nightly over a dataset): record the main one and note the other.
|
|
88
|
+
|
|
89
|
+
## Following a call to where its prompt is built
|
|
90
|
+
|
|
91
|
+
From each call site, trace the arguments back:
|
|
92
|
+
|
|
93
|
+
- **System prompt:** the string or builder passed as `system`, the first `system` message, or `instructions`. Look for f-strings, template literals, `.format(`, `datetime.now()`, `new Date()`, user or tenant ids, paths, versions, and retrieved text in it.
|
|
94
|
+
- **Tools:** the list passed as `tools` or `functions`; the registry or MCP client that produces it, and whether its order is fixed.
|
|
95
|
+
- **History:** where the message list is stored, loaded, trimmed, summarised or rewritten between turns.
|
|
96
|
+
- **Request options:** `max_tokens`, `thinking`, `reasoning_effort`, `temperature`, `n`, `tool_choice`, `prompt_cache_key`, `cache_control`, timeouts and retries (on the client and in decorators around the call).
|
|
97
|
+
|
|
98
|
+
The rule files of [prefill-cache](../prefill-cache/SKILL.md), [generation-economy](../generation-economy/SKILL.md), [prompt-diet](../prompt-diet/SKILL.md) and [lmwarden](../lmwarden/SKILL.md) give the `rg` patterns and code shapes for each rule; use them once the call sites are known.
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
# Presenting the audit
|
|
2
|
+
|
|
3
|
+
leanprompt has no interface of its own. The conversation with you, the user's coding assistant, is the interface: you show the results, ask the questions and apply the fixes. This page says how.
|
|
4
|
+
|
|
5
|
+
## Summary first
|
|
6
|
+
|
|
7
|
+
Lead with a summary first, in three or four lines, before any detail: how many call sites the audit found, how many findings, the score with its kind (static, static calibrated, or measured), and the single biggest leak with its file:line and its tokens lost per 1,000 calls. Then stop and offer to go through the findings. Do not open with the inventory table or the rule list.
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
leanprompt audit: <n> call sites, <n> findings, score <score> <kind>.
|
|
11
|
+
Biggest leak: <rule id> <rule title> at <file>:<line>, about <tokens> tokens lost per 1,000 calls (<estimate | measured, N calls>).
|
|
12
|
+
Full report written to leanprompt-report.md. Go through the findings one by one?
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## One finding at a time
|
|
16
|
+
|
|
17
|
+
Go through the findings one at a time, in ranked order. Present each one as a decision: the rule id and title, file:line, the tokens it loses per 1,000 calls with the kind of that number, one sentence on what the code does there, and the one fix you propose. Then offer exactly four choices: `fix now`, `explain more`, `skip`, `don't flag this again`.
|
|
18
|
+
|
|
19
|
+
- `fix now`: show the fix as a small diff and apply it. If the fix moves or rewords content, ask the reorder question below first. `fix now` consents to that diff only. To prove it, ask the user to run the before and after scenario, or ask whether you may run it yourself and say that it sends real requests to the provider, which are billed. Offer the stable-head test as its own small diff, and add it only after the user says yes.
|
|
20
|
+
- `explain more`: explain the rule's "Why" and "Don't break meaning" in plain words, using the lines from this code, and link the rule file. Then offer the same four choices again.
|
|
21
|
+
- `skip`: leave the finding open (Status: skipped in the report) and move on. The next audit reports it again.
|
|
22
|
+
- `don't flag this again`: see below.
|
|
23
|
+
|
|
24
|
+
Choosing `don't flag this again` writes an `ignore:` entry to `leanprompt.yaml`, the rule id and the file exactly as they appear in `.leanprompt/findings.json`, for example `{rule: LP-PC-03, file: src/agent/prompt.ts}`. Append it to the `ignore:` list, create the list (or the file) if it is missing, and keep every other key and comment as it was. The entry covers that rule in that whole file, not one line. From then on the audit does not report it, and `npx leanprompt score` leaves it out of the static score (as does `leanprompt calibrate`); the measured score is unaffected, because it reads the usage log, not the findings. The user undoes it by deleting the line. Tell the user which line you added.
|
|
25
|
+
|
|
26
|
+
Present each open question (a finding in `"<external>"` or with `status: "needs-facts"`) in its place in the ranking, marked as an open question: say where it lives, the tokens it would lose with the kind of that number, and its `confirm` text as the question to settle. If the user gives the fact and it confirms the finding, drop `status` and go on with the four choices; if it dismisses the finding, remove it from `.leanprompt/findings.json` and rescore; if the user does not know yet, leave it open: it stays in the score and in the report's "Open questions".
|
|
27
|
+
|
|
28
|
+
Accept a short answer: the choice's words, its number, or "yes" for `fix now`. After the last finding, say what changed: fixed, skipped and ignored counts, and the new score with its kind.
|
|
29
|
+
|
|
30
|
+
## Asking questions
|
|
31
|
+
|
|
32
|
+
When you have your own question tool, use it: in Claude Code, the option prompts of its question tool (`AskUserQuestion`), which show the choices as options the user picks from. Without one, write numbered choices in text, one per line, and accept the number or the words as the answer. Ask one question at a time.
|
|
33
|
+
|
|
34
|
+
Ask only what the code cannot answer. Read everything you can first: the SDK, the base URL, the model names, the launch files, `leanprompt.yaml`. The questions that are usually left:
|
|
35
|
+
|
|
36
|
+
- **The priority** (cost, speed or quality, or weights), when `leanprompt.yaml` is absent or has no `priority`. It decides the order of the advice; caching applies whatever the answer.
|
|
37
|
+
- **Whether a reorder may change answers,** before a fix that moves content (LP-PC-02, LP-PC-07, or LP-PC-03 when a value moves to a later message). Moving a date away from the text that refers to it is the known failure (E6). Say what would move and where.
|
|
38
|
+
- **Whether a trim may cut something the model needs,** before a fix that removes content (an `LP-PD-*` finding: a tool, an instruction, part of a tool result, old turns). Say what would be removed and from which calls, that the fix ships only after an answer check, and, when it touches the cached head, what the one-time cache loss is. Stripping reasoning from history is the known failure here (E11).
|
|
39
|
+
- **The provider or model,** only when the code reads it from the environment at run time and nothing else names it.
|
|
40
|
+
|
|
41
|
+
Offer to save each answer to `leanprompt.yaml` so it is never asked twice: show the lines that would be written (the priority under `priority:`, the provider or engine under `target:`, or one entry per backend under `targets:` when the app calls more than one, [docs/profile.md](../../docs/profile.md)) and write them only on a yes. Answering a question is not consent to writing the file; if the user declines, keep the answer for this session only. The file accepts only `target` (or `targets`), `engine`, `priority` and `ignore`, and any other key makes leanprompt stop with `unknown key`, so do not add keys of your own. A "no, the order matters" to a reorder question can be saved, on the same offer, as an `ignore:` entry for that rule and file, so the content stays where it is. A "yes" needs no entry: the fix is made, with its answer check, and the finding is gone.
|
|
42
|
+
|
|
43
|
+
## Fixes and proofs
|
|
44
|
+
|
|
45
|
+
Show each fix as a small diff: only the lines that change, in a `diff` block, with the file path. One fix per finding, the smallest one in the rule's "Fix", and no refactoring around it. If the fix needs an answer check, say which one before you apply it.
|
|
46
|
+
|
|
47
|
+
```diff
|
|
48
|
+
--- a/src/agent/prompt.ts
|
|
49
|
+
+++ b/src/agent/prompt.ts
|
|
50
|
+
-const systemPrompt = (now: Date) => `Current time: ${now.toISOString()}\n${BASE_PROMPT}`;
|
|
51
|
+
-const userText = (text: string, _now: Date) => text;
|
|
52
|
+
+const systemPrompt = (_now: Date) => BASE_PROMPT;
|
|
53
|
+
+const userText = (text: string, now: Date) =>
|
|
54
|
+
+ `<environment>\nCurrent time: ${now.toISOString()}\n</environment>\n\n${text}`;
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
The time still reaches the model, in the newest message, so a question about the date can still be answered; this is the LP-PC-03 fix in the `dated-chat` example app, and it is a move, so it gets the reorder question and an answer check first.
|
|
58
|
+
|
|
59
|
+
Show each proof as a before/after line, one per field, in the form `cached_tokens: 0 → 18,432`, with the numbers from your own before and after runs of the same scenario. Use the field the provider reports (`cache_read_input_tokens` on Anthropic; the table is in [measure-loop](../measure-loop/SKILL.md)), and add the generation fields when the fix is a generation one (`output_tokens`, retries, `finish: "length"` counts). Name the run each number came from. When the proof is a kvsig id, say which id stayed equal across which two inputs.
|
|
60
|
+
|
|
61
|
+
## Offering to share a lesson
|
|
62
|
+
|
|
63
|
+
After the last finding, if one fix now has a measured before and after, or a rule misled the user, add one line offering to share it as a "lesson learned": "If you like, `npx leanprompt lesson` drafts a short, general-terms write-up on your machine. You read the exact text and open the GitHub issue yourself; nothing is sent." The user reads the exact text and opens the issue themselves. Offer it once and accept a no. Run `npx leanprompt lesson --rule <id>` only after the user says yes, then point them at `.leanprompt/lesson.md` and the link it prints. Do not offer it for a static score alone, and never paste anything the user removed from the draft. A maintainer reads every submission before it informs a rule; credit is optional ([THANKYOU.md](../../docs/THANKYOU.md)).
|
|
64
|
+
|
|
65
|
+
## The page, the hand-off and sharing
|
|
66
|
+
|
|
67
|
+
After the summary, run `npx leanprompt report --html` and give the user the path it prints. It writes one local, self-contained page, `.leanprompt/report.html`, for the person who reads the audit rather than the conversation: a plain-English headline, what the findings cost (in money only when `leanprompt.yaml` has a volume and a dated price), one card per finding built from its `problem`, `change`, `why`, `estimate`, `assumptions` and `verify`, then the score. Write those fields for every finding: the page is only as clear as they are. When there are more than 10 findings, or the user wants to share the result, point at the page first.
|
|
68
|
+
|
|
69
|
+
The page's "Fix it with your coding agent" block is for a user who reads the page later, or in another tool: it is self-contained instructions (install leanprompt if it is missing, read the findings, check each against the code, fix one at a time with the user's yes, prove each with `measure-loop`) and the list of findings. If you are already going through the findings with the user, say so and carry on; the block is for a fresh session.
|
|
70
|
+
|
|
71
|
+
The page asks for a star or a word to a colleague only after it has shown an estimate or a measured score, and offers the README badge only when the repository's remote is on GitHub, GitLab.com or Bitbucket. Do not ask for either yourself. The Markdown report, `leanprompt-report.md`, stays the record either way.
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
# Report template: `leanprompt-report.md`
|
|
2
|
+
|
|
3
|
+
Write the report at the project root with the sections below, in this order. It follows the same order as the page `npx leanprompt report --html` writes: what is wrong and what it costs first, in plain English, then the hand-off for a coding agent, then the score and the detail. Replace every `<...>`; leave no placeholder in the written report. Keep the rule text out of it: link the rule file instead. The same content is what you present in the conversation ([presenting.md](presenting.md)); the file is the record.
|
|
4
|
+
|
|
5
|
+
The plain-English lines come from each finding's fields in `.leanprompt/findings.json` (`problem`, `change`, `why`, `estimate`, `assumptions`, `verify`), so the report, the page and the hand-off block say the same thing. Write them for a person who has not read the rule: no rule ids in the sentences, no jargon.
|
|
6
|
+
|
|
7
|
+
````markdown
|
|
8
|
+
# leanprompt report: <project name>
|
|
9
|
+
|
|
10
|
+
<date> · leanprompt <version> · target: <provider or engine, model family> · priority: <cost | speed | quality | weights>
|
|
11
|
+
|
|
12
|
+
**<n> places where this app pays for tokens it doesn't need.** The biggest: <rule title, plain> at <file>:<line>, about <tokens> tokens per 1,000 calls. Together about <total tokens> tokens per 1,000 calls (<"estimate from the code, not a measurement" | "measured over N calls">).<If there are open questions:> Plus <n> open questions to confirm.
|
|
13
|
+
|
|
14
|
+
## What this costs you
|
|
15
|
+
|
|
16
|
+
<With `volume:` and a dated price in leanprompt.yaml:>
|
|
17
|
+
About <$X> a month at <N> calls a month. Fixing these saves about <$X> a month (about <Y> of an estimated <$B> monthly bill). <Self-hosted, with `prefill_tokens_per_second`: about <H> hours of GPU prefill time a month, and <+s> on the first-token time of the calls the prefill findings affect.>
|
|
18
|
+
|
|
19
|
+
Inputs: volume <N> calls a month (<source>); <model> input <$>, cached input <$>, output <$> per 1M tokens, from <pricing page URL or the user's source>, checked <date>; average call <prompt> prompt and <output> output tokens. Every figure is an estimate from the code, not a measurement (or: measured over N calls).
|
|
20
|
+
|
|
21
|
+
<Without them:> Tokens per 1,000 calls only. To see this in money, add `volume: {calls_per_month: N}` and `prices:` for <model> (input, cached_input, output per 1M tokens, with source and checked date) to `leanprompt.yaml`. leanprompt never invents a volume or a price.
|
|
22
|
+
|
|
23
|
+
| Finding | Where | Tokens per 1,000 calls | A month |
|
|
24
|
+
|---|---|---|---|
|
|
25
|
+
| <rule id> | <file>:<line> | <n prompt, n not cached, n output> | <$, or blank without volume and price> |
|
|
26
|
+
|
|
27
|
+
## What's wrong and what to change
|
|
28
|
+
|
|
29
|
+
Largest first, by estimated tokens lost per 1,000 calls. Findings that change price or latency but not tokens follow, in the order the priority gives them.
|
|
30
|
+
|
|
31
|
+
### 1. <problem, in a few words> · <file>:<line>
|
|
32
|
+
|
|
33
|
+
- **Problem:** <`problem`: what is wrong, one or two plain sentences>
|
|
34
|
+
- **What to change:** <`change`; a short diff if it fits>
|
|
35
|
+
- **Why it matters:** <`why`: why it costs tokens or time>
|
|
36
|
+
- **Estimate:** <`estimate`>, tokens lost per 1,000 calls (<estimate | measured, N calls>)
|
|
37
|
+
- **Assumes:** <`assumptions`: call mix, tokens per call, how often this path runs>
|
|
38
|
+
- **Share:** <0.000> of <prompt | output> tokens = <tokens lost per 1,000 calls> ÷ <that side's tokens for the same 1,000 calls>. <Or: "severity default share: no estimate possible, because <reason>">
|
|
39
|
+
- **Don't break meaning:** <the rule's check for this fix, or "caching only: answers cannot change">
|
|
40
|
+
- **How to check the fix:** <`verify`: the usage field that must change and the kvsig id that must stay equal>; proved with `measure-loop`
|
|
41
|
+
- **Rule:** [<rule id> <rule title>](<link to the rule file>)
|
|
42
|
+
- **Status:** <open | fixed, with the before and after line | skipped | ignored in leanprompt.yaml>
|
|
43
|
+
|
|
44
|
+
### Open questions
|
|
45
|
+
|
|
46
|
+
Findings outside this repository (`"<external>"`) or waiting on a fact (`needs-facts`), ranked the same way. They count in the score. Confirm or dismiss each one with its fact. Leave this heading out when there are none.
|
|
47
|
+
|
|
48
|
+
#### <n>. <problem, in a few words> · <where, for example "engine launch flags">
|
|
49
|
+
|
|
50
|
+
- **Problem:** <`problem`: why it may apply>
|
|
51
|
+
- **To confirm:** <the `confirm` text: the fact that would confirm or dismiss it, and where the user can read it>
|
|
52
|
+
- **Change, if confirmed:** <`change`>
|
|
53
|
+
- **Estimate:** <`estimate`> (estimate); <what it assumes about the missing fact>
|
|
54
|
+
- **Rule:** [<rule id> <rule title>](<link to the rule file>)
|
|
55
|
+
- **Status:** <open question | confirmed | dismissed>
|
|
56
|
+
|
|
57
|
+
## Fix it with your coding agent
|
|
58
|
+
|
|
59
|
+
Paste this into Claude Code, Codex, Cursor or any coding assistant. It checks each finding against the code and proposes fixes one at a time, asking before it changes anything.
|
|
60
|
+
|
|
61
|
+
```text
|
|
62
|
+
Please check and fix the LLM-call findings from a leanprompt audit of this repository.
|
|
63
|
+
|
|
64
|
+
1. If the leanprompt skills are not installed for you here, install them: npx github:Podwarden/leanprompt install
|
|
65
|
+
2. Read .leanprompt/findings.json and leanprompt-report.md. If they are missing, use the list below.
|
|
66
|
+
3. Check each finding against the code before you change anything. The audit can be wrong: if a finding does not hold, tell me why and leave that code alone.
|
|
67
|
+
4. Fix one finding at a time. Show me the change as a small diff and apply it only after I say yes.
|
|
68
|
+
5. Prove each fix with the measure-loop skill: a before and after on the same scenario. Ask me before running anything that sends real, billed requests.
|
|
69
|
+
6. When a fix is proved, set "fixed": true on its finding in .leanprompt/findings.json and run npx github:Podwarden/leanprompt score.
|
|
70
|
+
|
|
71
|
+
Findings, largest first:
|
|
72
|
+
1. <rule id> at <file>:<line>: <problem>
|
|
73
|
+
|
|
74
|
+
Open questions (confirm before fixing):
|
|
75
|
+
- <rule id> (<where>): <problem> To confirm: <confirm>
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Score
|
|
79
|
+
|
|
80
|
+
<score> <kind>, from <".leanprompt/findings.json" | ".leanprompt/usage.jsonl, N calls (M unmeasured)">, <default | calibrated> weights. One number from 0 to 100 for how well the app avoids paying for the same tokens twice; higher is better.
|
|
81
|
+
|
|
82
|
+
<Static only:> <N> of <M> findings use a default share (`default_shares` in `.leanprompt/score.json`), the rest an estimated one.
|
|
83
|
+
|
|
84
|
+
| Input | Value | Meaning |
|
|
85
|
+
|---|---|---|
|
|
86
|
+
| E | <0.00> | prefill reuse (measured), or the prefill term from the findings (static) |
|
|
87
|
+
| S | <0.00> | prefix stability (measured); 1 in a static score |
|
|
88
|
+
| G | <0.00> | share of output tokens wasted |
|
|
89
|
+
|
|
90
|
+
<Measured only:> Heads: <distinct_head> distinct heads over <conversations> conversations. <One line: expected, or which finding it points to.>
|
|
91
|
+
|
|
92
|
+
<Static only:> This score is an estimate from code. A trial run with `npx leanprompt calibrate` fits it to this app.
|
|
93
|
+
|
|
94
|
+
Money is not part of the score.
|
|
95
|
+
|
|
96
|
+
## Inventory
|
|
97
|
+
|
|
98
|
+
| # | File | Provider | Model | Call kind | Notes |
|
|
99
|
+
|---|---|---|---|---|---|
|
|
100
|
+
| 1 | <path>:<line> | <provider, or "unknown: asked"> | <model> | <chat · agent loop · one-shot · batch> | <wrapper it goes through, router, framework> |
|
|
101
|
+
|
|
102
|
+
## Next steps
|
|
103
|
+
|
|
104
|
+
1. <The fix to do first and why: the biggest leak, or the one the priority favours>
|
|
105
|
+
2. <Prove it with `measure-loop`: the scenario to run, the field to watch>
|
|
106
|
+
3. <Turn on the usage logger to get a measured score, if there is no log yet>
|
|
107
|
+
4. <Calibrate the static score, if it is static>
|
|
108
|
+
5. <Add volume and prices to `leanprompt.yaml`, if the report shows tokens only>
|
|
109
|
+
6. <The page: `npx leanprompt report --html` writes `.leanprompt/report.html` with the same content and the copyable hand-off block>
|
|
110
|
+
````
|
|
111
|
+
|
|
112
|
+
Write the numbers with their kind every time: "(estimate)" next to a figure from code, "(measured, N calls)" next to a figure from the usage log. A static score is never presented as measured, and money is shown only from the user's own volume and a price with its source and checked date; never invent either.
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: lmwarden
|
|
3
|
+
description: Use when an app calls a model it hosts itself (vLLM, SGLang, llama.cpp, LM Warden or another OpenAI-compatible server on your own GPUs) and prefix-cache reuse is low, a hybrid model reuses only part of a prompt, several replicas serve one model, or several apps or tenants share one server; also when deciding whether to self-host at all. Covers engine settings that change reuse, keeping a conversation on the replica that holds its cache, keys and cache isolation, and reading the engine facts from LM Warden into leanprompt.yaml.
|
|
4
|
+
license: CC-BY-4.0
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# lmwarden
|
|
8
|
+
|
|
9
|
+
What to do when the model runs on your own hardware: when that is the right choice, which engine settings change prefix-cache reuse, how to keep a conversation on the replica that holds its cache, and how to share one server between apps without mixing their usage or their caches. Three rules, `LP-LW-01` to `LP-LW-03`, each in its own file under `rules/`.
|
|
10
|
+
|
|
11
|
+
LM Warden is the self-hosted server the LM Warden Team makes, and it is one option among several here. The rules apply to any self-hosted engine unless a rule says otherwise. The `prefill-cache` skill covers the prompt itself; this skill covers the server it is sent to.
|
|
12
|
+
|
|
13
|
+
## When to use
|
|
14
|
+
|
|
15
|
+
- The app calls a model on hardware you run, and the cached share of prompt tokens is low.
|
|
16
|
+
- A hybrid model reuses only part of a long prompt, or reuse falls short of what kvsig says was reusable.
|
|
17
|
+
- One model runs as several replicas, and conversations reuse less than they should.
|
|
18
|
+
- Several apps or tenants use one server and you need per-consumer usage, or need to keep their caches apart.
|
|
19
|
+
- You are deciding whether to self-host at all.
|
|
20
|
+
- The `llm-call-audit` skill sends you here for an `LP-LW-*` finding.
|
|
21
|
+
|
|
22
|
+
Caching never changes answers, so these rules apply whatever the project's priority is. A change to routing or engine flags is an operations change: propose it and ask before editing a server's launch configuration.
|
|
23
|
+
|
|
24
|
+
## Does self-hosting pay
|
|
25
|
+
|
|
26
|
+
Self-hosting tends to pay when traffic is steady, many requests share a long prefix, the data must not leave your host, and you already own NVIDIA GPUs. It tends not to pay with no GPU, with spiky and low traffic (an idle GPU still costs), or when the work needs a frontier model that cannot be self-hosted. This skill does not price either side; the cost of a hosted call comes from [providers/](../../providers/) and the cost of a GPU from your own bill.
|
|
27
|
+
|
|
28
|
+
## The options
|
|
29
|
+
|
|
30
|
+
| Option | What it is | What this repo has on it |
|
|
31
|
+
|---|---|---|
|
|
32
|
+
| vLLM | Inference engine with automatic prefix caching in blocks | [providers/vllm.md](../../providers/vllm.md) (E9) |
|
|
33
|
+
| SGLang | Inference engine with a radix-tree prefix cache | [providers/sglang.md](../../providers/sglang.md), documented, not yet measured here |
|
|
34
|
+
| llama.cpp | Inference engine for GGUF models, CPU or GPU | accepted as `target.engine` in [leanprompt.yaml](../../docs/profile.md); no cache table yet |
|
|
35
|
+
| Ollama | Local model runner built on llama.cpp | no table here |
|
|
36
|
+
| LM Warden | A server that runs vLLM and llama.cpp behind one OpenAI-compatible port on your NVIDIA GPUs | its facts are read from its own API (below); it uses the vLLM table |
|
|
37
|
+
| Hosted APIs | Anthropic, OpenAI, Gemini, OpenRouter, DeepInfra | [providers/](../../providers/) |
|
|
38
|
+
|
|
39
|
+
Pick on your hardware, models and operations, not on this table. Running vLLM or SGLang directly is a reasonable choice when you want one engine and already have the tooling around it.
|
|
40
|
+
|
|
41
|
+
### What LM Warden adds, and what it does not
|
|
42
|
+
|
|
43
|
+
It adds:
|
|
44
|
+
|
|
45
|
+
- **Lifecycle.** Models are started, stopped and switched from one control plane instead of by hand-written launch commands.
|
|
46
|
+
- **Per-key accounting.** A key per consumer, each with its own usage figures (LP-LW-03).
|
|
47
|
+
- **Cache-aware routing.** For a model that runs as several data-parallel vLLM replicas, a conversation is placed on one replica and kept there (LP-LW-02).
|
|
48
|
+
|
|
49
|
+
It does not:
|
|
50
|
+
|
|
51
|
+
- **Make a model faster.** The engine does the generation; LM Warden does not change it. What E10 measures is reuse of a cache that would otherwise be rebuilt.
|
|
52
|
+
- **Span hosts.** It is one host.
|
|
53
|
+
- **Run without NVIDIA GPUs.** It is NVIDIA only, so a Mac, an AMD card or a CPU-only box is a different choice from the table above.
|
|
54
|
+
|
|
55
|
+
The routing result, with its limits (E10): on one box of four NVIDIA RTX A4000 cards serving Qwen3-4B, under a synthetic Claude Code-shaped load of 8 concurrent agent sessions with one run per arm, cache-aware routing took the median time to first byte from 2.33 s to 0.48 s, the share of prompt tokens served from cache from 44% to 86%, and output tokens a minute up 29% (8,364 to 10,752) (E10). At 24 and more sessions, where the cards were overloaded either way, the median time to first byte was worse with routing on (E10). It is an engine result, measured by LM Warden's authors, and not something a leanprompt rule achieves. Measure your own workload with routing on and off.
|
|
56
|
+
|
|
57
|
+
## Workflow
|
|
58
|
+
|
|
59
|
+
1. **Know the target.** Read `leanprompt.yaml` (`target.engine`, `engine:`; or the engine entries of `targets` when the app also calls a hosted API). If the project has none, infer the server from `base_url` and the launch files, and ask if it is unclear.
|
|
60
|
+
2. **Get the engine facts.** For LM Warden, let the CLI read them instead of asking (next section). For vLLM or SGLang, read the block or page size and the speculative-decoding setting from the server's startup log and launch arguments, and put them under `engine:` ([docs/profile.md](../../docs/profile.md)).
|
|
61
|
+
3. **Check each rule,** in the order of the index below. Each rule's "Detect in code" gives `rg` patterns and code shapes for launch files and for Python, TS/JS and Go clients.
|
|
62
|
+
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 the launch configuration is not in this repository, the audit records the finding with `"file": "<external>"` and a `where`; when it hangs on an engine fact you do not have yet (the block size, the match unit), it also gets `status: "needs-facts"` and a `confirm` naming that fact.
|
|
63
|
+
5. **Verify.** Use the rule's "Verify": the usage the server reports across two requests, and the kvsig ids that must stay equal. The `measure-loop` skill turns the second into a test.
|
|
64
|
+
|
|
65
|
+
## Reading the engine facts from LM Warden
|
|
66
|
+
|
|
67
|
+
```
|
|
68
|
+
export LMWARDEN_API_KEY=... # the inference key the app already uses
|
|
69
|
+
leanprompt profile detect --lmwarden https://lm.example.com [--token-env LMWARDEN_API_KEY] [--model <name>]
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
This reads `GET <url>/api/me/engine` with the key as a bearer token and writes `block_tokens`, `match_unit_tokens` and `speculative` (true when the engine reports a speculative-decoding method) under `engine:` in `leanprompt.yaml`. It also sets `target.context_tokens` from `max_model_len` when the file does not already set it. Everything else in the file is kept. If there is no `leanprompt.yaml` it creates one with `target: {engine: lm-warden}`. In a profile with `targets:` it writes into the `lm-warden` entry (else the `vllm` entry, else it adds an `lm-warden` entry), under that entry's `engine_facts`, or under the top-level `engine:` when that block exists and the profile has one engine entry. A value the server cannot determine is left out and named in a printed note. If the key can use several models, pass `--model` or the command stops and lists their names.
|
|
73
|
+
|
|
74
|
+
Auto-detect needs an LM Warden release that has this endpoint. A server without it answers 404, and the command says so; then set the `engine:` block by hand from the engine's startup log (step 2 above). The command makes one request, to the URL you give, and never prints the key.
|
|
75
|
+
|
|
76
|
+
## Prompt Lens (planned)
|
|
77
|
+
|
|
78
|
+
Prompt Lens is planned: an LM Warden view that names the first part of a prompt where reuse broke and what the miss cost, with an API and tools for assistants. Until it ships, find the break with kvsig ids (`prefill-cache`, "Reading kvsig ids") and the engine's cache statistics.
|
|
79
|
+
|
|
80
|
+
## Rules
|
|
81
|
+
|
|
82
|
+
| Id | Rule | Severity | Evidence |
|
|
83
|
+
|---|---|---|---|
|
|
84
|
+
| [LP-LW-01](rules/LP-LW-01.md) | Turn on prefix caching and set the match unit | high | E9 |
|
|
85
|
+
| [LP-LW-02](rules/LP-LW-02.md) | Keep a conversation on the replica that holds its cache | medium | E10 |
|
|
86
|
+
| [LP-LW-03](rules/LP-LW-03.md) | One key per app or tenant; cache scope is a privacy boundary | medium | provider docs |
|
|
87
|
+
|
|
88
|
+
Evidence rows (E1 to E12) are in [docs/evidence.md](../../docs/evidence.md). A rule whose only source is documentation says "documented, not yet measured here".
|
|
89
|
+
|
|
90
|
+
## Hardware notes
|
|
91
|
+
|
|
92
|
+
A longer context and more concurrent sequences take more KV-cache memory, and the cache that holds reusable prefixes competes for the same memory; that follows from how engines work and is untested here. Put the KV memory you have under `kv_memory_gb` in `engine:` when you know it ([docs/profile.md](../../docs/profile.md)). Engine flags change over versions: read the flag's meaning in your version's documentation before changing it.
|
|
93
|
+
|
|
94
|
+
## What this skill does not do
|
|
95
|
+
|
|
96
|
+
It does not make the model faster, change how much it generates (that is `generation-economy`), or change the prompt (that is `prefill-cache`). It does not choose hardware, and it does not promise the E9 or E10 results for another model, card count or workload.
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: LP-LW-01
|
|
3
|
+
title: Turn on prefix caching and set the match unit
|
|
4
|
+
skill: lmwarden
|
|
5
|
+
applies_to: [vllm, sglang, lm-warden]
|
|
6
|
+
saves: prefill
|
|
7
|
+
severity: high
|
|
8
|
+
evidence: [E9]
|
|
9
|
+
---
|
|
10
|
+
## Rule
|
|
11
|
+
On a self-hosted engine, run with prefix caching on, and on a hybrid model set the prefix match unit (vLLM) or page size (SGLang) small enough that a prompt's tail is not thrown away.
|
|
12
|
+
|
|
13
|
+
## Why
|
|
14
|
+
A block-mode prefix cache reuses whole blocks. The part of a prompt after the last full block is recomputed on every request, and an engine that drops one more block (speculative decoding does this on the hybrid model measured) recomputes that block too. With large blocks this is most of a short prompt. On one 4B hybrid model on one 16 GB card, the block was 1,584 tokens, and short prompts reused 44% of their tokens on an append-only workload (E9). With `--prefix-match-unit 16` on vLLM 0.32 the same workload reused 76%, against an ideal of 78%, with no change in decode speed (E9). That is one model, one card and thinking off; another model, engine version or card count can differ.
|
|
15
|
+
|
|
16
|
+
What the engine documents: `--prefix-match-unit` sets the granularity at which prefix-cache keys are computed. Unset, it defaults to the greatest common divisor of the cacheable block sizes, which on hybrid Mamba models is the block size; the docs suggest 64 as a starting point. On hybrid models a hit can resume only at a block boundary of the Mamba state, and the shared-prefix checkpoint option is off by default and works only with a match unit smaller than the Mamba block ([providers/vllm.md](../../../providers/vllm.md)). SGLang matches at its `page_size`, and the radix tree splits a node for an exact boundary ([providers/sglang.md](../../../providers/sglang.md)), documented, not yet measured here. Whether prefix caching is on by default is not in the tables; check the launch arguments.
|
|
17
|
+
|
|
18
|
+
The same mechanism decides reuse in a one-shot app (a constant shared head, then a different body on every request, no history). Across requests only the full blocks inside the shared head can be reused, so a head shorter than one block reuses nothing on a block-mode engine, and when the per-request body is short, the extra block speculative decoding drops can fall inside the head too. This follows from the block mechanism measured with a block of 1,584 tokens (E9); one-shot traffic is not yet measured here. The question to ask is "is the shared head longer than one block, plus one more with speculative decoding on?", and a smaller match unit is what lowers that bar.
|
|
19
|
+
|
|
20
|
+
A non-hybrid model usually has a small block and little to gain from the match unit; the first step there is only to confirm caching is on.
|
|
21
|
+
|
|
22
|
+
## Detect in code
|
|
23
|
+
Look at how the server is launched, and at code that launches it. The client code does not show this.
|
|
24
|
+
|
|
25
|
+
Launch files (compose, Kubernetes, systemd, shell, Makefile):
|
|
26
|
+
```
|
|
27
|
+
rg -n 'vllm serve|vllm\.entrypoints|--no-enable-prefix-caching|--enable-prefix-caching|--prefix-match-unit|--enable-mamba-shared-prefix-checkpoint' .
|
|
28
|
+
rg -n 'sglang\.launch_server|--page-size|page_size' .
|
|
29
|
+
rg -n 'speculative|--speculative-config|mtp|eagle' .
|
|
30
|
+
```
|
|
31
|
+
Shapes: a `vllm serve` command with `--no-enable-prefix-caching`; a hybrid model (a Qwen model whose `chat_template` or `config.json` names Mamba or linear-attention layers) with speculative decoding on and no `--prefix-match-unit`.
|
|
32
|
+
|
|
33
|
+
Python, TS/JS, Go: code that starts an engine as a subprocess (`subprocess.Popen(["vllm", "serve", ...])`, `spawn("vllm", ...)`, `exec.Command("vllm", ...)`) carries the same arguments; apply the same patterns to its argument lists.
|
|
34
|
+
|
|
35
|
+
For a one-shot app (no chat history) on a hybrid model, estimate the shared head's length in tokens (system prompt plus tool definitions, everything before the per-request text) and compare it with the block size from the engine's startup log or `leanprompt.yaml` `engine.block_tokens`. A head shorter than one block, or shorter than two when speculative decoding is on and the per-request body is short, is a finding even when the client code is already cache-friendly.
|
|
36
|
+
|
|
37
|
+
Check the data too: a self-hosted app whose cached share is low while kvsig says the prefix was equal (`prefill-cache`, "Reading kvsig ids"), with the shortfall close to the block size.
|
|
38
|
+
|
|
39
|
+
For LM Warden the engine facts are reported by the server; run `leanprompt profile detect` (see the skill; it needs a release with that endpoint) instead of reading launch files.
|
|
40
|
+
|
|
41
|
+
## Fix
|
|
42
|
+
Confirm caching is on, then add the match unit for a hybrid model. Start from a value the engine's documentation suggests and measure; 16 is the value measured in E9, on one model.
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
# before
|
|
46
|
+
vllm serve Qwen/<hybrid-model> --speculative-config '{"method": "mtp", "num_speculative_tokens": 2}'
|
|
47
|
+
|
|
48
|
+
# after
|
|
49
|
+
vllm serve Qwen/<hybrid-model> --enable-prefix-caching --prefix-match-unit 16 \
|
|
50
|
+
--speculative-config '{"method": "mtp", "num_speculative_tokens": 2}'
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Then record what the engine reports in `leanprompt.yaml`, so the scorer uses the real granularity:
|
|
54
|
+
|
|
55
|
+
```yaml
|
|
56
|
+
target: {engine: vllm}
|
|
57
|
+
engine:
|
|
58
|
+
block_tokens: 1584
|
|
59
|
+
match_unit_tokens: 16
|
|
60
|
+
speculative: true
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Don't break meaning
|
|
64
|
+
Prefix caching does not change answers. The match unit changes what is stored and where a hit can resume, not what the model computes, but it is an engine setting with costs this skill has not measured beyond E9 (which saw no change in decode speed): watch memory headroom and decode speed after the change, and roll back if either moves. Restart the engine to apply it, which empties its cache and drops live conversations' warm prefixes. Do it in a quiet window and tell the people who use the server.
|
|
65
|
+
|
|
66
|
+
## Verify
|
|
67
|
+
(a) Send the same long conversation twice, appending a short turn each time. Before the change the second request reports cached tokens only up to a block boundary (`cached_tokens` in the usage, where the server reports it, or the engine's prefix-cache hit counters); after it, `cached_tokens` is close to the previous turn's full prompt.
|
|
68
|
+
|
|
69
|
+
(b) kvsig: the two requests have equal exact `nodes[i]` up to the previous turn. The share of the reusable prefix that was actually cached should rise toward the ideal; E9 went from 44% to 76% of prompt tokens on its workload, against 78% ideal (E9). Run the same conversation before and after, on the same model and engine version.
|
|
70
|
+
|
|
71
|
+
## Waste signal
|
|
72
|
+
Measured: raises E (provider-cached tokens over reusable tokens) for short prompts on a block-mode engine; the scorer treats the last partial block as the engine's rule and not as the app's, using the `engine:` values (docs/profile.md). A shortfall much larger than one block counts against the app. Static: a finding of severity high where a hybrid model runs with speculative decoding and no match unit, or with prefix caching turned off; low where the model is not hybrid and caching is on.
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
---
|
|
2
|
+
id: LP-LW-02
|
|
3
|
+
title: Keep a conversation on the replica that holds its cache
|
|
4
|
+
skill: lmwarden
|
|
5
|
+
applies_to: [vllm, lm-warden]
|
|
6
|
+
saves: prefill
|
|
7
|
+
severity: medium
|
|
8
|
+
evidence: [E10]
|
|
9
|
+
---
|
|
10
|
+
## Rule
|
|
11
|
+
When one model runs as several replicas, send every request of a conversation to the same replica, and send the same stable conversation key with each of them, so the cache the previous turn built is the one the next turn reads.
|
|
12
|
+
|
|
13
|
+
## Why
|
|
14
|
+
Each replica has its own prefix cache. A balancer that places each request on the least busy replica, with no memory of the conversation, sends turn two to a replica that has never seen turn one's prompt, and that replica prefills it from scratch. An agent resends its whole history every turn, so the miss is large and repeats. Placing a conversation on one replica and keeping it there gives the next turn a warm cache.
|
|
15
|
+
|
|
16
|
+
The result, with its limits (E10): on one box of four NVIDIA RTX A4000 cards serving Qwen3-4B, under a synthetic Claude Code-shaped load of 8 concurrent agent sessions with one run per arm, routing conversations to their replica took the median time to first byte from 2.33 s to 0.48 s, prompt tokens served from cache from 44% to 86%, and output tokens a minute up 29% (E10). At 24 and more sessions, where the cards were saturated either way, the median time to first byte was worse with routing on (E10). It is a result for the engine's routing on one small setup, not for a change in your code, and one run per arm is not a distribution. Measure your own load with routing on and off; LM Warden can turn it off per model.
|
|
17
|
+
|
|
18
|
+
What the app controls is the key. LM Warden's routing reads a session or conversation id from the request (for example an `X-Session-Id` header or the body's `prompt_cache_key`; its routing write-up lists the order), and without one it falls back to a hash of the first user message. A client that sends a fresh random id on every request, or none and an unstable first message, defeats it. Other balancers differ: this skill has not checked them, so read your balancer's documentation for what it keys on.
|
|
19
|
+
|
|
20
|
+
## Detect in code
|
|
21
|
+
Find code that sends requests to a multi-replica or load-balanced self-hosted endpoint and see what identifies the conversation.
|
|
22
|
+
|
|
23
|
+
Python:
|
|
24
|
+
```
|
|
25
|
+
rg -n 'itertools\.cycle|random\.choice\(.*(urls|hosts|endpoints)|base_url=.*(urls|hosts)\[' -g '*.py'
|
|
26
|
+
rg -n 'uuid4\(\)|uuid\.uuid4' -g '*.py'
|
|
27
|
+
rg -n 'prompt_cache_key|X-Session-Id|x-session-affinity|session_id' -g '*.py'
|
|
28
|
+
```
|
|
29
|
+
Shapes: a list of base URLs, one per replica, that the client cycles through per request; a `uuid4()` placed in a header or in `prompt_cache_key` on every call instead of once per conversation.
|
|
30
|
+
|
|
31
|
+
TS/JS:
|
|
32
|
+
```
|
|
33
|
+
rg -n 'randomUUID\(\)|Math\.random\(\)' -g '*.{ts,tsx,js,mjs}'
|
|
34
|
+
rg -n 'prompt_cache_key|X-Session-Id|x-session-affinity|sessionId' -g '*.{ts,tsx,js,mjs}'
|
|
35
|
+
rg -n 'baseURL|endpoints\[|urls\[.*%' -g '*.{ts,tsx,js,mjs}'
|
|
36
|
+
```
|
|
37
|
+
Shapes: `urls[i++ % urls.length]` choosing a replica per request; `crypto.randomUUID()` in a per-request header.
|
|
38
|
+
|
|
39
|
+
Go:
|
|
40
|
+
```
|
|
41
|
+
rg -n 'rand\.Intn\(len\(|uuid\.New\(\)|atomic\.AddUint(32|64)' -g '*.go'
|
|
42
|
+
rg -n 'prompt_cache_key|X-Session-Id|x-session-affinity|SessionID' -g '*.go'
|
|
43
|
+
```
|
|
44
|
+
Shapes: a round-robin counter over replica URLs; `uuid.New().String()` set per request.
|
|
45
|
+
|
|
46
|
+
Not a finding: a single replica (nothing to route), a stateless one-shot call with no history, and a server that routes on something the client already sends.
|
|
47
|
+
|
|
48
|
+
## Fix
|
|
49
|
+
Create the key once per conversation and send it on every turn; send every turn to the same endpoint (the server's one URL, not a list of replicas).
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
# before: a new id per request, and a client-side round-robin across replicas
|
|
53
|
+
headers = {"X-Session-Id": str(uuid.uuid4())}
|
|
54
|
+
client = OpenAI(base_url=next(REPLICA_URLS), api_key=KEY)
|
|
55
|
+
|
|
56
|
+
# after: one id per conversation, one URL
|
|
57
|
+
class Conversation:
|
|
58
|
+
def __init__(self):
|
|
59
|
+
self.session_id = str(uuid.uuid4()) # created once
|
|
60
|
+
def headers(self):
|
|
61
|
+
return {"X-Session-Id": self.session_id}
|
|
62
|
+
|
|
63
|
+
client = OpenAI(base_url=SERVER_URL, api_key=KEY) # the server places the conversation
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Pin a key to an endpoint, do not hash a key onto a replica yourself: the server knows each replica's load.
|
|
67
|
+
|
|
68
|
+
## Don't break meaning
|
|
69
|
+
The key is not part of the prompt, so answers do not change. Keeping conversations on one replica concentrates load: a replica can hold more long conversations than its neighbours, and when every replica is saturated the median wait can get worse (E10). Check the median and the tail under your peak load, not only on a quiet box, and keep the option to turn routing off. Do not put the key in the prompt text, where it would change the cache key.
|
|
70
|
+
|
|
71
|
+
## Verify
|
|
72
|
+
(a) Send several turns of one conversation. With the key stable, each turn's `cached_tokens` (where the server reports it) is close to the previous turn's whole prompt; with a fresh key per request it is near zero on turns that land on another replica. The server's own per-replica counters (LM Warden's model page shows how many requests stayed on their home replica) show where the requests went.
|
|
73
|
+
|
|
74
|
+
(b) kvsig: the turns have equal exact `nodes[i]` up to the previous turn, so a low cached count with equal ids points at placement or the engine (LP-LW-01), not at the prompt. The leanprompt usage record has no replica field, so it cannot show which replica answered; use the server's counters for that.
|
|
75
|
+
|
|
76
|
+
## Waste signal
|
|
77
|
+
Measured: lowers E on conversations whose prefix kvsig says was equal and that the server did not reuse; the log cannot say whether placement was the cause, so check the server's counters before reporting it. Static: severity medium where a client rotates across replica URLs or sends a per-request random conversation key to a multi-replica server; none for a single replica.
|