fix(agent/tools): sort function definitions for deterministic ordering

`ToolRegistry.GetFunctionDefinitions` and `ListTools` previously ranged
over the internal map directly. Go map iteration is intentionally
randomized, so the resulting `tools` array reshuffled on every request.

That reshuffling silently breaks provider-side prompt caches that key on
a byte-level prefix match — most visibly Qwen explicit caching, which
requires the messages (system + tools + history) to be byte-identical up
to the `cache_control` marker. With random ordering the serialized tools
block changes every call, so the cache prefix never matches and the
hit rate stays at 0%.

Sort by tool name in both functions. Output is now byte-stable across
calls and `cache_control: ephemeral` can actually take effect.

Tests in registry_test.go cover:
- Deterministic ordering across 50 iterations
- JSON byte-stability across 20 iterations (the real motivation)
- Field projection (Name / Description / Parameters)
- Empty registry returns `[]` not `null`
- ListTools sorting
- First-wins duplicate registration policy (GHSA-67q9-58vj-32qx)
This commit is contained in:
young1lin
2026-05-25 11:37:12 +08:00
committed by lyingbug
parent 30332cca99
commit 29bec4204a
2 changed files with 176 additions and 4 deletions
+20 -4
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"sort"
"github.com/Tencent/WeKnora/internal/common"
"github.com/Tencent/WeKnora/internal/logger"
@@ -62,19 +63,34 @@ func (r *ToolRegistry) GetTool(name string) (types.Tool, error) {
return tool, nil
}
// ListTools returns all registered tool names
// ListTools returns all registered tool names sorted alphabetically.
// Sorting keeps the order stable across calls — Go map iteration is
// intentionally randomized.
func (r *ToolRegistry) ListTools() []string {
names := make([]string, 0, len(r.tools))
for name := range r.tools {
names = append(names, name)
}
sort.Strings(names)
return names
}
// GetFunctionDefinitions returns function definitions for all registered tools
// GetFunctionDefinitions returns function definitions for all registered tools.
// The slice is sorted by tool name so the serialized payload sent to the LLM
// is byte-identical across requests. Providers that key prompt caching on a
// byte-level prefix match (e.g. Qwen explicit caching) require this — map
// iteration order would otherwise reshuffle the tools block and break cache
// hits.
func (r *ToolRegistry) GetFunctionDefinitions() []types.FunctionDefinition {
definitions := make([]types.FunctionDefinition, 0)
for _, tool := range r.tools {
names := make([]string, 0, len(r.tools))
for name := range r.tools {
names = append(names, name)
}
sort.Strings(names)
definitions := make([]types.FunctionDefinition, 0, len(names))
for _, name := range names {
tool := r.tools[name]
definitions = append(definitions, types.FunctionDefinition{
Name: tool.Name(),
Description: tool.Description(),