feat(agent): implement memory consolidation and context management
- Introduced a memory consolidator to summarize older messages when the context window exceeds a specified limit, preserving key facts and tool results. - Enhanced the AgentEngine to utilize the new token estimator and memory consolidator for improved context window management. - Implemented logic to compress message history when approaching token limits, ensuring efficient use of context. - Added unit tests for the memory consolidator and token estimator to validate functionality and performance. - Updated tool execution to validate parameters against JSON schema before execution, improving error handling and robustness.
This commit is contained in:
@@ -0,0 +1,99 @@
|
||||
package token
|
||||
|
||||
import (
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
)
|
||||
|
||||
// DefaultContextThresholdRatio is the ratio of context window usage that triggers compression.
|
||||
// When message tokens exceed MaxContextTokens * threshold, old messages are trimmed.
|
||||
const DefaultContextThresholdRatio = 0.8
|
||||
|
||||
// CompressContext trims older messages to bring total token count below the threshold.
|
||||
// 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,
|
||||
) []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
|
||||
|
||||
for i, group := range groups {
|
||||
groupTokens := 0
|
||||
for _, msg := range group {
|
||||
groupTokens += estimator.EstimateMessage(&msg)
|
||||
}
|
||||
freed += groupTokens
|
||||
removeUpTo = i + 1
|
||||
if freed >= tokensToFree {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// 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++ {
|
||||
remaining = append(remaining, groups[i]...)
|
||||
}
|
||||
remaining = append(remaining, lastMsg)
|
||||
|
||||
return remaining
|
||||
}
|
||||
|
||||
// groupToolMessages groups middle messages into logical units:
|
||||
// - An assistant message with tool_calls + its corresponding tool result messages = one group
|
||||
// - A standalone message (user, assistant without tool_calls) = one group
|
||||
//
|
||||
// This ensures tool_call/tool_result pairs are never split during compression.
|
||||
func groupToolMessages(messages []chat.Message) [][]chat.Message {
|
||||
var groups [][]chat.Message
|
||||
i := 0
|
||||
for i < len(messages) {
|
||||
msg := messages[i]
|
||||
|
||||
// If this is an assistant message with tool_calls, group it with following tool results
|
||||
if msg.Role == "assistant" && len(msg.ToolCalls) > 0 {
|
||||
group := []chat.Message{msg}
|
||||
i++
|
||||
// Collect all following tool result messages
|
||||
for i < len(messages) && messages[i].Role == "tool" {
|
||||
group = append(group, messages[i])
|
||||
i++
|
||||
}
|
||||
groups = append(groups, group)
|
||||
} else {
|
||||
groups = append(groups, []chat.Message{msg})
|
||||
i++
|
||||
}
|
||||
}
|
||||
return groups
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
// Package token provides token estimation for LLM context window management.
|
||||
package token
|
||||
|
||||
import (
|
||||
"unicode"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
)
|
||||
|
||||
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
|
||||
)
|
||||
|
||||
// Estimator estimates token counts for messages and strings.
|
||||
// Uses a character-based heuristic that accounts for CJK characters.
|
||||
type Estimator struct {
|
||||
charsPerToken float64
|
||||
}
|
||||
|
||||
// NewEstimator creates a token estimator.
|
||||
// If charsPerToken <= 0, DefaultCharsPerToken is used.
|
||||
func NewEstimator(charsPerToken float64) *Estimator {
|
||||
if charsPerToken <= 0 {
|
||||
charsPerToken = DefaultCharsPerToken
|
||||
}
|
||||
return &Estimator{charsPerToken: charsPerToken}
|
||||
}
|
||||
|
||||
// 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.
|
||||
func (e *Estimator) EstimateMessages(messages []chat.Message) int {
|
||||
total := 0
|
||||
for i := range messages {
|
||||
total += e.EstimateMessage(&messages[i])
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
// EstimateMessage estimates 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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package token
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestEstimator(t *testing.T) {
|
||||
e := NewEstimator(0) // use default
|
||||
|
||||
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)
|
||||
})
|
||||
|
||||
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)
|
||||
})
|
||||
|
||||
t.Run("CJK is more tokens per char than latin", func(t *testing.T) {
|
||||
// Same number of characters, but CJK should estimate more tokens
|
||||
latin := strings.Repeat("a", 100)
|
||||
cjk := strings.Repeat("中", 100)
|
||||
latinTokens := e.EstimateString(latin)
|
||||
cjkTokens := e.EstimateString(cjk)
|
||||
assert.Greater(t, cjkTokens, latinTokens,
|
||||
"CJK text should estimate more tokens per character")
|
||||
})
|
||||
|
||||
t.Run("message estimation includes overhead", func(t *testing.T) {
|
||||
msg := chat.Message{
|
||||
Role: "assistant",
|
||||
Content: "hello",
|
||||
}
|
||||
tokens := e.EstimateMessage(&msg)
|
||||
contentTokens := e.EstimateString("hello")
|
||||
assert.Greater(t, tokens, contentTokens,
|
||||
"message tokens should include overhead beyond just content")
|
||||
})
|
||||
|
||||
t.Run("message with tool calls", func(t *testing.T) {
|
||||
msg := chat.Message{
|
||||
Role: "assistant",
|
||||
Content: "thinking...",
|
||||
ToolCalls: []chat.ToolCall{
|
||||
{
|
||||
Function: chat.FunctionCall{
|
||||
Name: "knowledge_search",
|
||||
Arguments: `{"query": "test"}`,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
tokens := e.EstimateMessage(&msg)
|
||||
assert.Greater(t, tokens, 10)
|
||||
})
|
||||
|
||||
t.Run("estimate messages", func(t *testing.T) {
|
||||
messages := []chat.Message{
|
||||
{Role: "system", Content: "You are a helpful assistant."},
|
||||
{Role: "user", Content: "Hello"},
|
||||
{Role: "assistant", Content: "Hi there!"},
|
||||
}
|
||||
tokens := e.EstimateMessages(messages)
|
||||
assert.Greater(t, tokens, 10)
|
||||
})
|
||||
}
|
||||
|
||||
func TestCompressContext(t *testing.T) {
|
||||
e := NewEstimator(0)
|
||||
|
||||
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)
|
||||
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
|
||||
require.GreaterOrEqual(t, len(result), 2)
|
||||
assert.Equal(t, "system", result[0].Role)
|
||||
assert.Equal(t, "current query", result[len(result)-1].Content)
|
||||
})
|
||||
|
||||
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
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("zero maxTokens returns unchanged", func(t *testing.T) {
|
||||
messages := []chat.Message{
|
||||
{Role: "system", Content: "system"},
|
||||
{Role: "user", Content: "hello"},
|
||||
}
|
||||
result := CompressContext(messages, e, 0)
|
||||
assert.Equal(t, messages, result)
|
||||
})
|
||||
|
||||
t.Run("two messages returns unchanged", func(t *testing.T) {
|
||||
messages := []chat.Message{
|
||||
{Role: "system", Content: "system"},
|
||||
{Role: "user", Content: "hello"},
|
||||
}
|
||||
result := CompressContext(messages, e, 1) // even with tiny limit
|
||||
assert.Equal(t, messages, result)
|
||||
})
|
||||
}
|
||||
|
||||
func TestGroupToolMessages(t *testing.T) {
|
||||
t.Run("standalone messages", func(t *testing.T) {
|
||||
messages := []chat.Message{
|
||||
{Role: "user", Content: "hello"},
|
||||
{Role: "assistant", Content: "hi"},
|
||||
}
|
||||
groups := groupToolMessages(messages)
|
||||
assert.Len(t, groups, 2)
|
||||
})
|
||||
|
||||
t.Run("tool call with results grouped", func(t *testing.T) {
|
||||
messages := []chat.Message{
|
||||
{Role: "user", Content: "search for X"},
|
||||
{Role: "assistant", Content: "thinking", ToolCalls: []chat.ToolCall{
|
||||
{ID: "call_1", Function: chat.FunctionCall{Name: "search"}},
|
||||
{ID: "call_2", Function: chat.FunctionCall{Name: "fetch"}},
|
||||
}},
|
||||
{Role: "tool", Content: "result1", ToolCallID: "call_1"},
|
||||
{Role: "tool", Content: "result2", ToolCallID: "call_2"},
|
||||
{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
|
||||
b, _ := json.Marshal(groups)
|
||||
fmt.Println(string(b))
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user