sdk-python icon indicating copy to clipboard operation
sdk-python copied to clipboard

[FEATURE] Context Manager Cache aware mode

Open lizradway opened this issue 2 months ago • 3 comments

Problem

The current offload strategies (truncate, drop, summarize) are cache-unaware. When they remove or modify messages, they invalidate the model's cached prefix, causing a cache write on the next call instead of a cheaper cache read. In high-throughput or long-running agents with caching enabled, this negates the cost savings that prompt caching provides.

Proposal

1. Per-strategy cache_aware flag

Add a cache_aware flag (Python) / cacheAware (TypeScript) to OffloadConditions that changes how the strategy selects messages for removal.

Offload.truncate("tool_results").when(threshold=2500, cache_aware=True)
Offload.truncate('toolResults').when({ threshold: 2500, cacheAware: true })

When cache_aware=True, the strategy:

  1. Finds the most recent cachePoint block to identify the cached prefix boundary
  2. Prefers message-level removal in the uncached region (after the cache point) first
  3. Falls back to per-block truncation in the cached region (preserves prefix structure)
  4. Last resort: message-level removal in the cached region

When cache_aware=False (default), behavior is unchanged.

2. Top-level "cache-optimized" mode

Add a "cache-optimized" preset to ContextManager that provides default strategies tuned for cache performance.

# Cache-optimized defaults
agent = Agent(context_manager=ContextManager(mode="cache-optimized"))

# Equivalent to something like:
ContextManager(strategies=[
    Offload.truncate("tool_results").when(threshold=2500, cache_aware=True),
    Offload.summarize("*").when(threshold=1000, utilization=0.85, cache_aware=True),
])

# Existing default behavior
agent = Agent(context_manager=ContextManager())  # unchanged
new ContextManager({ mode: 'cacheOptimized' })

The "cache-optimized" mode could also adjust strategy selection — e.g., prefer head preview mode over head_tail to keep the prefix stable, or set a higher preserve_recent to push removal toward the uncached tail.

Open questions

  • What strategies/settings should "cache-optimized" use? Needs benchmarking with real cache metrics.
  • Should the mode also influence EmergencyTruncateStrategy (e.g., prefer tail removal even in emergency)?
  • Could a future version use model response metadata (cacheReadInputTokens) to track the actual cache boundary rather than relying on cachePoint block positions?

Considerations

  • Providers (Bedrock, Anthropic) re-place the cache point on the last user message every call, so the cached prefix grows each turn. Eventually the uncached region shrinks to nothing and the strategy must fall back.
  • cachePoint blocks are already skipped by _blockMatchesTarget / _block_matches_target, so block-level strategies never transform them. This adds awareness at the message-selection level.
  • Cross-SDK feature — should be designed for parity in both Python and TypeScript.

Applies to

  • strands-py — _context_manager/strategies/offload/
  • strands-ts — context-manager/strategies/offload/

lizradway avatar Sep 04 '26 15:09 lizradway

Can I take this up

NavuluriBalaji avatar Sep 04 '26 16:09 NavuluriBalaji

hey @NavuluriBalaji this is a pretty comprehensive change that is nuanced and required design designs, so this should be handled by the team.

please see "open to contribution" for items that would be good to pick up :)

lizradway avatar Sep 04 '26 16:09 lizradway

TL;DR: at their defaults, the proactive summarization paths compact every 3-5 model calls, and after each compaction 0-1% of the previous request's messages are still a prefix of the next one. Data point for making these strategies cache-aware.

Compactions in one 41-call tool loop (fake model, 6000-token context window, main at 0943408):

Configuration Python TypeScript
SummarizingConversationManager(proactive_compression=True) 6 7
proactive_summarization preset 7 9
context_manager="auto" 2 2
  • Cause: the first two summarize only the oldest 30% of messages at 70% utilization, so the threshold is crossed again a few calls later. auto waits for 85% and summarizes everything but the newest 4 messages.
  • Each compaction rewrites the start of the history, so the whole message prefix is written again every time. Compacting deeper per pass, as auto does, would make that rare.
  • Two other context features rewrite the prefix on a schedule that ignores the cache: #6337 (default sliding window, every turn) and #6338 (preserve_recent offload, every model call).
Scripts, output, code locations

C marks a model call whose request does not extend the previous one. The Python and TypeScript counts differ because the two fake models estimate tokens from differently serialized messages.

SummarizingConversationManager(proactive_compression=True)     agent calls 41, summary calls 6, compactions 6, message chars kept across them 1%
    ................C....C...C...C...C...C..
ContextManager(strategies=["proactive_summarization"])         agent calls 41, summary calls 7, compactions 7, message chars kept across them 0%
    ................C...C..C...C...C...C...C
context_manager="auto"                                         agent calls 41, summary calls 2, compactions 2, message chars kept across them 0%
    ....................C.................C.
SummarizingConversationManager({ proactiveCompression: true }) agent calls 41, summary calls 7, compactions 7, message chars kept across them 0%
    ..............C...C..C...C...C...C...C..
contextManager: { strategies: ['proactiveSummarization'] }     agent calls 41, summary calls 9, compactions 9, message chars kept across them 0%
    ..............C...C..C..C..C..C..C..C..C
contextManager: 'auto'                                         agent calls 41, summary calls 2, compactions 2, message chars kept across them 0%
    .................C..............C.......

Code (main at 0943408): strands-py/src/strands/agent/conversation_manager/summarizing_conversation_manager.py:215-220 (30%), conversation_manager.py:17 (70%), strands-py/src/strands/_context_manager/presets.py:44-45, context_manager.py:91 (auto); strands-ts/src/conversation-manager/summarizing-conversation-manager.ts:146, conversation-manager.ts:17, strands-ts/src/context-manager/presets.ts:46-47, context-manager.ts:49.

Python, python count.py:

"""Count compactions in one 41-call tool loop on a 6000-token context window (fake model, no network)."""
import json

from strands import Agent, tool
from strands.agent.conversation_manager import SummarizingConversationManager
from strands.experimental.context_manager import ContextManager
from strands.models import Model


class LoopModel(Model):
    """Fake model: 40 tool calls, then a final answer. A request whose last message or system prompt
    asks for a summary gets a short summary back and is counted separately."""

    def __init__(self):
        self.agent_requests, self.summary_calls = [], 0

    def update_config(self, **kwargs): ...
    def get_config(self): return {"context_window_limit": 6000}
    def structured_output(self, *args, **kwargs): ...

    async def stream(self, messages, tool_specs=None, system_prompt=None, **kwargs):
        ask = (json.dumps(messages[-1]) + str(system_prompt) + str(kwargs.get("system_prompt_content"))).lower()
        is_summary = "summar" in ask or "do not act on" in ask
        yield {"messageStart": {"role": "assistant"}}
        if is_summary:
            self.summary_calls += 1
            yield {"contentBlockDelta": {"delta": {"text": "SUMMARY: pages fetched so far were fine. " + "s" * 200}}}
        else:
            self.agent_requests.append(json.loads(json.dumps(messages)))
            n = len(self.agent_requests)
            if n <= 40:
                yield {"contentBlockStart": {"start": {"toolUse": {"name": "fetch", "toolUseId": f"t{n}"}}}}
                yield {"contentBlockDelta": {"delta": {"toolUse": {"input": '{"page": %d}' % n}}}}
            else:
                yield {"contentBlockDelta": {"delta": {"text": "final answer"}}}
        yield {"contentBlockStop": {}}
        yield {"messageStop": {"stopReason": "end_turn" if is_summary or len(self.agent_requests) > 40 else "tool_use"}}
        tokens = len(json.dumps(messages)) // 4
        yield {"metadata": {"usage": {"inputTokens": tokens, "outputTokens": 20, "totalTokens": tokens + 20},
                            "metrics": {"latencyMs": 1}}}


@tool
def fetch(page: int) -> str:
    """Fetch a page."""
    return f"PAGE {page} START " + (f"line-{page} " * 100) + f" PAGE {page} END"


def run(label, **agent_kwargs):
    model = LoopModel()
    Agent(model=model, tools=[fetch], system_prompt="You are a test agent.", callback_handler=None,
          **agent_kwargs)("fetch 40 pages")
    r = model.agent_requests
    marks, kept, total = "", 0, 0
    for i in range(1, len(r)):
        same = next((k for k in range(len(r[i - 1])) if k >= len(r[i]) or r[i - 1][k] != r[i][k]), len(r[i - 1]))
        if same < len(r[i - 1]):
            kept += len(json.dumps(r[i - 1][:same]))
            total += len(json.dumps(r[i - 1]))
        marks += "." if same == len(r[i - 1]) else "C"
    print(f"{label:<62} agent calls {len(r)}, summary calls {model.summary_calls}, "
          f"compactions {marks.count('C')}, message chars kept across them {100 * kept // max(1, total)}%")
    print(f"    {marks}")


run("SummarizingConversationManager(proactive_compression=True)",
    conversation_manager=SummarizingConversationManager(proactive_compression=True))
run('ContextManager(strategies=["proactive_summarization"])',
    context_manager=ContextManager(strategies=["proactive_summarization"]))
run('context_manager="auto"', context_manager="auto")

TypeScript, saved in the repo root, npx tsx count.ts:

// Count compactions in one 41-call tool loop on a 6000-token context window (fake model, no network).
import { Agent, Model, SummarizingConversationManager, tool } from './strands-ts/src/index.ts'

// Fake model: 40 tool calls, then a final answer. A request whose last message or system prompt asks for a
// summary gets a short summary back and is counted separately.
class LoopModel extends Model {
  agentRequests: string[][] = []
  summaryCalls = 0
  updateConfig() {}
  getConfig = () => ({ modelId: 'fake', contextWindowLimit: 6000 })
  async *stream(messages: any[], options?: any): AsyncGenerator<any> {
    const all = messages.map((m) => JSON.stringify(m))
    const ask = (all.at(-1)! + JSON.stringify(options?.systemPrompt ?? '')).toLowerCase()
    const isSummary = ask.includes('summar') || ask.includes('do not act on')
    yield { type: 'modelMessageStartEvent', role: 'assistant' }
    let text = 'SUMMARY: pages fetched so far were fine. ' + 's'.repeat(200)
    if (isSummary) this.summaryCalls++
    else {
      this.agentRequests.push(all)
      text = 'final answer'
    }
    const n = this.agentRequests.length
    const callTool = !isSummary && n <= 40
    if (callTool) {
      yield { type: 'modelContentBlockStartEvent', start: { type: 'toolUseStart', name: 'fetch', toolUseId: `t${n}` } }
      yield { type: 'modelContentBlockDeltaEvent', delta: { type: 'toolUseInputDelta', input: `{"page": ${n}}` } }
    } else {
      yield { type: 'modelContentBlockStartEvent' }
      yield { type: 'modelContentBlockDeltaEvent', delta: { type: 'textDelta', text } }
    }
    yield { type: 'modelContentBlockStopEvent' }
    yield { type: 'modelMessageStopEvent', stopReason: callTool ? 'toolUse' : 'endTurn' }
    const tokens = Math.floor(all.join(',').length / 4)
    yield { type: 'modelMetadataEvent', usage: { inputTokens: tokens, outputTokens: 20, totalTokens: tokens + 20 } }
  }
}

const fetchPage = tool({
  name: 'fetch',
  description: 'Fetch a page.',
  inputSchema: { type: 'object', properties: { page: { type: 'number' } }, required: ['page'] },
  callback: (input: any) => `PAGE ${input.page} START ` + `line-${input.page} `.repeat(100) + ` PAGE ${input.page} END`,
})

async function run(label: string, config: object) {
  const model = new LoopModel()
  const agent = new Agent({ model, tools: [fetchPage], systemPrompt: 'You are a test agent.', printer: false, ...config })
  await agent.invoke('fetch 40 pages')
  const r = model.agentRequests
  let [marks, kept, total] = ['', 0, 0]
  for (let i = 1; i < r.length; i++) {
    const [prev, cur] = [r[i - 1]!, r[i]!]
    let same = 0
    while (same < prev.length && prev[same] === cur[same]) same++
    if (same < prev.length) {
      kept += prev.slice(0, same).join(',').length
      total += prev.join(',').length
    }
    marks += same === prev.length ? '.' : 'C'
  }
  const compactions = marks.split('C').length - 1
  console.log(
    `${label.padEnd(62)} agent calls ${r.length}, summary calls ${model.summaryCalls}, ` +
      `compactions ${compactions}, message chars kept across them ${Math.floor((100 * kept) / Math.max(1, total))}%`
  )
  console.log(`    ${marks}`)
}

async function main() {
  await run('SummarizingConversationManager({ proactiveCompression: true })', {
    conversationManager: new SummarizingConversationManager({ proactiveCompression: true }),
  })
  await run("contextManager: { strategies: ['proactiveSummarization'] }", {
    contextManager: { strategies: ['proactiveSummarization'] },
  })
  await run("contextManager: 'auto'", { contextManager: 'auto' })
}
main()

Offline only: no cache reads were measured for this one.

strandly-the-agent avatar Nov 18 '26 21:11 strandly-the-agent