Skip to content

Commit b52c301

Browse files
committed
Discard old history items based on available tokens
1 parent e799ee6 commit b52c301

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

src/ai/chatbot.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,24 @@ def _add_to_history(self, role: str, content: str) -> None:
6868
# Keep history within limits, but preserve system message
6969
if len(self.history) > self.max_history + 1: # +1 for system message
7070
# Remove oldest messages but keep system message
71-
self.history = [self.history[0]] + self.history[-(self.max_history) :]
71+
self.history = [self.history[0]] + self.history[-(self.max_history):]
72+
73+
# Check total token usage and trim if needed
74+
_, _, available = self.get_context_limits()
75+
current_tokens = sum(self.count_tokens(msg["content"]) for msg in self.history)
76+
77+
if current_tokens > available:
78+
# Always keep system message and last 2 messages of conversation
79+
preserved = [self.history[0]] + self.history[-2:]
80+
older_messages = self.history[1:-2]
81+
82+
# Remove older messages until we're under the limit
83+
while current_tokens > available and older_messages:
84+
removed = older_messages.pop()
85+
current_tokens -= self.count_tokens(removed["content"])
86+
87+
# Reconstruct history with remaining messages
88+
self.history = preserved if not older_messages else [self.history[0]] + older_messages + self.history[-2:]
7289

7390
def count_tokens(self, text: str) -> int:
7491
"""Estimate token count for a string"""

0 commit comments

Comments
 (0)