Repository navigation
Description
Problem
In agentic chat, we fetch the last 10 messages and send them to gpt-5.1 on every request (routers/chat.py:116). The message list changes with every new message — the oldest message gets dropped and a new one is appended. This means the message portion of the prompt changes entirely on every request, invalidating the prompt cache for that section.
OpenAI's prompt caching works on exact prefix matching in 128-token chunks. Currently our cacheable prefix is:
[tool schemas: ~11,100 tokens] [static system prompt: ~2,000 tokens] [messages: ~1,750 tokens × 10]
The tools + system prompt (~13,100 tokens) cache well thanks to #4677. But the messages section shifts on every request, so only the static prefix is cached.
Proposed optimization: append-only message window
Instead of a fixed sliding window of 10, use an expanding window with deferred truncation:
Current behavior (cache-hostile)
Request 1: messages [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Request 2: messages [2, 3, 4, 5, 6, 7, 8, 9, 10, 11] ← prefix broken at msg boundary
Request 3: messages [3, 4, 5, 6, 7, 8, 9, 10, 11, 12] ← prefix broken again
Every request invalidates the message cache because the start shifts.
Proposed behavior (cache-friendly)
Request 1: messages [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Request 2: messages [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] ← append-only, full prefix cached
...
Request 10: messages [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ..., 20] ← hit 20 messages
Request 11: messages [11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21] ← reset window to [11..21]
Request 12: messages [11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22] ← append again
How it works:
- Keep sending messages in an append-only fashion (window grows from 10 to 20)
- Once we hit 20 messages, shift the start to message 11 and continue from there
- The LLM always sees at least 10 messages of context
- Between resets, every request's message prefix is identical to the previous one + 1 new message — so all previous messages are cache hits
Implementation notes
- Need to track
window_start_message_idper chat session (could be stored in Redis or derived from message count) database/chat.py:get_messages()already supportsoffsetparameter — can useoffset+ higherlimitto fetch the right window- The window reset point (20) is configurable — higher = more cache reuse but more tokens per request
- Compatible with existing
prompt_cache_key+prompt_cache_retention: 24hfrom fix: optimize agentic chat prompt caching — 62% cost reduction (#4676) #4677
Files involved
routers/chat.py:116— message fetching logicdatabase/chat.py:149—get_messages()queryutils/retrieval/agentic.py:171—_messages_to_langchain()conversion
Credit
Technique from @beastoin's comment on #4677.
Activity
beastoin commentedon Feb 9, 2026
That might be a dumb idea from me. Please validate it carefully since we use cross-user caching.
beastoin commentedon Feb 11, 2026