#7480·CopilotKit

Feature Request: App Context / state note in system_message invalidates provider prompt caching on every turn

Author: NishulDhakarCreated Sep 27, 2026Updated Sep 30, 2026
Labelsfeature request

Pre-flight Checklist

  • I have searched existing issues, and this hasn't been requested yet.

Problem or Motivation

CopilotKitMiddleware.wrap_model_call appends the App Context note (_apply_app_context_note) and, when expose_state is on, the state note (_apply_state_note) to request.system_message. Both change on almost every request, so the system message is never byte-identical between turns - and OpenAI's automatic prompt caching then reuses nothing. The long static system prompt plus the tool definitions are billed at the full input rate on every turn.

Measured (gpt-5.6-luna, ~8.6k-token system prompt + tools, requests 4s apart, usage.prompt_tokens_details.cached_tokens):

Request Cached tokens
Identical request, sent twice 8,599 / 8,602
Same system prompt, only an appended context note changed 0
Context note moved to a second system message 0
Static system message, context moved into the latest user message 8,583 / 8,610

In our production LangGraph + AG-UI agent, moving the per-turn context out of the system message took the first model call of each turn from 0 to ~99% cached input tokens (11,753 / 11,837), about a 75% cut in input cost for that call.

Measured on OpenAI only. Anthropic (explicit cache_control breakpoints) and Gemini implicit caching may behave differently - worth checking before changing any default.

Related: #5807 (moved App Context into the system prompt to avoid non-consecutive system messages), #7077 / #7104 (same function, privacy side).

Tell us your idea

Add an opt-in option on CopilotKitMiddleware:

CopilotKitMiddleware(context_placement="system" | "user")   # default "system" = today's behaviour

With "user", the App Context and state notes are prepended to the LATEST human message as a clearly delimited block, e.g.

[App context - background from the application, not the user's words]
...
[The user's message]
<original text>

and request.system_message is left untouched, so it stays byte-identical across turns and the provider's prompt cache applies to the system prompt + tools.

This keeps the single-system-message guarantee #5807 needed (nothing new is inserted as a system message), doesn't touch message history (only the model request is changed, like today), and is opt-in, so nothing changes for existing users.

Use case: any production agent with a long system prompt and many tools where the app context changes every turn (page state, user profile, selection). The same pattern would apply to the built-in agent's "## Context from the application" block in packages/runtime/src/agent/index.ts.

Would you like to work on this?

  • Yes, I’d love to work on it!
  • I’m open to collaborating but need guidance.
  • No, I’m just sharing the idea.