-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext_compactor.py
More file actions
85 lines (66 loc) · 2.86 KB
/
context_compactor.py
File metadata and controls
85 lines (66 loc) · 2.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
"""In-place compaction of agent conversation history.
Truncates the `content` field of large `tool_result` blocks in older messages,
leaving the message structure (roles, tool_use_ids, positions) intact. This is
called every iteration as a lightweight pre-step before the LLM call, to prevent
bloated tool results from consuming context unnecessarily.
Complementary to Session.compact() — that one archives the full conversation
to a markdown file for long-running sessions. This one is cheap GC for tool
results.
"""
from __future__ import annotations
import copy
import logging
logger = logging.getLogger("agent_computer.compactor")
_TRUNCATION_MARKER = "\n...[truncated: {removed} chars removed to save context]"
def truncate_tool_results(
messages: list[dict],
*,
max_tool_result_chars: int = 2000,
keep_recent_turns: int = 3,
) -> list[dict]:
"""Return a copy of messages with large tool_result contents truncated.
The most recent `keep_recent_turns` turns are never touched — the agent
likely still needs their full content for the next reasoning step.
A "turn" for this purpose is a single message. We use a message count
rather than a semantic turn grouping because this function doesn't
need to preserve tool_use/tool_result pairing — truncating the content
of a tool_result doesn't break the pairing, only removing the message
entirely would. We never remove messages here.
Args:
messages: OpenAI-format message list (role/content/tool_call_id).
max_tool_result_chars: Maximum character length to keep per tool_result
content in the compactable region. Older content beyond this is
replaced with a truncation marker.
keep_recent_turns: Number of most-recent messages to leave untouched.
Returns:
A new list (deep-copied). The original list is not mutated.
"""
if not messages:
return messages
msgs = copy.deepcopy(messages)
protected_start = max(0, len(msgs) - keep_recent_turns)
truncated_count = 0
chars_removed = 0
for i in range(protected_start):
msg = msgs[i]
# Only tool-role messages have tool_result content in OpenAI format
if msg.get("role") != "tool":
continue
content = msg.get("content", "")
if not isinstance(content, str):
continue
if len(content) <= max_tool_result_chars:
continue
removed = len(content) - max_tool_result_chars
msg["content"] = (
content[:max_tool_result_chars]
+ _TRUNCATION_MARKER.format(removed=removed)
)
truncated_count += 1
chars_removed += removed
if truncated_count > 0:
logger.debug(
"Truncated %d tool_result(s), freed ~%d chars (~%d tokens)",
truncated_count, chars_removed, chars_removed // 4,
)
return msgs