仰望星辰工作室

gitcat

gitcat/ internal/ai/stream_test.go 6.8 KB · 200 行 原始文件
1package ai
2
3import (
4 "context"
5 "fmt"
6 "net/http"
7 "net/http/httptest"
8 "strings"
9 "testing"
10)
11
12// sseServer 起一个按给定 data 行依次输出的 SSE 端点。
13func sseServer(t *testing.T, lines ...string) *httptest.Server {
14 t.Helper()
15 return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
16 w.Header().Set("Content-Type", "text/event-stream")
17 for _, l := range lines {
18 fmt.Fprintln(w, l)
19 if f, ok := w.(http.Flusher); ok {
20 f.Flush()
21 }
22 }
23 }))
24}
25
26func cfgOf(srv *httptest.Server) Config {
27 return Config{Enabled: true, BaseURL: srv.URL, Model: "m"}
28}
29
30type collected struct {
31 kinds []string
32 texts []string
33}
34
35func (c *collected) cb(kind, text string) {
36 c.kinds = append(c.kinds, kind)
37 c.texts = append(c.texts, text)
38}
39
40func (c *collected) all(kind string) string {
41 var b strings.Builder
42 for i, k := range c.kinds {
43 if k == kind {
44 b.WriteString(c.texts[i])
45 }
46 }
47 return b.String()
48}
49
50func TestChatStreamContentAndReasoning(t *testing.T) {
51 srv := sseServer(t,
52 `data: {"choices":[{"delta":{"reasoning_content":"先想一想"}}]}`,
53 `data: {"choices":[{"delta":{"content":"你"}}]}`,
54 `data: {"choices":[{"delta":{"content":"好"}}]}`,
55 `data: [DONE]`,
56 )
57 c := &collected{}
58 res, err := ChatStream(context.Background(), cfgOf(srv), []Message{{Role: "user", Content: "u"}}, nil, c.cb)
59 if err != nil {
60 t.Fatalf("ChatStream 失败: %v", err)
61 }
62 if res.Content != "你好" {
63 t.Errorf("聚合内容 = %q,期望 你好", res.Content)
64 }
65 if res.Reasoning != "先想一想" {
66 t.Errorf("聚合思维链 = %q", res.Reasoning)
67 }
68 if got := c.all(DeltaContent); got != "你好" {
69 t.Errorf("content 回调拼接 = %q", got)
70 }
71 if got := c.all(DeltaReasoning); got != "先想一想" {
72 t.Errorf("reasoning 回调拼接 = %q", got)
73 }
74}
75
76// TestChatStreamAssemblesToolCallFragments 工具调用会被拆成多个增量片段
77//(arguments 分片、id 只在首块出现),流结束后必须聚合完整。
78func TestChatStreamAssemblesToolCallFragments(t *testing.T) {
79 srv := sseServer(t,
80 `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","function":{"name":"read_file","arguments":"{\"pa"}}]}}]}`,
81 `data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"th\":\"a.go\"}"}}]}}]}`,
82 `data: {"choices":[{"delta":{"tool_calls":[{"index":1,"id":"call_2","function":{"name":"list_files","arguments":"{}"}}]}}]}`,
83 `data: [DONE]`,
84 )
85 c := &collected{}
86 res, err := ChatStream(context.Background(), cfgOf(srv), []Message{{Role: "user", Content: "u"}}, nil, c.cb)
87 if err != nil {
88 t.Fatalf("ChatStream 失败: %v", err)
89 }
90 if len(res.ToolCalls) != 2 {
91 t.Fatalf("应聚合出 2 个工具调用,实际 %d", len(res.ToolCalls))
92 }
93 if res.ToolCalls[0].ID != "call_1" || res.ToolCalls[0].Name != "read_file" || res.ToolCalls[0].Args != `{"path":"a.go"}` {
94 t.Errorf("第一个工具调用聚合错误: %+v", res.ToolCalls[0])
95 }
96 if res.ToolCalls[1].ID != "call_2" || res.ToolCalls[1].Name != "list_files" || res.ToolCalls[1].Args != "{}" {
97 t.Errorf("第二个工具调用聚合错误: %+v", res.ToolCalls[1])
98 }
99 if c.all(DeltaContent) != "" {
100 t.Error("工具轮不应产生内容回调")
101 }
102}
103
104// TestChatStreamFallsBackToJSON 端点不支持流式(回普通 JSON)时自动降级,
105// 不产生增量回调,返回完整结果。
106func TestChatStreamFallsBackToJSON(t *testing.T) {
107 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
108 w.Header().Set("Content-Type", "application/json")
109 _, _ = w.Write([]byte(`{"choices":[{"message":{"content":"整段回答","reasoning_content":"推理"}}]}`))
110 }))
111 c := &collected{}
112 res, err := ChatStream(context.Background(), cfgOf(srv), []Message{{Role: "user", Content: "u"}}, nil, c.cb)
113 if err != nil {
114 t.Fatalf("ChatStream 失败: %v", err)
115 }
116 if res.Content != "整段回答" || res.Reasoning != "推理" {
117 t.Errorf("降级结果错误: %+v", res)
118 }
119 if len(c.kinds) != 0 {
120 t.Errorf("JSON 降级不应产生增量回调,实际 %v", c.kinds)
121 }
122}
123
124func TestChatStreamReportsError(t *testing.T) {
125 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
126 w.Header().Set("Content-Type", "text/event-stream")
127 fmt.Fprintln(w, `data: {"error":{"message":"invalid api key"}}`)
128 }))
129 if _, err := ChatStream(context.Background(), cfgOf(srv), []Message{{Role: "user", Content: "u"}}, nil, nil); err == nil || !strings.Contains(err.Error(), "invalid api key") {
130 t.Fatalf("应带出接口错误,实际 %v", err)
131 }
132}
133
134func TestChatStreamRequiresReadyConfig(t *testing.T) {
135 if _, err := ChatStream(context.Background(), Config{Enabled: true}, []Message{{Role: "user", Content: "u"}}, nil, nil); err == nil {
136 t.Error("配置不完整应直接报错")
137 }
138}
139
140// ---------------------------------------------------------------- ThinkFilter
141
142// collectThink 让过滤器输出到可断言的容器。
143func collectThink() (f *ThinkFilter, c *collected, r *collected) {
144 c, r = &collected{}, &collected{}
145 return NewThinkFilter(
146 func(s string) { c.cb(DeltaContent, s) },
147 func(s string) { r.cb(DeltaReasoning, s) },
148 ), c, r
149}
150
151func assertThink(t *testing.T, f *ThinkFilter, c, r *collected, wantContent, wantReasoning string) {
152 t.Helper()
153 f.Close()
154 if got := c.all(DeltaContent); got != wantContent {
155 t.Errorf("content = %q,期望 %q", got, wantContent)
156 }
157 if got := r.all(DeltaReasoning); got != wantReasoning {
158 t.Errorf("reasoning = %q,期望 %q", got, wantReasoning)
159 }
160}
161
162func TestThinkFilterWholeTagInOneChunk(t *testing.T) {
163 f, c, r := collectThink()
164 f.Write("<think>推理</think>回答")
165 assertThink(t, f, c, r, "回答", "推理")
166}
167
168// 标签被拆在相邻增量里是常态,过滤器必须正确衔接。
169func TestThinkFilterSplitTags(t *testing.T) {
170 f, c, r := collectThink()
171 for _, chunk := range []string{"<thi", "nk>推理过", "程</th", "ink>最", "终回答"} {
172 f.Write(chunk)
173 }
174 assertThink(t, f, c, r, "最终回答", "推理过程")
175}
176
177func TestThinkFilterUnclosedTag(t *testing.T) {
178 f, c, r := collectThink()
179 f.Write("前置<think>忘了闭合的思考直到结尾")
180 assertThink(t, f, c, r, "前置", "忘了闭合的思考直到结尾")
181}
182
183func TestThinkFilterTagWithAttributes(t *testing.T) {
184 f, c, r := collectThink()
185 f.Write(`<think mode="deep">推理</think > 答案`)
186 assertThink(t, f, c, r, " 答案", "推理")
187}
188
189func TestThinkFilterPassesThroughWithoutTags(t *testing.T) {
190 f, c, r := collectThink()
191 f.Write("普通 <b> 内容,含 < 与 > 符号。")
192 assertThink(t, f, c, r, "普通 <b> 内容,含 < 与 > 符号。", "")
193}
194
195// SplitThinking 的回归约束同样适用于流式过滤器:两个 think 块按序拼接。
196func TestThinkFilterTwoBlocks(t *testing.T) {
197 f, c, r := collectThink()
198 f.Write("<think>一</think>中<think>二</think>尾")
199 assertThink(t, f, c, r, "中尾", "一\n\n二")
200}