feat(agent): enhance token management and context handling in AgentEngine

- Added token usage tracking to the AgentEngine, allowing for better estimation of current context token counts.
- Implemented a new method to estimate current tokens based on previous usage and newly appended messages, improving context management.
- Updated context window management to utilize estimated token counts for more efficient message consolidation.
- Enhanced streaming methods to include token usage information, providing better insights into LLM interactions.
- Refactored the token estimator to support BPE tokenization, ensuring accurate token counts for messages.
- Added unit tests to validate new token estimation and context management functionalities.
This commit is contained in:
wizardchen
2026-03-22 23:15:33 +08:00
committed by lyingbug
parent 0d4ceb6c96
commit 0bb1a581de
16 changed files with 247 additions and 239 deletions
+5 -5
View File
@@ -58,14 +58,14 @@ func NewConsolidator(
}
}
// ShouldConsolidate checks if the messages need consolidation based on token count.
func (c *Consolidator) ShouldConsolidate(messages []chat.Message) bool {
if c.maxTokens <= 0 || len(messages) <= 3 {
// ShouldConsolidate checks if consolidation is needed based on the caller-provided
// token estimate. The estimate should come from the model API's Usage when available.
func (c *Consolidator) ShouldConsolidate(currentTokens int) bool {
if c.maxTokens <= 0 {
return false
}
tokenCount := c.estimator.EstimateMessages(messages)
triggerAt := int(float64(c.maxTokens) * c.threshold)
return tokenCount > triggerAt
return currentTokens > triggerAt
}
// Consolidate summarizes older messages and returns a compressed message array.