仰望星辰工作室

gitcat

gitcat/ internal/ai/assistant_test.go 7.5 KB · 219 行 原始文件
1package ai
2
3import (
4 "context"
5 "encoding/json"
6 "net/http"
7 "net/http/httptest"
8 "strings"
9 "sync"
10 "testing"
11)
12
13// capture 线程安全地保存假端点收到的请求体。
14type capture struct {
15 mu sync.Mutex
16 req map[string]any
17}
18
19func (c *capture) set(m map[string]any) {
20 c.mu.Lock()
21 c.req = m
22 c.mu.Unlock()
23}
24
25func (c *capture) get() map[string]any {
26 c.mu.Lock()
27 defer c.mu.Unlock()
28 return c.req
29}
30
31// newCaptureServer 起一个假端点:记录请求体,并按给定状态码与正文响应。
32func newCaptureServer(t *testing.T, status int, body string) (*httptest.Server, *capture) {
33 t.Helper()
34 c := &capture{}
35 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
36 var m map[string]any
37 _ = json.NewDecoder(r.Body).Decode(&m)
38 c.set(m)
39 w.Header().Set("Content-Type", "application/json")
40 if status != http.StatusOK {
41 w.WriteHeader(status)
42 }
43 _, _ = w.Write([]byte(body))
44 }))
45 t.Cleanup(srv.Close)
46 return srv, c
47}
48
49func testConfig(srv *httptest.Server) Config {
50 return Config{Enabled: true, BaseURL: srv.URL, Model: "test-model"}
51}
52
53// TestChatSendsToolsAndParsesToolCalls 验证工具声明按 OpenAI 格式发出,
54// 模型返回的 tool_calls 被正确解析。
55func TestChatSendsToolsAndParsesToolCalls(t *testing.T) {
56 reply := `{"choices":[{"message":{"content":"","tool_calls":[` +
57 `{"id":"call_1","type":"function","function":{"name":"read_file","arguments":"{\"path\":\"a.go\"}"}}]}}]}`
58 srv, cap := newCaptureServer(t, http.StatusOK, reply)
59
60 res, err := Chat(context.Background(), testConfig(srv), []Message{
61 {Role: "system", Content: "你是助手"},
62 {Role: "user", Content: "这个文件里有什么?"},
63 }, []ToolSpec{{
64 Name: "read_file",
65 Description: "读取文件",
66 Parameters: map[string]any{
67 "type": "object",
68 "properties": map[string]any{"path": map[string]any{"type": "string"}},
69 "required": []string{"path"},
70 },
71 }})
72 if err != nil {
73 t.Fatalf("Chat 失败: %v", err)
74 }
75
76 req := cap.get()
77 if req["model"] != "test-model" {
78 t.Errorf("model 为 %v", req["model"])
79 }
80 tools, _ := req["tools"].([]any)
81 if len(tools) != 1 {
82 t.Fatalf("请求里应有 1 个工具,实际 %d", len(tools))
83 }
84 first, _ := tools[0].(map[string]any)
85 if first["type"] != "function" {
86 t.Errorf("工具 type 为 %v,期望 function", first["type"])
87 }
88 fn, _ := first["function"].(map[string]any)
89 if fn["name"] != "read_file" {
90 t.Errorf("工具名为 %v", fn["name"])
91 }
92 if _, ok := fn["parameters"].(map[string]any); !ok {
93 t.Error("工具缺少 parameters schema")
94 }
95
96 if len(res.ToolCalls) != 1 {
97 t.Fatalf("应解析出 1 个工具调用,实际 %d", len(res.ToolCalls))
98 }
99 if res.ToolCalls[0].ID != "call_1" || res.ToolCalls[0].Name != "read_file" {
100 t.Errorf("工具调用解析错误: %+v", res.ToolCalls[0])
101 }
102 if res.ToolCalls[0].Args != `{"path":"a.go"}` {
103 t.Errorf("参数原文为 %q", res.ToolCalls[0].Args)
104 }
105}
106
107// TestChatToolResultRoundTrip 验证把工具结果回填给模型时,
108// assistant 的 tool_calls 与 tool 消息的 tool_call_id 都在请求体里。
109func TestChatToolResultRoundTrip(t *testing.T) {
110 srv, cap := newCaptureServer(t, http.StatusOK, `{"choices":[{"message":{"content":"done"}}]}`)
111
112 res, err := Chat(context.Background(), testConfig(srv), []Message{
113 {Role: "user", Content: "u"},
114 {Role: "assistant", ToolCalls: []ToolCall{{ID: "c1", Name: "read_file", Args: "{}"}}},
115 {Role: "tool", ToolCallID: "c1", Content: "文件内容"},
116 }, nil)
117 if err != nil {
118 t.Fatalf("Chat 失败: %v", err)
119 }
120 if res.Content != "done" {
121 t.Errorf("内容为 %q", res.Content)
122 }
123 raw, _ := json.Marshal(cap.get()["messages"])
124 for _, want := range []string{`"tool_call_id":"c1"`, `"tool_calls"`, `"type":"function"`, "文件内容", `"role":"tool"`} {
125 if !strings.Contains(string(raw), want) {
126 t.Errorf("请求消息里缺少 %q:%s", want, raw)
127 }
128 }
129 if _, hasTools := cap.get()["tools"]; hasTools {
130 t.Error("未声明工具时不应带 tools 字段")
131 }
132}
133
134// TestChatReportsProviderError 接口报错时要带出可诊断的信息。
135func TestChatReportsProviderError(t *testing.T) {
136 srv, _ := newCaptureServer(t, http.StatusBadRequest, `{"error":{"message":"invalid api key"}}`)
137 _, err := Chat(context.Background(), testConfig(srv), []Message{{Role: "user", Content: "u"}}, nil)
138 if err == nil || !strings.Contains(err.Error(), "invalid api key") {
139 t.Fatalf("期望带出接口错误,实际 %v", err)
140 }
141}
142
143// TestChatRejectsEmptyReply 模型什么都没返回时视为失败。
144func TestChatRejectsEmptyReply(t *testing.T) {
145 srv, _ := newCaptureServer(t, http.StatusOK, `{"choices":[{"message":{"content":""}}]}`)
146 if _, err := Chat(context.Background(), testConfig(srv), []Message{{Role: "user", Content: "u"}}, nil); err == nil {
147 t.Error("空响应应返回错误")
148 }
149}
150
151// TestChatRejectsIncompleteConfig 配置不完整时不发请求。
152func TestChatRejectsIncompleteConfig(t *testing.T) {
153 if _, err := Chat(context.Background(), Config{Enabled: true}, []Message{{Role: "user", Content: "u"}}, nil); err == nil {
154 t.Error("配置不完整应直接报错")
155 }
156}
157
158// TestRedactExported 仓库内容外发前的脱敏入口可用。
159func TestRedactExported(t *testing.T) {
160 out := Redact("aws_key = AKIAIOSFODNN7EXAMPLE")
161 if strings.Contains(out, "AKIAIOSFODNN7EXAMPLE") {
162 t.Errorf("Redact 未生效: %q", out)
163 }
164}
165
166// TestSplitThinking 验证内联思维链的分离:成对标签、多次出现、未闭合、无思维链。
167func TestSplitThinking(t *testing.T) {
168 cases := []struct {
169 name, in, wantThink, wantAnswer string
170 }{
171 {"无思维链", "普通回答", "", "普通回答"},
172 {"成对标签", "<think>先想一下</think>正式回答", "先想一下", "正式回答"},
173 {"前后都有内容", "开头<think>\n推理过程\n</think>\n结尾回答", "推理过程", "开头\n结尾回答"},
174 {"多次出现", "<think>a</think>中<think>b</think>尾", "a\n\nb", "中尾"},
175 {"未闭合", "回答前半<think>忘了闭合的思考", "忘了闭合的思考", "回答前半"},
176 {"带属性", "<think mode=\"deep\">推理</think>答案", "推理", "答案"},
177 }
178 for _, c := range cases {
179 t.Run(c.name, func(t *testing.T) {
180 thinking, answer := SplitThinking(c.in)
181 if thinking != c.wantThink {
182 t.Errorf("思维链 = %q,期望 %q", thinking, c.wantThink)
183 }
184 if answer != c.wantAnswer {
185 t.Errorf("回答 = %q,期望 %q", answer, c.wantAnswer)
186 }
187 })
188 }
189 // StripThinking 是丢弃思维链的便捷入口
190 if got := StripThinking("<think>x</think>y"); got != "y" {
191 t.Errorf("StripThinking = %q", got)
192 }
193}
194
195// TestChatParsesReasoningFields 模型把思维链放在独立字段时也要接住。
196func TestChatParsesReasoningFields(t *testing.T) {
197 cases := []struct {
198 name, body, field string
199 }{
200 {"reasoning_content", `{"choices":[{"message":{"content":"答","reasoning_content":"推理A"}}]}`, "推理A"},
201 {"reasoning", `{"choices":[{"message":{"content":"答","reasoning":"推理B"}}]}`, "推理B"},
202 {"content 优先于独立字段", `{"choices":[{"message":{"content":"<think>内联</think>答"}}]}`, ""},
203 }
204 for _, c := range cases {
205 t.Run(c.name, func(t *testing.T) {
206 srv, _ := newCaptureServer(t, http.StatusOK, c.body)
207 res, err := Chat(context.Background(), testConfig(srv), []Message{{Role: "user", Content: "u"}}, nil)
208 if err != nil {
209 t.Fatalf("Chat 失败: %v", err)
210 }
211 if c.field != "" && res.Reasoning != c.field {
212 t.Errorf("Reasoning = %q,期望 %q", res.Reasoning, c.field)
213 }
214 if c.field == "" && res.Reasoning != "" {
215 t.Errorf("不应有独立字段思维链,实际 %q", res.Reasoning)
216 }
217 })
218 }
219}