|
| 1 | +package agent |
| 2 | + |
| 3 | +import "testing" |
| 4 | + |
| 5 | +func roles(msgs []ChatMessage) []string { |
| 6 | + r := make([]string, len(msgs)) |
| 7 | + for i, m := range msgs { |
| 8 | + r[i] = m.Role |
| 9 | + } |
| 10 | + return r |
| 11 | +} |
| 12 | + |
| 13 | +func TestSanitizeDropsOrphanTool(t *testing.T) { |
| 14 | + // tool 消息前面没有对应 tool_call → 孤儿,应被丢弃 |
| 15 | + in := []ChatMessage{ |
| 16 | + {Role: "user", Content: "hi"}, |
| 17 | + {Role: "tool", ToolCallID: "x", Content: "orphan result"}, |
| 18 | + {Role: "assistant", Content: "answer"}, |
| 19 | + } |
| 20 | + out := sanitizeToolPairs(in) |
| 21 | + got := roles(out) |
| 22 | + if len(got) != 2 || got[0] != "user" || got[1] != "assistant" { |
| 23 | + t.Fatalf("孤儿 tool 应被剔除,got %v", got) |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +func TestSanitizeKeepsValidPair(t *testing.T) { |
| 28 | + in := []ChatMessage{ |
| 29 | + {Role: "user", Content: "hi"}, |
| 30 | + {Role: "assistant", ToolCalls: []ToolCall{{ID: "x", Function: ToolCallFunc{Name: "Read"}}}}, |
| 31 | + {Role: "tool", ToolCallID: "x", Content: "ok"}, |
| 32 | + {Role: "assistant", Content: "done"}, |
| 33 | + } |
| 34 | + out := sanitizeToolPairs(in) |
| 35 | + if len(out) != 4 { |
| 36 | + t.Fatalf("完整配对应原样保留,got %d 条: %v", len(out), roles(out)) |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +func TestSanitizeStripsDanglingToolCalls(t *testing.T) { |
| 41 | + // assistant 带 tool_calls 但没有对应 tool 响应: |
| 42 | + // - 有正文 → 剥掉 tool_calls,保留正文 |
| 43 | + // - 无正文 → 整条丢弃 |
| 44 | + in := []ChatMessage{ |
| 45 | + {Role: "user", Content: "hi"}, |
| 46 | + {Role: "assistant", Content: "让我查一下", ToolCalls: []ToolCall{{ID: "x", Function: ToolCallFunc{Name: "Read"}}}}, |
| 47 | + {Role: "assistant", ToolCalls: []ToolCall{{ID: "y", Function: ToolCallFunc{Name: "Grep"}}}}, // 无正文、无响应 → 丢 |
| 48 | + {Role: "assistant", Content: "结果如下"}, |
| 49 | + } |
| 50 | + out := sanitizeToolPairs(in) |
| 51 | + got := roles(out) |
| 52 | + if len(got) != 3 { |
| 53 | + t.Fatalf("悬挂 tool_calls 处理错误,got %d 条: %v", len(got), got) |
| 54 | + } |
| 55 | + if len(out[1].ToolCalls) != 0 || out[1].Content != "让我查一下" { |
| 56 | + t.Errorf("应剥掉无响应 tool_calls、保留正文,got %+v", out[1]) |
| 57 | + } |
| 58 | +} |
0 commit comments