fix(agent): 合并相邻 assistant 消息时保留 tool_calls,避免孤儿 tool 消息导致整轮 400 (#3574)

* fix(agent): 合并相邻 assistant 消息时保留 tool_calls

SanitizeMessages 合并相邻同 role 消息时只拼接 Content、丢掉了后一条的
ToolCalls;而紧随其后的 tool 消息是否保留,判断的是原始切片,于是保留下来的
tool 消息在请求体里找不到宿主 → OpenAI 兼容端点 400。400 不是 transient,管线
会降级到不带 tools 的总结调用,那一轮模型只能把工具调用写成正文(现象是
"模型输出了调用但页面没变")。

合并时把 ToolCalls 一并合并,并复制而非原地 append,避免与调用方的切片共享
底层数组。

Fixes #3569

* style(agent): 折行以符合 lll 的 120 字符上限

---------

Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
main
linus-liu-web 2026-09-25 18:47:55 +08:00 committed by GitHub
parent 5614c04d88
commit 6eb3cce164
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 85 additions and 2 deletions

View File

@ -30,8 +30,26 @@ func SanitizeMessages(messages []chat.Message) []chat.Message {
if len(result) > 0 && msg.Role != "tool" {
prev := result[len(result)-1]
if prev.Role == msg.Role && prev.Role != "tool" {
// Merge with previous message
result[len(result)-1].Content += "\n\n" + msg.Content
// Merge with previous message.
//
// The merge has to take the tool calls along: the tool results
// that follow still reference them, and a tool message whose
// tool_call_id has no matching assistant call is rejected by
// OpenAI-compatible endpoints. Dropping them here is what used
// to turn one merged pair into a 400, and the agent then fell
// back to a tool-less summary call where the model can only
// write the call it wanted to make as text.
merged := prev
merged.Content += "\n\n" + msg.Content
if len(msg.ToolCalls) > 0 {
// Copy instead of appending in place: prev may share its
// backing array with the caller's slice.
calls := make([]chat.ToolCall, 0, len(prev.ToolCalls)+len(msg.ToolCalls))
calls = append(calls, prev.ToolCalls...)
calls = append(calls, msg.ToolCalls...)
merged.ToolCalls = calls
}
result[len(result)-1] = merged
continue
}
}

View File

@ -1,6 +1,8 @@
package tools
import (
"fmt"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/models/chat"
@ -91,3 +93,66 @@ func TestSanitizeMessages(t *testing.T) {
assert.Empty(t, result)
})
}
// A step that follows an intermediate-answer step replays as a second
// consecutive assistant message (see buildAgentStepMessages in
// application/service/agent_history.go, IntermediateAnswer branch). Merging
// such a message must not throw its tool calls away: dropping them leaves the
// following `tool` message referencing a call the provider cannot see, and the
// model never learns the call it asked for is missing from the transcript.
func TestSanitizeMessages_KeepsToolCallsWhenAssistantMessagesMerge(t *testing.T) {
messages := []chat.Message{
{Role: "system", Content: "system"},
{Role: "user", Content: "please fix the page"},
{Role: "assistant", Content: "Let me look at the page first."},
{
Role: "assistant",
Content: "Now replacing the text.",
ToolCalls: []chat.ToolCall{{
ID: "call_1", Type: "function",
Function: chat.FunctionCall{
Name: "wiki_replace_text",
Arguments: `{"slug":"g","old_text":"a","new_text":"b"}`,
},
}},
},
{
Role: "tool", Content: "Successfully replaced 1 occurrence(s)",
ToolCallID: "call_1", Name: "wiki_replace_text",
},
}
result := SanitizeMessages(messages)
t.Logf("sanitized: %s", describeMessages(result))
require.Len(t, result, 4)
require.Len(t, result[2].ToolCalls, 1, "the merged assistant message must keep the tool call")
assert.Equal(t, "call_1", result[2].ToolCalls[0].ID)
assert.Equal(t, "wiki_replace_text", result[2].ToolCalls[0].Function.Name)
// The contract the function documents: no tool result may be left pointing
// at a call that is no longer present in the messages that get sent.
for i, msg := range result {
if msg.Role != "tool" || msg.ToolCallID == "" {
continue
}
found := false
for _, prev := range result[:i] {
for _, tc := range prev.ToolCalls {
if tc.ID == msg.ToolCallID {
found = true
}
}
}
assert.True(t, found, "tool message %d references %q, which no assistant message carries", i, msg.ToolCallID)
}
}
func describeMessages(messages []chat.Message) string {
var b strings.Builder
for i, m := range messages {
fmt.Fprintf(&b, "\n [%d] role=%s content=%q toolCallID=%q toolCalls=%d",
i, m.Role, m.Content, m.ToolCallID, len(m.ToolCalls))
}
return b.String()
}