Changing documents come before the chat history, so the cache cannot reuse it

An all-in-one AI app with 40 chat providers, whose maintainers already describe the fix in their own issue.
≈ 1,200,000 tokens per 1,000 calls, for chat history the cache could have served estimate
Audited with leanprompt 0.1.0-dev.15
Estimates, not measurements. Every figure on this page is an estimate from reading the code, not a measurement of the app in use.
- Repository
- Mintplex-Labs/anything-llm
- Commit audited
b014470- leanprompt version
- 0.1.0-dev.15
- Audit date
- Status
- The maintainers have been told about this audit; no response yet.
- Maintainers
- the comment
- How it ran
- 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.
The three largest cache findings are already planned in the maintainers' issue #6401, so they are shown as already known and left out of the score; the audit adds the sliding history window and the agent loop. Metering is in their open pull request #6747 and the tool-argument re-ask was declined in #7102. Audited with 0.1.0-dev.11, re-scored with 0.1.0-dev.14.
leanprompt read the code at commit b014470 and found 4 places where its LLM calls could use fewer tokens, 3 the project already knows about, plus 2 other problems, not scored. Static score: 90 of 100 (an estimate from the findings, leaving out what the project already knows about). The code may have changed since.
Findings
-
LP-PD-05Drop stale history on purpose, not by strippingserver/utils/chats/stream.js:105· severity medium · saves prefillWhat happens. History is the last 20 saved exchanges (openAiHistory, default 20). Once a thread passes 20 exchanges, every new turn drops the oldest one, so the start of the history changes on every turn. This is not covered in #6401 and would defeat its stated goal that everything before the latest user turn stays byte-identical.
The change. Drop old exchanges in steps (for example keep between 10 and 20 and cut back to 10 when 20 is reached) so the window moves only every tenth turn, or add this to the #6401 plan.
Why it helps. A window that slides by one row each turn changes the first history message every turn, which breaks reuse of the entire history.
Estimate about 0.84M prompt tokens per 1,000 calls (estimate), overlapping the first two findings today
Assumptions. 15% of chat turns are in threads past 20 exchanges; a full window is about 8,000 tokens. Today the same tokens are already lost to the first two findings; this is the loss that remains after #6401 lands, so the shares are not additive.
-
LP-PC-01Put cache marks where the provider needs themserver/utils/agents/aibitat/providers/anthropic.js:270· severity high · saves prefillWhat happens. In the agent tool loop on Anthropic, the cache mark (when enabled) sits only on the system prompt and there is none on the messages, so each step of a multi-step tool task recomputes the preloaded history and every earlier tool result. With caching off (the default) nothing is cached at all. #6401 covers the chat path but does not name the agent loop.
The change. When ANTHROPIC_CACHE_CONTROL is set, also mark the last content block of the last message in the agent request (or use top-level automatic caching), so each step reads the previous step's prefix.
Why it helps. An agent task makes several calls in a few seconds with a growing, append-only message list, which is the best case for caching.
Estimate about 225k prompt tokens per 1,000 calls not served from cache (estimate)
Assumptions. 250 agent calls per 1,000; 15% on Anthropic (assumed); 75% are not the first step of a task; about 8,000 tokens of history and tool results per later step.
-
LP-PD-04Trim tool results and retrieved context at the tool boundaryserver/utils/agents/aibitat/plugins/web-scraping.js:124· severity medium · saves prefillWhat happens. The scrape tool returns the whole page text into the agent conversation whenever it is smaller than the model's entire context window, and summarises only above that. A 100k-token page on a 200k model goes in whole and is carried by every later call of the session.
The change. Summarise (or cut) above a fixed share of the window, for example a quarter, instead of the whole window.
Why it helps. Every later step and turn of the agent session resends the page.
Estimate about 43k prompt tokens per 1,000 calls (estimate)
Assumptions. About 62 agent tasks per 1,000 calls; 10% scrape a page; 30% of pages exceed 8,000 tokens by about 12,000 tokens; about 2 later calls carry it.
-
LP-PC-05Tool lists grow only at the endserver/utils/agents/aibitat/index.js:1162· severity medium · saves prefillWhat happens. When an agent task reaches the tool-call limit, the final call is sent with no tools, which removes the tool definitions from the front of the prompt and makes that call recompute everything.
The change. Keep the tool list and send tool_choice 'none' (or allowed_tools) on the final call, where the provider supports it.
Why it helps. Tool definitions are part of the cached prefix; removing them changes the prefix from the start.
Estimate about 15k prompt tokens per 1,000 calls not served from cache (estimate)
Assumptions. 2% of agent tasks reach the limit; about 12,000 tokens of prefix on the final call.
Already known to the project
The project’s own issues, pull requests or docs already cover these, so they are not counted above and are left out of the static score.
-
LP-PC-02Stable content first, without hurting meaningserver/utils/AiProviders/openAi/index.js:125· severity high · saves prefillWhat happens. Retrieved document chunks and the user's memories are appended to the system message, which comes before the chat history. The chunks change with every question, so the history after them can never be reused from the provider's prefix cache. The same layout is in 38 of the 40 chat providers. The maintainers already describe this exactly in issue #6401 (open, core-team-only).
The change. Follow the plan in #6401: keep the system message static and put retrieved context, memories and the current time into the newest user turn, assembled in one place (compressMessages) instead of in each provider.
Why it helps. On OpenAI, Gemini, DeepSeek and local engines with prefix reuse, every turn after the first recomputes the whole chat history at the full input price.
Already planned. Issue #6401 (open, core team): keep the system message static and move retrieved context, memories and the time into the newest user turn. https://github.com/Mintplex-Labs/anything-llm/issues/6401
Estimate about 1.2M prompt tokens per 1,000 calls not served from cache (estimate)
Assumptions. 1,000 app calls = 700 chat turns, 250 agent calls, 50 other; 85% of chat on providers with automatic prefix reuse; 60% of chat in workspaces with documents or memories; 85% of turns are not the first of a thread; average history 4,000 tokens; average prompt 6,900 tokens.
-
LP-PC-03No ids, timestamps, versions or paths at the top of the promptserver/models/systemSettings.js:40· severity high · saves prefillWhat happens. The default system prompt contains 'The current date and time is {datetime}', which expands to the time to the minute near the start of every request. Consecutive turns rarely share a minute, so even in a workspace with no documents the whole history is recomputed each turn. Reported as #6398, moved by the maintainer into #6401; PR #6399 was closed unmerged.
The change. As planned in #6401: drop the datetime sentence from the default system prompt and send the time in the newest user turn; recognise the old default text stored in existing workspaces.
Why it helps. The first changing token sits about 40 tokens into the prompt, so nothing after it can be reused.
Already planned. Reported in #6398, which the maintainers closed into #6401 (open, core team); #6401 drops the datetime from the default system prompt. https://github.com/Mintplex-Labs/anything-llm/issues/6401
Estimate about 0.8M prompt tokens per 1,000 calls not served from cache (estimate)
Assumptions. Same call mix as the first finding; counts only the 40% of chat in workspaces without documents or memories, so it does not overlap the first finding; default prompt in use.
-
LP-PC-01Put cache marks where the provider needs themserver/utils/AiProviders/anthropic/index.js:145· severity high · saves prefillWhat happens. With the Anthropic 'Prompt Caching' option on, the only cache mark is on the system block, which holds the per-turn context and the per-minute datetime, and there is no mark on the history. Each turn pays the cache-write premium (1.25x, or 2x for 1 hour) on a block that is never read again, and the history is never cached. Already listed as point 4 of #6401.
The change. After the system block is made static (#6401), keep the mark there and add a second mark on the last history message, as #6401 proposes.
Why it helps. Anthropic caches only up to a mark, so without a mark on the history it is recomputed every turn; a mark on changing content costs more than no mark.
Already planned. Point 4 of issue #6401 (open, core team): a second cache mark on the last history message. https://github.com/Mintplex-Labs/anything-llm/issues/6401
Estimate about 0.36M prompt tokens per 1,000 calls not served from cache (estimate)
Assumptions. 15% of chat traffic on Anthropic (unknown, assumed); 85% non-first turns; history 4,000 tokens. Caching is off by default ('No caching'), a deliberate opt-in from #6035.
Other problems the audit found
Problems read in the code that cost no tokens of their own, such as a cost meter or an error path. Not scored.
-
The Anthropic chat connector looks up the model's output limit on every turn
server/utils/AiProviders/anthropic/index.js:58What happens. A new AnthropicLLM is built for each chat (helpers/index.js:183-185), and its constructor starts fetchModelMaxTokens (lines 58-61); assertModelMaxTokens (lines 84-88) awaits a second models.retrieve if the first has not returned. That is one or two API round trips per turn, one before the first token. On any error, including a transient one, the lookup returns 4096 (lines 107-110), so that turn runs with max_tokens 4096 instead of the model's limit.
The change. Cache the output limit per model in a module-level map (helpers/contextWindowCache.js does this for context windows), and do not fall back silently to 4096 on a transient error.
To check. Two chat turns on the same model make one models.retrieve call, not two or four.
-
A reply cut off at the output limit is saved as complete
server/utils/AiProviders/anthropic/index.js:380·LP-GE-12Read the finish reason before using an answer · severity mediumWhat happens. handleStream resolves on message_stop whatever the stop_reason (lines 378-393), and the chat path does not call watchTokenLimit as the agent path does, so a reply that stopped at max_tokens is saved and shown as a complete answer. After a provider error mid-stream (lines 330-351) the partial text is also saved as a normal answer (chats/stream.js:357-375) and sent as history on later turns; for a user abort that is deliberate, for a provider error probably not.
The change. Surface stop_reason max_tokens to the user, as the agent path does, and mark a reply that ended in a provider error so it is not reused as a complete answer.
To check. With a small output limit, the saved chat shows that the reply was cut off.
The maintainers’ response
No response from the maintainers yet.
How this was made
The llm-call-audit skill read the code and wrote findings.json; nothing was run against the project’s providers. The full audit page is what leanprompt report --html writes from the same findings.
Corrections and takedown: email info@podwarden.com or open an issue.