This commit is contained in:
Timothy Jaeryang Baek committed 2026-06-11 12:35:55 +01:00
1 parent 2b32568c37
commit 74a1c26713
3 files changed
+50 -8

No files matched your search

+25 -3
View File
@@ -34,10 +34,32 @@ def estimate_messages_tokens(messages: list[dict]) -> int:
return total
def should_compact(messages: list[dict], system_prompt: str) -> bool:
"""True when estimated tokens exceed the compact token threshold."""
def should_compact(
messages: list[dict],
system_prompt: str,
last_usage: dict | None = None,
new_messages_since: int = 0,
) -> bool:
"""True when estimated tokens exceed the compact token threshold.
If last_usage is provided (real data from the previous API call),
uses actual input_tokens + output_tokens as the base and only
estimates the new messages appended since that call.
Falls back to full estimation when no usage data exists.
"""
threshold = _get_threshold()
if last_usage and last_usage.get("input_tokens"):
# Real base from last API call + estimate only new additions
base = last_usage["input_tokens"] + last_usage.get("output_tokens", 0)
if new_messages_since > 0:
new_msgs = messages[-new_messages_since:]
base += estimate_messages_tokens(new_msgs)
return base > threshold
# Full estimation fallback
total = estimate_tokens(system_prompt) + estimate_messages_tokens(messages)
return total > _get_threshold()
return total > threshold
def _get_threshold() -> int: