diff --git a/internal/agent/tools/sanitize_messages.go b/internal/agent/tools/sanitize_messages.go index 8b916d3c..57f4686e 100644 --- a/internal/agent/tools/sanitize_messages.go +++ b/internal/agent/tools/sanitize_messages.go @@ -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 } } diff --git a/internal/agent/tools/sanitize_messages_test.go b/internal/agent/tools/sanitize_messages_test.go index feb2898f..4b80973b 100644 --- a/internal/agent/tools/sanitize_messages_test.go +++ b/internal/agent/tools/sanitize_messages_test.go @@ -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() +}