The page leanprompt report --html writes for icereed/paperless-gpt at commit 1d07ced, audited 2026-11-27. Every figure on this page is an estimate from reading the code, not a measurement of the app in use. Corrections and takedown: email info@podwarden.com or open an issue. Back to the audit of icereed/paperless-gpt

leanprompt audit of icereed/paperless-gpt

Unattended audit: nobody was asked during the run, so priority, volume and prices were left open; the questions for the owner are listed at the end.

4 places where this app pays for tokens it doesn't need

The biggest, at app_llm.go:721, about 150k tokens per 1,000 calls: the tag list in the tag prompt is built by ranging over a Go map (app_llm.go:721), so its order is random and differs for every document.

Together about 278k tokens per 1,000 calls An estimate from the code, not a measurement.

Tokens per 1,000 calls, by finding, and each one's share of the total

Plus 4 findings the project already knows about (planned, in progress, reported or declined), listed after the findings. They are not in the totals or the score.

Plus 6 other problems the audit found, listed after the findings. Not scored.

What this costs you

Every figure here is an estimate from the code, not a measurement. Findings can overlap (one failed call can show up in two), so the sum may count some tokens twice. Money is not part of the score. The table lists this app's findings first, largest first, then its open questions, then the questions for the server's administrator, then the findings the project already knows about, which are not in the totals.

FindingWhereTokens per 1,000 calls
LP-PC-04app_llm.go:721150k not cached
LP-PC-04app_llm.go:73582k not cached
LP-GE-04ocr/llm_provider.go:4433.8k prompt, 30k output
LP-GE-05llm_client.go:18112k prompt
LP-GE-02 (in progress)app_llm.go:795487k prompt
LP-GE-05 (already reported)ocr/llm_provider.go:22915k output

To see this in money, add to leanprompt.yaml:

  • volume: {calls_per_month: N}: how many calls the app makes a month (with targets:, on each entry)
  • prices: per model: input, cached_input and output per 1M tokens (US dollars, or set currency), with source and checked date (or, self-hosted, engine: {prefill_tokens_per_second: N})

leanprompt never guesses a volume or a price. Your coding agent can look up the provider's current price page and add it with the date; how.

What's wrong and what to change

4 open, 4 already known to the project, 0 fixed. Largest first, by the audit's estimate of tokens lost per 1,000 calls.

The tag list in the tag prompt is built by ranging over a Go map (app_llm.go:721), so its order is random and differs for every document.

Finding 1. app_llm.go:721 medium LP-PC-04 size is assumed

The tag prompt puts that list right after the fixed instructions and before the document (tag_prompt.tmpl:13-15), so the part every document shares is never the same bytes twice.

What to change
Sort availableTagNames (slices.Sort) at the end of the tag block in prepareSuggestionGenerationContext.
Why it matters
Automatic prefix caching (OpenAI and OpenAI-compatible hosts from 1,024 tokens, Gemini implicit caching, vLLM, and Ollama's reuse of the previous request's prompt) can only reuse an identical start. With a random order, every tag call prefills the whole tag list again.
How big it is
The code shows the problem and how often it happens; how many tokens it costs each time is assumed. To measure it: how many tokens the tag list takes in a real install (number of tags in paperless-ngx), and cached_tokens on two consecutive tag calls before and after sorting
Estimate
about 150k prompt tokens per 1,000 calls not served from cache (estimate)
What the estimate assumes

tag calls are 125 of 1,000 calls; in half of installs the instructions plus tag list exceed the 1,024-token minimum (about 300 tags) and about 1,200 tokens of it could be reused; documents are processed one after another, well inside the cache lifetime

How to check the fix Process two documents with OpenAI and LOG_LEVEL=debug: the two tag prompts start with the same text up to <title>, and usage.prompt_tokens_details.cached_tokens on the second is above 0.

The correspondent list is also built from a Go map (app_llm.go:735).

Finding 2. app_llm.go:735 medium LP-PC-04 size is assumed

With CORRESPONDENT_PROMPT_LIMIT at its default 0 (main.go:832) filterCorrespondentsForPrompt returns it unsorted, so the list after the 560-token instructions (correspondent_prompt.tmpl:33-35) is in a new order for every document.

What to change
Sort availableCorrespondentNames in prepareSuggestionGenerationContext (the limited path already sorts by score, then name).
Why it matters
Same as the tag list: the stable start of every correspondent prompt is reshuffled, so no prefix cache can reuse it.
How big it is
The code shows the problem and how often it happens; how many tokens it costs each time is assumed. To measure it: number of correspondents in a real install and CORRESPONDENT_PROMPT_LIMIT; cached_tokens on two consecutive correspondent calls
Estimate
about 82k prompt tokens per 1,000 calls not served from cache (estimate)
What the estimate assumes

correspondent calls are 125 of 1,000 calls; in 60% of installs the instructions plus list exceed 1,024 tokens and about 1,100 tokens could be reused

How to check the fix As for the tag list: two consecutive correspondent prompts share their start up to <title>, and cached_tokens on the second is above 0.

Vision OCR through Ollama runs on a client with no request timeout.

Finding 3. ocr/llm_provider.go:443 medium LP-GE-04 how often is assumed

OLLAMA_TIMEOUT_SECONDS (PR #1070) is only passed to createVisionLLM (main.go:1461), whose result App.VisionLLM is never read; the OCR provider is built separately in createOllamaClient, which passes no HTTP client when OLLAMA_HEADERS is unset (and a header client without a timeout when it is set). README.md:707 and env_registry.go:99 say the timeout covers OCR.

What to change
In createOllamaClient, give the client the same timeout: build it with the OLLAMA_TIMEOUT_SECONDS value (default 300 s, 0 disables) when OLLAMA_HEADERS is unset, and set Timeout on the header client when it is set. Delete createVisionLLM and App.VisionLLM, which nothing uses.
Why it matters
A vision model that loops on a page (#875) keeps generating until someone restarts the container, and because OCR runs first in the single background loop (background.go:76-84), auto-tagging stops too.
How often it happens
The code shows the problem; how often it happens is assumed. To measure it: how many Ollama vision OCR requests run longer than OLLAMA_TIMEOUT_SECONDS (300 s) or never return, from the Ollama server log or the paperless-gpt log stopping mid-document
Estimate
about 30k output tokens per 1,000 calls generated by OCR requests that never return (estimate)
What the estimate assumes

call mix of 3 OCR pages and 5 suggestion calls per document; 0.5% of Ollama OCR pages loop and generate about 16k tokens before a restart; local Ollama only, so the cost is GPU time and a stalled queue, not money

How to check the fix Add a test like ollama_timeout_test.go for ocr.createOllamaClient against an httptest server that never answers: with OLLAMA_TIMEOUT_SECONDS=1 ProcessImage returns an error after about a second instead of blocking.

RateLimitedLLM.GenerateContent retries every error three times with backoff, including errors that cannot succeed on a resend: a 400 for a prompt over the context window (TOKEN_LIMIT is unset by default), a 400 for an unsupported parameter, a 401 or a 404 for a retired model.

Finding 4. llm_client.go:181 high LP-GE-05 how often is assumed

AUTO_TAG_MAX_RETRIES then re-runs the whole document on the next poll, so a permanent error is sent up to 12 times, each time after repeating the calls that had already succeeded.

What to change
Retry only 429, 5xx and network errors (the OCR path at ocr/llm_provider.go:206 already filters this way); return other errors at once.
Why it matters
Each resend of a permanent error pays the full prompt again, and the earlier successful calls of the document are bought again on every poll.
How often it happens
The code shows the problem; how often it happens is assumed. To measure it: how many suggestion calls fail with a 4xx other than 429 (400 context length or invalid parameter, 401, 404 model not found), from the log line 'all retry attempts failed'
Estimate
about 12k prompt tokens per 1,000 calls (estimate)
What the estimate assumes

0.5% of documents hit a permanent error on the first call; 3 polls x 4 attempts of about 1,600 prompt tokens

How to check the fix With a mock server returning 400 for every request, one document produces one request per poll instead of four.

Already known to the project

The project's own issues, pull requests or docs already cover these, so they are not new and are not in the totals or the score. Read the link before working on one.

With the defaults, every document is sent to the model five times (title, tags, correspondent, document type, created date; custom fields make six), each time with the whole document and with TOKEN_LIMIT unset, untruncated.

Finding 5. app_llm.go:795 high LP-GE-02

What to change
Ask for the fields together in one structured call (the open PR #1072), or at least start every template with the document so the five calls share a prefix.
Why it matters
The document text is the largest part of each prompt and is prefilled five times per document.
In progress
open PR: opt-in LLM_METADATA_GROUPING generates the title first, then tags, correspondent, document type and date in one call (5 to 2 calls on their benchmark). https://github.com/icereed/paperless-gpt/pull/1072
Estimate
about 487k prompt tokens per 1,000 calls (estimate)
What the estimate assumes

125 documents per 1,000 calls, about 1,300 tokens of content each, three of the five copies saved by grouping

How to check the fix With grouping on, the provider log shows two requests per document instead of five.

A page answer that stopped at the output limit is stored as the page text; the stop reason is only logged when the text is empty.

Finding 6. ocr/llm_provider.go:229 high LP-GE-05 how often is assumed

On Anthropic with VISION_LLM_MAX_TOKENS unset, langchaingo sends max_tokens 2048, which a dense page can exceed.

What to change
Read StopReason and treat length/max_tokens as a truncation (#1251's proposal).
Why it matters
The cut-off page has to be OCRed again once someone notices, and until then the document's text and every suggestion made from it are incomplete.
How often it happens
The code shows the problem; how often it happens is assumed. To measure it: how often OCR answers stop at the limit (Anthropic stop_reason max_tokens, OpenAI finish_reason length, Ollama done_reason length)
Already reported
open: LLM OCR stores truncated or empty responses as complete text; proposes OCR_FAIL_ON=truncated,empty. https://github.com/icereed/paperless-gpt/issues/1251
Estimate
about 15k output tokens per 1,000 calls (estimate)
What the estimate assumes

2% of OCR pages stop at the limit

How to check the fix A mock provider returning a stop reason of length produces an OCR error, not a stored page.

The OpenAI-compatible client (OpenAIHTTPClient, used for suggestions and OCR), and the Anthropic and Mistral clients, are created without a timeout, and the background loop's context has no deadline, so one request that never returns stops all processing.

Finding 7. ocr/llm_provider.go:321 medium LP-GE-04

What to change
Give every provider client a timeout (one LLM_REQUEST_TIMEOUT for hosted providers, default a few minutes), or wrap each GenerateContent call in context.WithTimeout.
Why it matters
A stalled hosted request blocks the single background loop until the container restarts; the requests behind it are not sent at all.
Already reported
open: LLM request hangs indefinitely when the Anthropic API does not respond; asks for LLM_REQUEST_TIMEOUT. PR #972 (open) adds a timeout only to the /api/generate-suggestions HTTP handler, not to the background loop. https://github.com/icereed/paperless-gpt/issues/937
Estimate
no tokens of its own; a stalled queue
What the estimate assumes

known upstream as #937

How to check the fix Point OPENAI_BASE_URL at a server that accepts and never answers; the document fails after the timeout and the loop moves on.

Each OCR request puts the page image before the fixed OCR instructions, so nothing the pages share comes first.

Finding 8. ocr/llm_provider.go:159 low LP-PC-10

What to change
Put the instructions first (PR #1204).
Why it matters
The fixed instructions are about 120 tokens, below every hosted provider's minimum, so this matters only for local engines.
In progress
open PR: move the OCR prompt before the image data. https://github.com/icereed/paperless-gpt/pull/1204
Estimate
close to zero on hosted providers
What the estimate assumes

default OCR prompt

How to check the fix On a local llama.cpp or Ollama server, the second page's prompt eval count drops by the instruction length.

Other problems the audit found

Problems the audit checked in the code that cost no tokens of their own, such as a spend meter that ignores cache tokens or a cut-off answer accepted as complete. They are not scored. Check each one before you change anything.

OCR retries miss Gemini and Ollama errors, so one 429 fails the whole document

Note 1. ocr/llm_provider.go:206 not scored

The OCR retry treats an error as transient only if its text contains 'status code: 429' or 'status code: 5'. That is langchaingo's OpenAI and Anthropic wording. Gemini's error reads 'Error 429, Message: ...' (google.golang.org/genai APIError.Error) and Ollama's reads '503 Service Unavailable: ...' (langchaingo ollamaclient StatusError), so rate limits and overload on those providers are never retried: the page fails, the document fails, and OCR_MAX_RETRIES later OCRs every page again.

What to change
Classify by status code instead of text: check errors.As for genai.APIError (Code) and the Ollama status error, or extend the match to both formats.

How to check the fix A retry test with errors.New("Error 429, Message: quota, Status: RESOURCE_EXHAUSTED, Details: []") retries like the existing 'status code: 429' cases in ocr/llm_provider_retry_test.go.

VISION_LLM_MAX_TOKENS and VISION_LLM_TEMPERATURE have no effect with googleai

Note 2. ocr/google_ai_client.go:149 LP-GE-17 medium not scored

GoogleAIProvider.GenerateContent ignores its opts: the genai config carries only the thinking budget, so the output limit and temperature set for OCR are never sent to Gemini, and the finish reason is not read.

What to change
Apply llms.CallOptions to genai.GenerateContentConfig (MaxOutputTokens, Temperature) and return the candidate's FinishReason as StopReason.

How to check the fix A test with a fake genai transport sees maxOutputTokens in the request body when VISION_LLM_MAX_TOKENS is set.

OcrLimitHit compares prompt plus output tokens with the output limit

Note 3. ocr/llm_provider.go:245 not scored

limitHit uses GenerationInfo TotalTokens, which langchaingo fills with prompt plus completion tokens for OpenAI and Ollama. The page image alone is often 800 to 1,500 tokens, so a page can be flagged as cut off when its output was short, while Anthropic (no TotalTokens) falls back to a tokenizer estimate.

What to change
Use the stop reason (length / max_tokens), or CompletionTokens / OutputTokens, instead of TotalTokens.
Already reported
#1251 notes OcrLimitHit is only computed when VISION_LLM_MAX_TOKENS is set and is not acted on; the TotalTokens comparison is not mentioned. https://github.com/icereed/paperless-gpt/issues/1251

How to check the fix For an OpenAI page with prompt 1,200 and completion 300 tokens and VISION_LLM_MAX_TOKENS=1024, OcrLimitHit is false.

LLM_MAX_RETRIES=0 still retries three times

Note 4. llm_client.go:148 not scored

NewRateLimitedLLM replaces 0 or a negative MaxRetries with 3, so the documented setting cannot turn retries off for suggestions (for OCR, VISION_LLM_MAX_RETRIES=0 does disable them, per the README).

What to change
Treat 0 as no retries and keep 3 only as the default when the variable is unset (getRateLimitConfig already defaults to 3).

How to check the fix With LLM_MAX_RETRIES=0 and a failing mock, one request is sent.

README examples name a model retired on 2026-11-30 and snapshots shut down on 2027-01-14

Note 5. README.md:253 LP-GE-13 low not scored

The README suggests claude-sonnet-4-5 (lines 253, 263, 674; docs/openai_compatible_providers.md:46), which Anthropic retires on 2026-11-30 (model deprecations page, checked 2026-11-27), and gpt-4o (lines 225, 263, 354, 392), whose snapshots gpt-4o-2024-08-06 and -11-20 shut down on 2027-01-14 (OpenAI deprecations page, checked 2026-11-27). LLM_MODEL has no code default, so only new setups copied from the README are affected.

What to change
Replace the examples with current models (claude-sonnet-5-5; an active OpenAI model), keeping the note that any vision model works.

How to check the fix A new install from the README example starts and its first suggestion call returns 200.

Ad-hoc analysis returns a cut-off answer as complete

Note 6. app_http_handlers.go:1171 LP-GE-12 medium not scored

analyzeDocumentsHandler calls app.LLM.Call, which returns only the text; the stop reason is lost. On Anthropic, langchaingo sends max_tokens 2048 when none is set, so a table over many documents can stop mid-row and is shown as the result.

What to change
Call GenerateContent, check Choices' StopReason, and tell the user when the answer was cut off (or pass a larger max tokens).

How to check the fix With a mock returning stop_reason max_tokens, the response carries a truncation flag or error.

Fix it with your coding agent

Paste this into Claude Code, Codex, Cursor or any coding assistant. It will check each finding against your code and propose fixes one at a time, asking before it changes anything.

Please check and fix the LLM-call findings from a leanprompt audit of this repository.

1. If the leanprompt skills are not installed for you here, install them: npx leanprompt@0.1.0-dev.15 install
2. Read .leanprompt/findings.json and leanprompt-report.md. If they are missing, use the list below.
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.
4. Fix one finding at a time. Show me the change as a small diff and apply it only after I say yes.
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.
6. When a fix is proved, set "fixed": true on its finding in .leanprompt/findings.json and run npx leanprompt@0.1.0-dev.15 score.

Findings, largest first:
1. LP-PC-04 at app_llm.go:721: The tag list in the tag prompt is built by ranging over a Go map (app_llm.go:721), so its order is random and differs for every document. The tag prompt puts that list right after the fixed instructions and before the document (tag_prompt.tmpl:13-15), so the part every document shares is never the same bytes twice.
2. LP-PC-04 at app_llm.go:735: The correspondent list is also built from a Go map (app_llm.go:735). With CORRESPONDENT_PROMPT_LIMIT at its default 0 (main.go:832) filterCorrespondentsForPrompt returns it unsorted, so the list after the 560-token instructions (correspondent_prompt.tmpl:33-35) is in a new order for every document.
3. LP-GE-04 at ocr/llm_provider.go:443: Vision OCR through Ollama runs on a client with no request timeout. OLLAMA_TIMEOUT_SECONDS (PR #1070) is only passed to createVisionLLM (main.go:1461), whose result App.VisionLLM is never read; the OCR provider is built separately in createOllamaClient, which passes no HTTP client when OLLAMA_HEADERS is unset (and a header client without a timeout when it is set). README.md:707 and env_registry.go:99 say the timeout covers OCR.
4. LP-GE-05 at llm_client.go:181: RateLimitedLLM.GenerateContent retries every error three times with backoff, including errors that cannot succeed on a resend: a 400 for a prompt over the context window (TOKEN_LIMIT is unset by default), a 400 for an unsupported parameter, a 401 or a 404 for a retired model. AUTO_TAG_MAX_RETRIES then re-runs the whole document on the next poll, so a permanent error is sent up to 12 times, each time after repeating the calls that had already succeeded.

Already known to the project (read the link first; do not duplicate work the project has planned or started):
- LP-GE-02 (app_llm.go:795): With the defaults, every document is sent to the model five times (title, tags, correspondent, document type, created date; custom fields make six), each time with the whole document and with TOKEN_LIMIT unset, untruncated. In progress: open PR: opt-in LLM_METADATA_GROUPING generates the title first, then tags, correspondent, document type and date in one call (5 to 2 calls on their benchmark). https://github.com/icereed/paperless-gpt/pull/1072
- LP-GE-05 (ocr/llm_provider.go:229): A page answer that stopped at the output limit is stored as the page text; the stop reason is only logged when the text is empty. On Anthropic with VISION_LLM_MAX_TOKENS unset, langchaingo sends max_tokens 2048, which a dense page can exceed. Already reported: open: LLM OCR stores truncated or empty responses as complete text; proposes OCR_FAIL_ON=truncated,empty. https://github.com/icereed/paperless-gpt/issues/1251
- LP-GE-04 (ocr/llm_provider.go:321): The OpenAI-compatible client (OpenAIHTTPClient, used for suggestions and OCR), and the Anthropic and Mistral clients, are created without a timeout, and the background loop's context has no deadline, so one request that never returns stops all processing. Already reported: open: LLM request hangs indefinitely when the Anthropic API does not respond; asks for LLM_REQUEST_TIMEOUT. PR #972 (open) adds a timeout only to the /api/generate-suggestions HTTP handler, not to the background loop. https://github.com/icereed/paperless-gpt/issues/937
- LP-PC-10 (ocr/llm_provider.go:159): Each OCR request puts the page image before the fixed OCR instructions, so nothing the pages share comes first. In progress: open PR: move the OCR prompt before the image data. https://github.com/icereed/paperless-gpt/pull/1204

Other problems found (check each against the code first; not scored):
- OCR retries miss Gemini and Ollama errors, so one 429 fails the whole document (ocr/llm_provider.go:206): The OCR retry treats an error as transient only if its text contains 'status code: 429' or 'status code: 5'. That is langchaingo's OpenAI and Anthropic wording. Gemini's error reads 'Error 429, Message: ...' (google.golang.org/genai APIError.Error) and Ollama's reads '503 Service Unavailable: ...' (langchaingo ollamaclient StatusError), so rate limits and overload on those providers are never retried: the page fails, the document fails, and OCR_MAX_RETRIES later OCRs every page again. Change: Classify by status code instead of text: check errors.As for genai.APIError (Code) and the Ollama status error, or extend the match to both formats.
- VISION_LLM_MAX_TOKENS and VISION_LLM_TEMPERATURE have no effect with googleai (ocr/google_ai_client.go:149) [LP-GE-17]: GoogleAIProvider.GenerateContent ignores its opts: the genai config carries only the thinking budget, so the output limit and temperature set for OCR are never sent to Gemini, and the finish reason is not read. Change: Apply llms.CallOptions to genai.GenerateContentConfig (MaxOutputTokens, Temperature) and return the candidate's FinishReason as StopReason.
- OcrLimitHit compares prompt plus output tokens with the output limit (ocr/llm_provider.go:245): limitHit uses GenerationInfo TotalTokens, which langchaingo fills with prompt plus completion tokens for OpenAI and Ollama. The page image alone is often 800 to 1,500 tokens, so a page can be flagged as cut off when its output was short, while Anthropic (no TotalTokens) falls back to a tokenizer estimate. Change: Use the stop reason (length / max_tokens), or CompletionTokens / OutputTokens, instead of TotalTokens.
- LLM_MAX_RETRIES=0 still retries three times (llm_client.go:148): NewRateLimitedLLM replaces 0 or a negative MaxRetries with 3, so the documented setting cannot turn retries off for suggestions (for OCR, VISION_LLM_MAX_RETRIES=0 does disable them, per the README). Change: Treat 0 as no retries and keep 3 only as the default when the variable is unset (getRateLimitConfig already defaults to 3).
- README examples name a model retired on 2026-11-30 and snapshots shut down on 2027-01-14 (README.md:253) [LP-GE-13]: The README suggests claude-sonnet-4-5 (lines 253, 263, 674; docs/openai_compatible_providers.md:46), which Anthropic retires on 2026-11-30 (model deprecations page, checked 2026-11-27), and gpt-4o (lines 225, 263, 354, 392), whose snapshots gpt-4o-2024-08-06 and -11-20 shut down on 2027-01-14 (OpenAI deprecations page, checked 2026-11-27). LLM_MODEL has no code default, so only new setups copied from the README are affected. Change: Replace the examples with current models (claude-sonnet-5-5; an active OpenAI model), keeping the note that any vision model works.
- Ad-hoc analysis returns a cut-off answer as complete (app_http_handlers.go:1171) [LP-GE-12]: analyzeDocumentsHandler calls app.LLM.Call, which returns only the text; the stop reason is lost. On Anthropic, langchaingo sends max_tokens 2048 when none is set, so a table over many documents can stop mid-row and is shown as the result. Change: Call GenerateContent, check Choices' StopReason, and tell the user when the answer was cut off (or pass a larger max tokens).

Score

One number from 0 to 100 for how well this app avoids paying for the same tokens twice; higher is better. It is computed from the findings above (static) or from your usage log (measured).

87static
E, prefill reuse
0.86
S, prefix stability
1.00
G, generation waste
0.11
Default shares
0 of 4

Findings scored with severity defaults, not estimates. The fewer, the more the static score says about this app.

It leaves out 4 findings the project already knows about (planned, in progress, declined or reported); with them it would be 70.

A static score is an estimate from the audit's findings, not a measurement.

Scored 2026-11-27 (the date on the machine that ran it).

Questions for the owner

These were not answered during the audit. Until they are, the page shows tokens only and ranks the advice without a priority.

  • Priority: which matters most for this app, cost, speed or quality (or weights)? Not set, so the advice uses equal weights. Answer with priority: in leanprompt.yaml.
  • Volume: how many calls does the app make a month? Answer with volume: {calls_per_month: N, source: "..."} in leanprompt.yaml.
  • Prices: what does each model cost (input, cached input, output per 1M tokens, with the source and the date it was read, and the currency if not US dollars)? Answer with prices: in leanprompt.yaml.