Skip to content

The agent that grows with you

perf(caching): selective copy instead of deepcopy entire history

Koho Zheng43a9bd9e0bfc
diff --git a/agent/prompt_caching.py b/agent/prompt_caching.py
index 2e606cd377c..1a0326c79df 100644
--- a/agent/prompt_caching.py
+++ b/agent/prompt_caching.py
@@ -187,17 +187,18 @@ def apply_anthropic_cache_control(
is retained.
Returns:
- Deep copy of messages with cache_control breakpoints injected.
+ Shallow copy of message list with selective deep copies of modified messages.
"""
- messages = copy.deepcopy(api_messages)
- if not messages:
- return messages
+ if not api_messages:
+ return api_messages
+ messages = list(api_messages)
marker = _build_marker(cache_ttl)
breakpoints_used = 0
if messages[0].get("role") == "system":
+ messages[0] = copy.deepcopy(messages[0])
breakpoints_used = _apply_system_cache_markers(
messages[0],
marker,
@@ -213,6 +214,7 @@ def apply_anthropic_cache_control(
and _can_carry_marker(messages[i], native_anthropic=native_anthropic)
]
for idx in non_sys[-remaining:]:
+ messages[idx] = copy.deepcopy(messages[idx])
_apply_cache_marker(messages[idx], marker, native_anthropic=native_anthropic)
return messages