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:
@@ -9,39 +9,35 @@ import (
|
||||
const DefaultContextThresholdRatio = 0.8
|
||||
|
||||
// CompressContext trims older messages to bring total token count below the threshold.
|
||||
// currentTokens is the caller's best estimate of the current context size (from API
|
||||
// Usage when available, falling back to BPE estimation). The estimator is still used
|
||||
// internally for per-message-group cost calculation during trimming.
|
||||
//
|
||||
// It preserves:
|
||||
// - The first message (system prompt)
|
||||
// - The last message (current user query)
|
||||
// - tool_call / tool_result message pairs (never splits them)
|
||||
//
|
||||
// Returns the compressed message slice. If no compression is needed, returns the original.
|
||||
func CompressContext(
|
||||
messages []chat.Message,
|
||||
estimator *Estimator,
|
||||
maxTokens int,
|
||||
currentTokens int,
|
||||
) []chat.Message {
|
||||
if maxTokens <= 0 || len(messages) <= 2 {
|
||||
return messages
|
||||
}
|
||||
|
||||
threshold := int(float64(maxTokens) * DefaultContextThresholdRatio)
|
||||
currentTokens := estimator.EstimateMessages(messages)
|
||||
if currentTokens <= threshold {
|
||||
return messages
|
||||
}
|
||||
|
||||
// Strategy: keep system prompt (first) + current query (last),
|
||||
// trim from the oldest messages inward, respecting tool_call/tool_result boundaries.
|
||||
|
||||
systemMsg := messages[0]
|
||||
lastMsg := messages[len(messages)-1]
|
||||
middle := messages[1 : len(messages)-1]
|
||||
|
||||
// Find groups of messages that form tool_call/tool_result pairs.
|
||||
// A group = one assistant message with tool_calls + all following tool result messages.
|
||||
groups := groupToolMessages(middle)
|
||||
|
||||
// Remove groups from the front until we're under the threshold.
|
||||
tokensToFree := currentTokens - threshold
|
||||
freed := 0
|
||||
removeUpTo := 0
|
||||
@@ -58,7 +54,6 @@ func CompressContext(
|
||||
}
|
||||
}
|
||||
|
||||
// Rebuild messages: system + remaining groups + current query
|
||||
remaining := make([]chat.Message, 0, len(messages))
|
||||
remaining = append(remaining, systemMsg)
|
||||
for i := removeUpTo; i < len(groups); i++ {
|
||||
|
||||
@@ -1,116 +1,87 @@
|
||||
// Package token provides token estimation for LLM context window management.
|
||||
//
|
||||
// The primary source of truth for token counts is the model API's Usage field
|
||||
// (types.TokenUsage), returned with every LLM response. This package serves as
|
||||
// a supplementary estimator used in two scenarios:
|
||||
//
|
||||
// 1. Delta estimation — after an LLM call, new messages (assistant reply +
|
||||
// tool results) are appended before the next call. The Estimator computes
|
||||
// the token cost of these new messages so the engine can decide whether
|
||||
// context compression is needed without making an extra API round-trip.
|
||||
//
|
||||
// 2. First-round fallback — on the very first round of a session, no prior
|
||||
// API Usage is available, so the Estimator provides a full estimate.
|
||||
//
|
||||
// The encoding used (cl100k_base) is an approximation. Different model families
|
||||
// use different tokenizers, so the numbers will not be exact for non-OpenAI
|
||||
// models. This is acceptable because the estimate only needs to be close enough
|
||||
// to trigger compression at roughly the right time; over- or under-estimating
|
||||
// by a small margin is corrected on the next API call.
|
||||
package token
|
||||
|
||||
import (
|
||||
"unicode"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/tiktoken-go/tokenizer"
|
||||
)
|
||||
|
||||
const (
|
||||
// DefaultCharsPerToken is a blended ratio for mixed English/CJK text.
|
||||
// English ≈ 4 chars/token, CJK ≈ 1.5 chars/token, blended ≈ 3.5.
|
||||
DefaultCharsPerToken = 3.5
|
||||
|
||||
// perMessageOverhead is the estimated token overhead per message
|
||||
// (role label, formatting, separator tokens).
|
||||
perMessageOverhead = 4
|
||||
perMessageOverhead = 3
|
||||
perConversationTail = 3
|
||||
)
|
||||
|
||||
// Estimator estimates token counts for messages and strings.
|
||||
// Uses a character-based heuristic that accounts for CJK characters.
|
||||
// Estimator counts tokens for messages and strings using BPE tokenization.
|
||||
// It is intended for incremental (delta) estimation between LLM calls; the
|
||||
// authoritative token count comes from the API's Usage response.
|
||||
type Estimator struct {
|
||||
charsPerToken float64
|
||||
codec tokenizer.Codec
|
||||
}
|
||||
|
||||
// NewEstimator creates a token estimator.
|
||||
// If charsPerToken <= 0, DefaultCharsPerToken is used.
|
||||
func NewEstimator(charsPerToken float64) *Estimator {
|
||||
if charsPerToken <= 0 {
|
||||
charsPerToken = DefaultCharsPerToken
|
||||
// NewEstimator creates a token estimator using the cl100k_base encoding.
|
||||
func NewEstimator() (*Estimator, error) {
|
||||
codec, err := tokenizer.Get(tokenizer.Cl100kBase)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("token: failed to initialize tokenizer: %w", err)
|
||||
}
|
||||
return &Estimator{charsPerToken: charsPerToken}
|
||||
return &Estimator{codec: codec}, nil
|
||||
}
|
||||
|
||||
// EstimateString estimates the token count for a string.
|
||||
// It uses a CJK-aware heuristic: CJK characters are counted at ~1.5 chars/token,
|
||||
// while ASCII/Latin characters use the configured charsPerToken ratio.
|
||||
func (e *Estimator) EstimateString(s string) int {
|
||||
if len(s) == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
var cjkRunes, otherRunes int
|
||||
for _, r := range s {
|
||||
if isCJK(r) {
|
||||
cjkRunes++
|
||||
} else {
|
||||
otherRunes++
|
||||
}
|
||||
}
|
||||
|
||||
// CJK characters are roughly 1.5 chars per token
|
||||
cjkTokens := float64(cjkRunes) / 1.5
|
||||
otherTokens := float64(otherRunes) / e.charsPerToken
|
||||
|
||||
return int(cjkTokens+otherTokens) + 1 // +1 to avoid underestimation
|
||||
}
|
||||
|
||||
// EstimateMessages estimates the total token count for a slice of chat messages.
|
||||
// EstimateMessages returns the estimated token count for a slice of messages.
|
||||
// Prefer using API Usage for the full context and this method only for deltas.
|
||||
func (e *Estimator) EstimateMessages(messages []chat.Message) int {
|
||||
total := 0
|
||||
for i := range messages {
|
||||
total += e.EstimateMessage(&messages[i])
|
||||
}
|
||||
total += perConversationTail
|
||||
return total
|
||||
}
|
||||
|
||||
// EstimateMessage estimates the token count for a single message.
|
||||
// EstimateString returns the token count for a string using BPE tokenization.
|
||||
func (e *Estimator) EstimateString(s string) int {
|
||||
if len(s) == 0 {
|
||||
return 0
|
||||
}
|
||||
ids, _, err := e.codec.Encode(s)
|
||||
if err != nil {
|
||||
return (len(s) + 3) / 4
|
||||
}
|
||||
return len(ids)
|
||||
}
|
||||
|
||||
// EstimateMessage returns the token count for a single message.
|
||||
func (e *Estimator) EstimateMessage(msg *chat.Message) int {
|
||||
tokens := perMessageOverhead
|
||||
tokens += e.EstimateString(msg.Role)
|
||||
tokens += e.EstimateString(msg.Content)
|
||||
tokens += e.EstimateString(msg.Name)
|
||||
|
||||
// Tool calls in assistant messages
|
||||
for _, tc := range msg.ToolCalls {
|
||||
tokens += e.EstimateString(tc.Function.Name)
|
||||
tokens += e.EstimateString(tc.Function.Arguments)
|
||||
tokens += 4 // overhead for tool call structure
|
||||
tokens += 4
|
||||
}
|
||||
|
||||
return tokens
|
||||
}
|
||||
|
||||
// isCJK checks if a rune is a CJK (Chinese, Japanese, Korean) character.
|
||||
func isCJK(r rune) bool {
|
||||
// CJK Unified Ideographs
|
||||
if r >= 0x4E00 && r <= 0x9FFF {
|
||||
return true
|
||||
}
|
||||
// CJK Unified Ideographs Extension A
|
||||
if r >= 0x3400 && r <= 0x4DBF {
|
||||
return true
|
||||
}
|
||||
// CJK Unified Ideographs Extension B
|
||||
if r >= 0x20000 && r <= 0x2A6DF {
|
||||
return true
|
||||
}
|
||||
// CJK Compatibility Ideographs
|
||||
if r >= 0xF900 && r <= 0xFAFF {
|
||||
return true
|
||||
}
|
||||
// Hiragana + Katakana
|
||||
if r >= 0x3040 && r <= 0x30FF {
|
||||
return true
|
||||
}
|
||||
// Hangul Syllables
|
||||
if r >= 0xAC00 && r <= 0xD7AF {
|
||||
return true
|
||||
}
|
||||
// Full-width characters
|
||||
if unicode.Is(unicode.Han, r) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -12,34 +12,34 @@ import (
|
||||
)
|
||||
|
||||
func TestEstimator(t *testing.T) {
|
||||
e := NewEstimator(0) // use default
|
||||
e, err := NewEstimator()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create estimator: %v", err)
|
||||
}
|
||||
|
||||
t.Run("empty string", func(t *testing.T) {
|
||||
assert.Equal(t, 0, e.EstimateString(""))
|
||||
})
|
||||
|
||||
t.Run("english text", func(t *testing.T) {
|
||||
// "hello world" = 11 chars ≈ 11/3.5 + 1 ≈ 4 tokens
|
||||
tokens := e.EstimateString("hello world")
|
||||
assert.Greater(t, tokens, 0)
|
||||
assert.Less(t, tokens, 20)
|
||||
assert.Equal(t, 2, tokens)
|
||||
})
|
||||
|
||||
t.Run("chinese text", func(t *testing.T) {
|
||||
// 10 Chinese chars at ~1.5 chars/token ≈ 7 tokens
|
||||
tokens := e.EstimateString("你好世界测试数据中文")
|
||||
assert.Greater(t, tokens, 3)
|
||||
assert.Less(t, tokens, 20)
|
||||
fmt.Println(tokens)
|
||||
assert.Greater(t, tokens, 0)
|
||||
})
|
||||
|
||||
t.Run("CJK is more tokens per char than latin", func(t *testing.T) {
|
||||
// Same number of characters, but CJK should estimate more tokens
|
||||
t.Run("CJK produces more tokens per char than latin", func(t *testing.T) {
|
||||
latin := strings.Repeat("a", 100)
|
||||
cjk := strings.Repeat("中", 100)
|
||||
latinTokens := e.EstimateString(latin)
|
||||
cjkTokens := e.EstimateString(cjk)
|
||||
fmt.Println(latinTokens, cjkTokens)
|
||||
assert.Greater(t, cjkTokens, latinTokens,
|
||||
"CJK text should estimate more tokens per character")
|
||||
"CJK text should produce more tokens per character")
|
||||
})
|
||||
|
||||
t.Run("message estimation includes overhead", func(t *testing.T) {
|
||||
@@ -49,6 +49,7 @@ func TestEstimator(t *testing.T) {
|
||||
}
|
||||
tokens := e.EstimateMessage(&msg)
|
||||
contentTokens := e.EstimateString("hello")
|
||||
fmt.Println(tokens, contentTokens)
|
||||
assert.Greater(t, tokens, contentTokens,
|
||||
"message tokens should include overhead beyond just content")
|
||||
})
|
||||
@@ -82,26 +83,28 @@ func TestEstimator(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCompressContext(t *testing.T) {
|
||||
e := NewEstimator(0)
|
||||
e, err := NewEstimator()
|
||||
require.NoError(t, err)
|
||||
|
||||
t.Run("no compression needed", func(t *testing.T) {
|
||||
messages := []chat.Message{
|
||||
{Role: "system", Content: "system prompt"},
|
||||
{Role: "user", Content: "hello"},
|
||||
}
|
||||
result := CompressContext(messages, e, 100000)
|
||||
tokens := e.EstimateMessages(messages)
|
||||
result := CompressContext(messages, e, 100000, tokens)
|
||||
assert.Equal(t, messages, result)
|
||||
})
|
||||
|
||||
t.Run("preserves system and last message", func(t *testing.T) {
|
||||
// Create messages that exceed the token limit
|
||||
messages := []chat.Message{
|
||||
{Role: "system", Content: "system prompt"},
|
||||
{Role: "user", Content: strings.Repeat("old message ", 1000)},
|
||||
{Role: "assistant", Content: strings.Repeat("old response ", 1000)},
|
||||
{Role: "user", Content: "current query"},
|
||||
}
|
||||
result := CompressContext(messages, e, 100) // very low limit to force compression
|
||||
tokens := e.EstimateMessages(messages)
|
||||
result := CompressContext(messages, e, 100, tokens)
|
||||
require.GreaterOrEqual(t, len(result), 2)
|
||||
assert.Equal(t, "system", result[0].Role)
|
||||
assert.Equal(t, "current query", result[len(result)-1].Content)
|
||||
@@ -110,27 +113,23 @@ func TestCompressContext(t *testing.T) {
|
||||
t.Run("keeps tool_call and tool_result paired", func(t *testing.T) {
|
||||
messages := []chat.Message{
|
||||
{Role: "system", Content: "system prompt"},
|
||||
// Old conversation
|
||||
{Role: "user", Content: strings.Repeat("x", 500)},
|
||||
{Role: "assistant", Content: strings.Repeat("y", 500)},
|
||||
// Tool interaction that should stay together
|
||||
{Role: "assistant", Content: "thinking", ToolCalls: []chat.ToolCall{
|
||||
{ID: "call_1", Function: chat.FunctionCall{Name: "search", Arguments: `{"q":"test"}`}},
|
||||
}},
|
||||
{Role: "tool", Content: strings.Repeat("result ", 100), ToolCallID: "call_1", Name: "search"},
|
||||
// Current query
|
||||
{Role: "user", Content: "what did you find?"},
|
||||
}
|
||||
|
||||
result := CompressContext(messages, e, 200) // force some compression
|
||||
tokens := e.EstimateMessages(messages)
|
||||
result := CompressContext(messages, e, 200, tokens)
|
||||
|
||||
b, _ := json.Marshal(result)
|
||||
fmt.Println(string(b))
|
||||
|
||||
// Check that tool_call and tool_result are still paired
|
||||
for i, msg := range result {
|
||||
if msg.Role == "tool" {
|
||||
// The previous message should be an assistant with tool_calls
|
||||
require.Greater(t, i, 0)
|
||||
assert.Equal(t, "assistant", result[i-1].Role)
|
||||
assert.Greater(t, len(result[i-1].ToolCalls), 0)
|
||||
@@ -143,7 +142,7 @@ func TestCompressContext(t *testing.T) {
|
||||
{Role: "system", Content: "system"},
|
||||
{Role: "user", Content: "hello"},
|
||||
}
|
||||
result := CompressContext(messages, e, 0)
|
||||
result := CompressContext(messages, e, 0, 0)
|
||||
assert.Equal(t, messages, result)
|
||||
})
|
||||
|
||||
@@ -152,7 +151,7 @@ func TestCompressContext(t *testing.T) {
|
||||
{Role: "system", Content: "system"},
|
||||
{Role: "user", Content: "hello"},
|
||||
}
|
||||
result := CompressContext(messages, e, 1) // even with tiny limit
|
||||
result := CompressContext(messages, e, 1, 999)
|
||||
assert.Equal(t, messages, result)
|
||||
})
|
||||
}
|
||||
@@ -179,8 +178,8 @@ func TestGroupToolMessages(t *testing.T) {
|
||||
{Role: "user", Content: "thanks"},
|
||||
}
|
||||
groups := groupToolMessages(messages)
|
||||
assert.Len(t, groups, 3) // user, (assistant+2 tools), user
|
||||
assert.Len(t, groups[1], 3) // assistant + 2 tool results
|
||||
assert.Len(t, groups, 3)
|
||||
assert.Len(t, groups[1], 3)
|
||||
b, _ := json.Marshal(groups)
|
||||
fmt.Println(string(b))
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user