fix(context): cap recent-history digest by tokens, not characters

The recent-history section injected into the system prompt was capped by character count (_MAX_HISTORY_CHARS = 32_000). Characters are a poor proxy for tokens: ~32k chars of English is ~8k tokens, but the same char count of CJK text or code can be far more, so the cap could let the section blow well past its intended size on non English/code-heavy histories.

Add a reusable truncate_text_to_tokens() helper (reusing the tiktoken
 cl100k_base encoder already used elsewhere, with a char-based fallback) and
  switch the digest cap to a token budget (_MAX_HISTORY_TOKENS = 8_000),
  matching the previous English-text size while holding regardless of
  content.
This commit is contained in:
w.antar authored and Xubin Ren committed 2026-06-17 00:47:52 +08:00
1 parent 846410f936
commit 973a5ee507
3 files changed
+51 -4

No files matched your search

+20
View File
@@ -237,6 +237,26 @@ def truncate_text(text: str, max_chars: int) -> str:
return text[:max_chars] + "\n... (truncated)"
def truncate_text_to_tokens(text: str, max_tokens: int) -> str:
"""Truncate text to a token budget with a stable suffix.
Unlike :func:`truncate_text`, this measures actual tokens, so the cap holds
regardless of language or content (CJK and code cost more tokens per char).
Falls back to a char-based estimate (~4 chars/token) if tiktoken is
unavailable.
"""
if max_tokens <= 0:
return text
try:
enc = tiktoken.get_encoding("cl100k_base")
tokens = enc.encode(text)
if len(tokens) <= max_tokens:
return text
return enc.decode(tokens[:max_tokens]) + "\n... (truncated)"
except Exception:
return truncate_text(text, max_tokens * 4)
def find_legal_message_start(messages: list[dict[str, Any]]) -> int:
"""Find the first index whose tool results have matching assistant calls."""
declared: set[str] = set()