返回 DeepSeek-Reasonix
empty_final_test.go
根目录 / internal / agent / empty_final_test.go
1 package agent
2
3 import (
4 "context"
5 "errors"
6 "strings"
7 "testing"
8
9 "reasonix/internal/event"
10 "reasonix/internal/provider"
11 "reasonix/internal/tool"
12 )
13
14 func TestRunRecoversReasoningOnlyFinalAnswer(t *testing.T) {
15 prov := &scriptedProvider{name: "p", turns: [][]provider.Chunk{
16 {
17 {Type: provider.ChunkReasoning, Text: "I should answer the user."},
18 {Type: provider.ChunkDone},
19 },
20 {{Type: provider.ChunkText, Text: "answer"}, {Type: provider.ChunkDone}},
21 }}
22 a := New(prov, tool.NewRegistry(), NewSession(""), Options{}, event.Discard)
23
24 if err := a.Run(context.Background(), "answer me"); err != nil {
25 t.Fatalf("Run: %v", err)
26 }
27 if prov.call != 2 {
28 t.Fatalf("provider calls = %d, want one recovery", prov.call)
29 }
30 if got := lastAssistantContent(a.sess.conversation); got != "answer" {
31 t.Fatalf("last assistant content = %q", got)
32 }
33 if !sessionHasUserMessageContaining(a.sess.conversation, "visible answer") {
34 t.Fatal("missing recovery")
35 }
36 }
37
38 func TestRunPrefixesReasoningLanguageOnReasoningOnlyCompletion(t *testing.T) {
39 prov := &mockProvider{name: "p", streams: [][]provider.Chunk{
40 {
41 {Type: provider.ChunkReasoning, Text: "I should answer the user."},
42 {Type: provider.ChunkDone},
43 },
44 {{Type: provider.ChunkText, Text: "answer"}, {Type: provider.ChunkDone}},
45 }}
46 a := New(prov, tool.NewRegistry(), NewSession(""), Options{ReasoningLanguage: "zh"}, event.Discard)
47
48 if err := a.Run(context.Background(), "answer me"); err != nil {
49 t.Fatalf("Run: %v", err)
50 }
51 if len(prov.requests) != 2 {
52 t.Fatalf("provider requests = %d, want 2", len(prov.requests))
53 }
54 got := lastUser(prov.requests[0])
55 if !strings.HasPrefix(got, "<reasoning-language>") || !strings.Contains(got, "简体中文") {
56 t.Fatalf("last user = %q, want reasoning-language prefix", got)
57 }
58 if strings.Contains(got, "visible answer") {
59 t.Fatalf("reasoning-only completion must not receive a synthetic visible-answer retry: %q", got)
60 }
61 }
62
63 func TestRunBoundsExplicitVisibleFinalRecovery(t *testing.T) {
64 prov := &scriptedProvider{name: "p", turns: [][]provider.Chunk{
65 {{Type: provider.ChunkReasoning, Text: "thinking 1"}, {Type: provider.ChunkDone}},
66 {{Type: provider.ChunkReasoning, Text: "thinking 2"}, {Type: provider.ChunkDone}},
67 {{Type: provider.ChunkReasoning, Text: "thinking 3"}, {Type: provider.ChunkDone}},
68 }}
69 a := New(prov, tool.NewRegistry(), NewSession(""), Options{RequireVisibleFinal: true}, event.Discard)
70
71 err := a.Run(context.Background(), "answer me")
72 if err == nil {
73 t.Fatal("expected repeated empty final answers to stop the run")
74 }
75 if !strings.Contains(err.Error(), "visible final answer") {
76 t.Fatalf("error = %v, want visible final answer", err)
77 }
78 if !errors.Is(err, provider.ErrNoDeliverableOutput) || prov.call != 2 {
79 t.Fatalf("error=%v, provider calls=%d, want bounded delivery failure", err, prov.call)
80 }
81 }
82
83 func TestEmptyResponseLeavesRetryToUser(t *testing.T) {
84 prov := &scriptedProvider{name: "p", turns: [][]provider.Chunk{
85 {{Type: provider.ChunkDone}},
86 {{Type: provider.ChunkText, Text: "visible reply"}, {Type: provider.ChunkDone}},
87 }}
88 a := New(prov, tool.NewRegistry(), NewSession(""), Options{}, event.Discard)
89 if err := a.Run(t.Context(), "answer me"); !errors.Is(err, provider.ErrEmptyResponse) {
90 t.Fatalf("err=%v", err)
91 }
92 if prov.call != 1 || lastAssistantContent(a.Session()) != "" {
93 t.Fatalf("calls=%d", prov.call)
94 }
95 if err := a.Run(t.Context(), "try again"); err != nil {
96 t.Fatal(err)
97 }
98 if prov.call != 2 || lastAssistantContent(a.Session()) != "visible reply" {
99 t.Fatalf("manual retry calls=%d", prov.call)
100 }
101 if sessionHasUserMessageContaining(a.Session(), "visible answer") {
102 t.Fatal("injected synthetic retry prompt")
103 }
104 }
105
106 func TestRunStopsOnZeroContentWithoutCommittingEmptyMessages(t *testing.T) {
107 turns := make([][]provider.Chunk, maxSamplingAttempts)
108 for i := range turns {
109 turns[i] = []provider.Chunk{{Type: provider.ChunkDone}}
110 }
111 prov := &scriptedProvider{name: "p", turns: turns}
112 sink := &recordSink{}
113 a := New(prov, tool.NewRegistry(), NewSession(""), Options{}, sink)
114
115 err := a.Run(context.Background(), "answer me")
116 if !errors.Is(err, provider.ErrEmptyResponse) {
117 t.Fatalf("Run error = %v, want ErrEmptyResponse", err)
118 }
119 if prov.call != 1 {
120 t.Fatalf("provider calls = %d, want 1", prov.call)
121 }
122 for _, message := range a.sess.conversation.Messages {
123 if message.Role == provider.RoleAssistant {
124 t.Fatalf("empty attempt committed assistant message: %+v", message)
125 }
126 if message.Role == provider.RoleUser && strings.Contains(message.Content, "visible answer") {
127 t.Fatalf("empty attempt injected synthetic user prompt: %q", message.Content)
128 }
129 }
130 retries := sink.kinds(event.Retrying)
131 if len(retries) != 0 {
132 t.Fatalf("unexpected retry events: %+v", retries)
133 }
134 }
135
136 func lastAssistantContent(s *Session) string {
137 var out string
138 for _, m := range s.Messages {
139 if m.Role == provider.RoleAssistant {
140 out = m.Content
141 }
142 }
143 return out
144 }
145
146 // deepseekThinkingProvider exercises the preserved reasoning replay contract.
147 type deepseekThinkingProvider struct{ *scriptedProvider }
148
149 func (deepseekThinkingProvider) RequiresToolCallReasoning() bool { return true }
150
151 func TestRunRecoversReasoningOnlyFinalWhenModelStopped(t *testing.T) {
152 // A clean transport stop must not be mistaken for an answer.
153 prov := &scriptedProvider{name: "p", turns: [][]provider.Chunk{
154 {
155 {Type: provider.ChunkReasoning, Text: "The user asked a simple question; I have reasoned through it and the answer is ready."},
156 {Type: provider.ChunkUsage, Usage: &provider.Usage{FinishReason: "stop", TotalTokens: 10}},
157 {Type: provider.ChunkDone},
158 },
159 {{Type: provider.ChunkText, Text: "answer"}, {Type: provider.ChunkDone}},
160 }}
161 a := New(deepseekThinkingProvider{prov}, tool.NewRegistry(), NewSession(""), Options{}, event.Discard)
162
163 if err := a.Run(context.Background(), "answer me"); err != nil {
164 t.Fatalf("Run: %v", err)
165 }
166 if prov.call != 2 {
167 t.Fatalf("provider calls = %d, want 2", prov.call)
168 }
169 if !sessionHasUserMessageContaining(a.sess.conversation, "visible answer") {
170 t.Fatal("missing recovery")
171 }
172 if got := lastAssistantContent(a.sess.conversation); got != "answer" {
173 t.Fatalf("last assistant content = %q", got)
174 }
175 }
176
177 func TestRunRecoversReasoningOnlyStopWithoutDeepSeekPolicy(t *testing.T) {
178 // Ordinary providers share the same delivery contract.
179 prov := &scriptedProvider{name: "p", turns: [][]provider.Chunk{
180 {
181 {Type: provider.ChunkReasoning, Text: "thinking only, nothing visible"},
182 {Type: provider.ChunkUsage, Usage: &provider.Usage{FinishReason: "stop", TotalTokens: 10}},
183 {Type: provider.ChunkDone},
184 },
185 {{Type: provider.ChunkText, Text: "answer"}, {Type: provider.ChunkDone}},
186 }}
187 a := New(prov, tool.NewRegistry(), NewSession(""), Options{}, event.Discard)
188
189 if err := a.Run(context.Background(), "answer me"); err != nil {
190 t.Fatalf("Run: %v", err)
191 }
192 if prov.call != 2 {
193 t.Fatalf("provider calls = %d, want 2", prov.call)
194 }
195 if !sessionHasUserMessageContaining(a.sess.conversation, "visible answer") {
196 t.Fatal("missing recovery")
197 }
198 if got := lastAssistantContent(a.sess.conversation); got != "answer" {
199 t.Fatalf("last assistant content = %q", got)
200 }
201 }
202
203 func BenchmarkHasVisibleFinalAnswer(b *testing.B) {
204 cases := []struct {
205 name string
206 text string
207 }{
208 {"normal", "visible reply"},
209 {"leading-space", strings.Repeat(" ", 256) + "visible reply"},
210 {"all-space", strings.Repeat(" \n\t", 256)},
211 }
212 for _, tc := range cases {
213 b.Run(tc.name, func(b *testing.B) {
214 b.ReportAllocs()
215 var got bool
216 for range b.N {
217 got = hasVisibleFinalAnswer(tc.text)
218 }
219 _ = got
220 })
221 }
222 }
223
224 func reasoningOnlyStop(text string) []provider.Chunk {
225 return []provider.Chunk{
226 {Type: provider.ChunkReasoning, Text: text},
227 {Type: provider.ChunkUsage, Usage: &provider.Usage{FinishReason: "stop", TotalTokens: 10}},
228 {Type: provider.ChunkDone},
229 }
230 }
231
232 func countUserMessagesContaining(s *Session, needle string) int {
233 n := 0
234 for _, message := range s.Messages {
235 if message.Role == provider.RoleUser && strings.Contains(message.Content, needle) {
236 n++
237 }
238 }
239 return n
240 }
241
242 func TestRunRetriesReasoningOnlyStopAfterToolRoundOnce(t *testing.T) {
243 prov := &scriptedProvider{name: "p", turns: [][]provider.Chunk{
244 {{Type: provider.ChunkReasoning, Text: "read the file"}, toolCallChunk("call-1", "read_file", `{}`), {Type: provider.ChunkUsage, Usage: &provider.Usage{FinishReason: "tool_calls", TotalTokens: 10}}, {Type: provider.ChunkDone}},
245 reasoningOnlyStop("I have the file contents; the answer is ready."),
246 {{Type: provider.ChunkText, Text: "The file says contents."}, {Type: provider.ChunkDone}},
247 }}
248 reg := tool.NewRegistry()
249 reg.Add(fakeReadFileTool{})
250 a := New(deepseekThinkingProvider{prov}, reg, NewSession(""), Options{}, event.Discard)
251
252 if err := a.Run(context.Background(), "what does the file say"); err != nil {
253 t.Fatalf("Run: %v", err)
254 }
255 if prov.call != 3 {
256 t.Fatalf("provider calls = %d, want tool round + reasoning-only stop + one retry", prov.call)
257 }
258 if got := countUserMessagesContaining(a.sess.conversation, "visible answer"); got != 1 {
259 t.Fatalf("visible-answer retries = %d, want exactly 1", got)
260 }
261 if got := lastAssistantContent(a.sess.conversation); got != "The file says contents." {
262 t.Fatalf("last assistant content = %q, want the visible synthesis", got)
263 }
264 }
265
266 func TestRunRejectsSecondReasoningOnlyStopAfterToolRound(t *testing.T) {
267 prov := &scriptedProvider{name: "p", turns: [][]provider.Chunk{
268 {{Type: provider.ChunkReasoning, Text: "read the file"}, toolCallChunk("call-1", "read_file", `{}`), {Type: provider.ChunkUsage, Usage: &provider.Usage{FinishReason: "tool_calls", TotalTokens: 10}}, {Type: provider.ChunkDone}},
269 reasoningOnlyStop("done thinking"),
270 reasoningOnlyStop("still only thinking"),
271 }}
272 reg := tool.NewRegistry()
273 reg.Add(fakeReadFileTool{})
274 a := New(deepseekThinkingProvider{prov}, reg, NewSession(""), Options{}, event.Discard)
275
276 if err := a.Run(context.Background(), "what does the file say"); !errors.Is(err, provider.ErrNoDeliverableOutput) {
277 t.Fatalf("Run: %v, want delivery failure", err)
278 }
279 if prov.call != 3 {
280 t.Fatalf("provider calls = %d, want a single bounded retry", prov.call)
281 }
282 if got := countUserMessagesContaining(a.sess.conversation, "visible answer"); got != 1 {
283 t.Fatalf("visible-answer retries = %d, want exactly 1", got)
284 }
285 }
286
286 lines GO