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:
wizardchen
2026-03-19 22:01:42 +08:00
committed by lyingbug
parent 9f4fb39e10
commit 0851d6d656
13 changed files with 1487 additions and 6 deletions
+234
View File
@@ -0,0 +1,234 @@
package tools
import (
"encoding/json"
"fmt"
"strings"
)
// ValidationError describes a specific parameter validation failure.
type ValidationError struct {
Param string // parameter name (or "" for top-level errors)
Message string // human-readable error description
}
// ValidateParams checks args against the JSON Schema declared by tool.Parameters().
// Returns nil if valid, or a list of validation errors.
//
// Supported checks:
// - required: ensures all required fields are present and non-null
// - type: verifies the JSON type matches (string, number, integer, boolean, array, object)
// - enum: checks the value is in the allowed set
// - minimum / maximum: numeric bounds
// - minLength / maxLength: string length bounds
func ValidateParams(args json.RawMessage, schema json.RawMessage) []ValidationError {
if len(schema) == 0 || len(args) == 0 {
return nil
}
var schemaDef map[string]any
if err := json.Unmarshal(schema, &schemaDef); err != nil {
return nil
}
properties, _ := schemaDef["properties"].(map[string]any)
if len(properties) == 0 {
return nil
}
var argsMap map[string]any
if err := json.Unmarshal(args, &argsMap); err != nil {
return nil
}
var errs []ValidationError
// Check required fields
if reqRaw, ok := schemaDef["required"]; ok {
if reqList, ok := reqRaw.([]any); ok {
for _, r := range reqList {
fieldName, ok := r.(string)
if !ok {
continue
}
val, exists := argsMap[fieldName]
if !exists || val == nil {
errs = append(errs, ValidationError{
Param: fieldName,
Message: fmt.Sprintf("required parameter '%s' is missing", fieldName),
})
}
}
}
}
// Validate each provided argument against its property schema
for key, val := range argsMap {
propDef, exists := properties[key]
if !exists {
continue // extra params are allowed (LLMs sometimes add them)
}
prop, ok := propDef.(map[string]any)
if !ok {
continue
}
propErrs := validateProperty(key, val, prop)
errs = append(errs, propErrs...)
}
return errs
}
// validateProperty validates a single parameter value against its schema definition.
func validateProperty(name string, val any, prop map[string]any) []ValidationError {
if val == nil {
return nil // nil values are handled by required check
}
var errs []ValidationError
targetType, _ := prop["type"].(string)
// Type check
if targetType != "" && !checkType(val, targetType) {
errs = append(errs, ValidationError{
Param: name,
Message: fmt.Sprintf("parameter '%s' should be type '%s'", name, targetType),
})
return errs // skip further checks if type is wrong
}
// Enum check
if enumRaw, ok := prop["enum"]; ok {
if enumList, ok := enumRaw.([]any); ok && len(enumList) > 0 {
if !isInEnum(val, enumList) {
allowed := formatEnum(enumList)
errs = append(errs, ValidationError{
Param: name,
Message: fmt.Sprintf("parameter '%s' must be one of [%s]", name, allowed),
})
}
}
}
// Numeric bounds
if targetType == "number" || targetType == "integer" {
numVal := toFloat64(val)
if minVal, ok := getFloat(prop, "minimum"); ok && numVal < minVal {
errs = append(errs, ValidationError{
Param: name,
Message: fmt.Sprintf("parameter '%s' must be >= %v", name, minVal),
})
}
if maxVal, ok := getFloat(prop, "maximum"); ok && numVal > maxVal {
errs = append(errs, ValidationError{
Param: name,
Message: fmt.Sprintf("parameter '%s' must be <= %v", name, maxVal),
})
}
}
// String length bounds
if targetType == "string" {
if s, ok := val.(string); ok {
if minLen, ok := getFloat(prop, "minLength"); ok && float64(len(s)) < minLen {
errs = append(errs, ValidationError{
Param: name,
Message: fmt.Sprintf("parameter '%s' must have at least %d characters",
name, int(minLen)),
})
}
if maxLen, ok := getFloat(prop, "maxLength"); ok && float64(len(s)) > maxLen {
errs = append(errs, ValidationError{
Param: name,
Message: fmt.Sprintf("parameter '%s' must have at most %d characters",
name, int(maxLen)),
})
}
}
}
return errs
}
// checkType verifies that val matches the expected JSON Schema type.
func checkType(val any, targetType string) bool {
switch targetType {
case "string":
_, ok := val.(string)
return ok
case "number":
_, ok := val.(float64)
return ok
case "integer":
f, ok := val.(float64)
return ok && f == float64(int64(f))
case "boolean":
_, ok := val.(bool)
return ok
case "array":
_, ok := val.([]any)
return ok
case "object":
_, ok := val.(map[string]any)
return ok
default:
return true // unknown type, don't reject
}
}
// isInEnum checks if val matches any value in the enum list.
func isInEnum(val any, enumList []any) bool {
for _, e := range enumList {
if fmt.Sprintf("%v", val) == fmt.Sprintf("%v", e) {
return true
}
}
return false
}
// formatEnum formats enum values for error messages.
func formatEnum(enumList []any) string {
parts := make([]string, len(enumList))
for i, e := range enumList {
parts[i] = fmt.Sprintf("%v", e)
}
return strings.Join(parts, ", ")
}
// getFloat extracts a float64 value from a map by key.
func getFloat(m map[string]any, key string) (float64, bool) {
v, ok := m[key]
if !ok {
return 0, false
}
f, ok := v.(float64)
return f, ok
}
// toFloat64 converts a numeric value to float64.
func toFloat64(val any) float64 {
switch v := val.(type) {
case float64:
return v
case int64:
return float64(v)
case int:
return float64(v)
default:
return 0
}
}
// FormatValidationErrors formats a list of validation errors into a human-readable string.
func FormatValidationErrors(errs []ValidationError) string {
if len(errs) == 0 {
return ""
}
msgs := make([]string, len(errs))
for i, e := range errs {
msgs[i] = e.Message
}
return "Parameter validation failed: " + strings.Join(msgs, "; ")
}
+144
View File
@@ -0,0 +1,144 @@
package tools
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestValidateParams(t *testing.T) {
schema := json.RawMessage(`{
"type": "object",
"properties": {
"query": {"type": "string", "minLength": 1},
"limit": {"type": "integer", "minimum": 1, "maximum": 100},
"mode": {"type": "string", "enum": ["fast", "deep"]},
"score": {"type": "number", "minimum": 0, "maximum": 1},
"enabled": {"type": "boolean"}
},
"required": ["query"]
}`)
t.Run("valid params pass", func(t *testing.T) {
args := json.RawMessage(`{"query": "hello", "limit": 10, "mode": "fast"}`)
errs := ValidateParams(args, schema)
assert.Empty(t, errs)
})
t.Run("missing required field", func(t *testing.T) {
args := json.RawMessage(`{"limit": 10}`)
errs := ValidateParams(args, schema)
require.Len(t, errs, 1)
assert.Equal(t, "query", errs[0].Param)
assert.Contains(t, errs[0].Message, "required")
})
t.Run("null required field", func(t *testing.T) {
args := json.RawMessage(`{"query": null}`)
errs := ValidateParams(args, schema)
require.Len(t, errs, 1)
assert.Contains(t, errs[0].Message, "required")
})
t.Run("wrong type", func(t *testing.T) {
args := json.RawMessage(`{"query": 123}`)
errs := ValidateParams(args, schema)
require.Len(t, errs, 1)
assert.Equal(t, "query", errs[0].Param)
assert.Contains(t, errs[0].Message, "type")
})
t.Run("enum violation", func(t *testing.T) {
args := json.RawMessage(`{"query": "test", "mode": "slow"}`)
errs := ValidateParams(args, schema)
require.Len(t, errs, 1)
assert.Equal(t, "mode", errs[0].Param)
assert.Contains(t, errs[0].Message, "one of")
})
t.Run("minimum violation", func(t *testing.T) {
args := json.RawMessage(`{"query": "test", "limit": 0}`)
errs := ValidateParams(args, schema)
require.Len(t, errs, 1)
assert.Equal(t, "limit", errs[0].Param)
assert.Contains(t, errs[0].Message, ">= 1")
})
t.Run("maximum violation", func(t *testing.T) {
args := json.RawMessage(`{"query": "test", "limit": 200}`)
errs := ValidateParams(args, schema)
require.Len(t, errs, 1)
assert.Equal(t, "limit", errs[0].Param)
assert.Contains(t, errs[0].Message, "<= 100")
})
t.Run("minLength violation", func(t *testing.T) {
args := json.RawMessage(`{"query": ""}`)
errs := ValidateParams(args, schema)
require.Len(t, errs, 1)
assert.Equal(t, "query", errs[0].Param)
assert.Contains(t, errs[0].Message, "at least 1 characters")
})
t.Run("number bounds", func(t *testing.T) {
args := json.RawMessage(`{"query": "test", "score": 1.5}`)
errs := ValidateParams(args, schema)
require.Len(t, errs, 1)
assert.Equal(t, "score", errs[0].Param)
})
t.Run("multiple errors", func(t *testing.T) {
args := json.RawMessage(`{"limit": -1, "mode": "invalid"}`)
errs := ValidateParams(args, schema)
assert.GreaterOrEqual(t, len(errs), 3) // missing query + limit min + mode enum
})
t.Run("extra params allowed", func(t *testing.T) {
args := json.RawMessage(`{"query": "test", "unknown_param": "value"}`)
errs := ValidateParams(args, schema)
assert.Empty(t, errs)
})
t.Run("nil schema returns nil", func(t *testing.T) {
args := json.RawMessage(`{"query": "test"}`)
errs := ValidateParams(args, nil)
assert.Nil(t, errs)
})
t.Run("empty args returns nil", func(t *testing.T) {
errs := ValidateParams(nil, schema)
assert.Nil(t, errs)
})
t.Run("boolean type check", func(t *testing.T) {
args := json.RawMessage(`{"query": "test", "enabled": "yes"}`)
errs := ValidateParams(args, schema)
require.Len(t, errs, 1)
assert.Equal(t, "enabled", errs[0].Param)
assert.Contains(t, errs[0].Message, "boolean")
})
}
func TestFormatValidationErrors(t *testing.T) {
t.Run("empty errors", func(t *testing.T) {
assert.Equal(t, "", FormatValidationErrors(nil))
})
t.Run("single error", func(t *testing.T) {
errs := []ValidationError{{Param: "q", Message: "required parameter 'q' is missing"}}
result := FormatValidationErrors(errs)
assert.Contains(t, result, "Parameter validation failed")
assert.Contains(t, result, "required parameter 'q' is missing")
})
t.Run("multiple errors joined", func(t *testing.T) {
errs := []ValidationError{
{Param: "a", Message: "error a"},
{Param: "b", Message: "error b"},
}
result := FormatValidationErrors(errs)
assert.Contains(t, result, "error a; error b")
})
}
+37 -1
View File
@@ -15,7 +15,8 @@ const toolErrorHint = "\n\n[Analyze the error above and try a different approach
// ToolRegistry manages the registration and retrieval of tools
type ToolRegistry struct {
tools map[string]types.Tool
tools map[string]types.Tool
maxToolOutputSize int // maximum chars for tool output (0 = use DefaultMaxToolOutput)
}
// NewToolRegistry creates a new tool registry
@@ -25,6 +26,20 @@ func NewToolRegistry() *ToolRegistry {
}
}
// SetMaxToolOutputSize sets the maximum character length for tool output.
// Values <= 0 will use DefaultMaxToolOutput.
func (r *ToolRegistry) SetMaxToolOutputSize(maxChars int) {
r.maxToolOutputSize = maxChars
}
// getMaxToolOutput returns the effective max tool output size.
func (r *ToolRegistry) getMaxToolOutput() int {
if r.maxToolOutputSize > 0 {
return r.maxToolOutputSize
}
return DefaultMaxToolOutput
}
// RegisterTool adds a tool to the registry.
// If a tool with the same name is already registered, the existing one is kept
// (first-wins) to prevent tool execution hijacking via name collision (GHSA-67q9-58vj-32qx).
@@ -95,7 +110,28 @@ func (r *ToolRegistry) ExecuteTool(
// This handles common LLM quirks like returning "true" instead of true.
args = CastParams(args, tool.Parameters())
// Validate parameters against the tool's JSON Schema before execution.
// This catches invalid arguments early, avoiding a wasted tool execution + LLM round.
if validationErrs := ValidateParams(args, tool.Parameters()); len(validationErrs) > 0 {
errMsg := FormatValidationErrors(validationErrs) + toolErrorHint
common.PipelineWarn(ctx, "AgentTool", "validation_failed", map[string]interface{}{
"tool": name,
"errors": errMsg,
})
return &types.ToolResult{
Success: false,
Error: errMsg,
}, nil
}
result, execErr := tool.Execute(ctx, args)
// Truncate large tool outputs to prevent context window poisoning.
maxOutput := r.getMaxToolOutput()
if result != nil && len(result.Output) > maxOutput {
result.Output = TruncateToolOutput(result.Output, maxOutput)
}
fields := map[string]interface{}{
"tool": name,
"args": args,
+57
View File
@@ -0,0 +1,57 @@
package tools
import (
"fmt"
"unicode/utf8"
)
const (
// DefaultMaxToolOutput is the default maximum character (rune) count for tool output.
// Outputs exceeding this limit are truncated with head + tail preservation.
// This counts Unicode characters (runes), not bytes, so CJK text is treated fairly.
DefaultMaxToolOutput = 16000
// headRatio controls the head/tail split when truncating (70% head, 30% tail).
headRatio = 0.7
// truncationMarkerReserve is the rune budget reserved for the truncation marker itself.
truncationMarkerReserve = 200
)
// TruncateToolOutput truncates tool output that exceeds maxChars runes, preserving
// the head (70%) and tail (30%) sections with a truncation marker in between.
// This prevents large tool results from consuming the entire LLM context window
// while keeping the most useful parts (headers/summaries at the start, conclusions at the end).
//
// maxChars is counted in Unicode characters (runes), not bytes, ensuring consistent
// behavior across English, Chinese, and other multi-byte character sets.
//
// If maxChars <= 0 or the output is within the limit, it is returned unchanged.
func TruncateToolOutput(output string, maxChars int) string {
runeCount := utf8.RuneCountInString(output)
if maxChars <= 0 || runeCount <= maxChars {
return output
}
usable := maxChars - truncationMarkerReserve
if usable <= 0 {
return string([]rune(output)[:maxChars])
}
headSize := int(float64(usable) * headRatio)
tailSize := usable - headSize
if tailSize <= 0 {
tailSize = 0
}
runes := []rune(output)
marker := fmt.Sprintf(
"\n\n... [output truncated: %d → %d chars, showing first %d + last %d] ...\n\n",
runeCount, maxChars, headSize, tailSize,
)
if tailSize == 0 {
return string(runes[:headSize]) + marker
}
return string(runes[:headSize]) + marker + string(runes[len(runes)-tailSize:])
}
+107
View File
@@ -0,0 +1,107 @@
package tools
import (
"strings"
"testing"
"unicode/utf8"
"github.com/stretchr/testify/assert"
)
func TestTruncateToolOutput(t *testing.T) {
t.Run("short output unchanged", func(t *testing.T) {
input := "hello world"
result := TruncateToolOutput(input, 1000)
assert.Equal(t, input, result)
})
t.Run("exact limit unchanged", func(t *testing.T) {
input := strings.Repeat("a", 16000)
result := TruncateToolOutput(input, 16000)
assert.Equal(t, input, result)
})
t.Run("zero maxChars returns unchanged", func(t *testing.T) {
input := strings.Repeat("a", 100)
result := TruncateToolOutput(input, 0)
assert.Equal(t, input, result)
})
t.Run("negative maxChars returns unchanged", func(t *testing.T) {
input := strings.Repeat("a", 100)
result := TruncateToolOutput(input, -1)
assert.Equal(t, input, result)
})
t.Run("large output truncated with marker", func(t *testing.T) {
input := strings.Repeat("H", 10000) + strings.Repeat("T", 10000)
result := TruncateToolOutput(input, 5000)
runeCount := utf8.RuneCountInString(result)
assert.LessOrEqual(t, runeCount, 5000+truncationMarkerReserve,
"truncated output rune count should be within limits")
assert.True(t, strings.HasPrefix(result, "HHHH"),
"should preserve head content")
assert.True(t, strings.HasSuffix(result, "TTTT"),
"should preserve tail content")
assert.Contains(t, result, "output truncated")
assert.Contains(t, result, "20000 → 5000 chars")
})
t.Run("50k output truncated to 16k default", func(t *testing.T) {
input := strings.Repeat("x", 50000)
result := TruncateToolOutput(input, DefaultMaxToolOutput)
runeCount := utf8.RuneCountInString(result)
assert.Less(t, runeCount, DefaultMaxToolOutput+truncationMarkerReserve)
assert.Contains(t, result, "output truncated")
})
t.Run("head and tail are from correct positions", func(t *testing.T) {
head := strings.Repeat("A", 5000)
mid := strings.Repeat("B", 5000)
tail := strings.Repeat("C", 5000)
input := head + mid + tail
result := TruncateToolOutput(input, 5000)
assert.True(t, strings.HasPrefix(result, "AAAA"))
assert.True(t, strings.HasSuffix(result, "CCCC"))
})
t.Run("Chinese text truncated by rune count not bytes", func(t *testing.T) {
// Each Chinese character is 3 bytes in UTF-8 but 1 rune.
// 10000 Chinese chars = 30000 bytes. With maxChars=5000 runes,
// the result should have ~5000 runes, not be cut at 5000 bytes.
head := strings.Repeat("你", 5000)
tail := strings.Repeat("好", 5000)
input := head + tail
result := TruncateToolOutput(input, 5000)
resultRunes := utf8.RuneCountInString(result)
assert.LessOrEqual(t, resultRunes, 5000+truncationMarkerReserve,
"should truncate by rune count, not byte count")
assert.True(t, strings.HasPrefix(result, "你你你"),
"should preserve Chinese head content")
assert.True(t, strings.HasSuffix(result, "好好好"),
"should preserve Chinese tail content")
assert.Contains(t, result, "10000 → 5000 chars")
})
t.Run("mixed CJK and ASCII", func(t *testing.T) {
// Mix of 1-byte and 3-byte chars
input := strings.Repeat("a", 3000) + strings.Repeat("中", 3000) +
strings.Repeat("b", 3000) + strings.Repeat("文", 3000)
result := TruncateToolOutput(input, 5000)
resultRunes := utf8.RuneCountInString(result)
assert.LessOrEqual(t, resultRunes, 5000+truncationMarkerReserve)
assert.True(t, strings.HasPrefix(result, "aaa"))
assert.True(t, strings.HasSuffix(result, "文文文"))
})
t.Run("CJK within limit unchanged", func(t *testing.T) {
input := strings.Repeat("测", 100)
result := TruncateToolOutput(input, 200)
assert.Equal(t, input, result)
})
}