| 1 | package bot |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "io" |
| 6 | "net/http" |
| 7 | "net/http/httptest" |
| 8 | "strings" |
| 9 | "sync" |
| 10 | "testing" |
| 11 | ) |
| 12 | |
| 13 | // TestExecTaskRetriesWithoutThinking pins the empty-result fallback: adaptive |
| 14 | // thinking can spend the whole 4096-token budget before any text is written |
| 15 | // (stop_reason max_tokens — seen live on a long feed digest), and the run |
| 16 | // must retry once with thinking off instead of reporting an empty edition. |
| 17 | func TestExecTaskRetriesWithoutThinking(t *testing.T) { |
| 18 | var mu sync.Mutex |
| 19 | var bodies []string |
| 20 | srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 21 | b, _ := io.ReadAll(r.Body) |
| 22 | mu.Lock() |
| 23 | bodies = append(bodies, string(b)) |
| 24 | call := len(bodies) |
| 25 | mu.Unlock() |
| 26 | if call == 1 { |
| 27 | // The whole budget went on thinking: no text, truncated. |
| 28 | json.NewEncoder(w).Encode(map[string]any{ |
| 29 | "content": []map[string]any{{"type": "thinking", "thinking": "hmm…", "signature": "sig"}}, |
| 30 | "stop_reason": "max_tokens", |
| 31 | }) |
| 32 | return |
| 33 | } |
| 34 | json.NewEncoder(w).Encode(map[string]any{ |
| 35 | "content": []map[string]any{{"type": "text", "text": "the edition"}}, |
| 36 | "stop_reason": "end_turn", |
| 37 | }) |
| 38 | })) |
| 39 | defer srv.Close() |
| 40 | t.Setenv("ANTHROPIC_BASE_URL", srv.URL) |
| 41 | |
| 42 | r := &Runtime{Session: &Session{Name: "Eleven"}, ai: newAnthropicClient("test-key", nil), Logf: t.Logf} |
| 43 | res, err := r.execTask("Test Bot", &TaskSpec{Prompt: "write the edition"}) |
| 44 | if err != nil { |
| 45 | t.Fatal(err) |
| 46 | } |
| 47 | if res.text != "the edition" { |
| 48 | t.Fatalf("text = %q, want the retry's edition", res.text) |
| 49 | } |
| 50 | if len(bodies) != 2 { |
| 51 | t.Fatalf("want 2 model calls (attempt + thinking-free retry), got %d", len(bodies)) |
| 52 | } |
| 53 | if !strings.Contains(bodies[0], `"thinking":{"type":"adaptive"}`) { |
| 54 | t.Error("first attempt should run with adaptive thinking") |
| 55 | } |
| 56 | if strings.Contains(bodies[1], `"thinking":{"type":"adaptive"}`) { |
| 57 | t.Error("the retry must run with thinking off") |
| 58 | } |
| 59 | } |
| 60 | |