| 1 | package assist |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "io" |
| 8 | "net/http" |
| 9 | "net/http/httptest" |
| 10 | "strings" |
| 11 | "sync" |
| 12 | "testing" |
| 13 | ) |
| 14 | |
| 15 | // fake is an OpenAI-compatible server answering what each test says. |
| 16 | type fake struct { |
| 17 | mu sync.Mutex |
| 18 | requests []map[string]any |
| 19 | auth []string |
| 20 | answer func(n int, req map[string]any) (int, string) |
| 21 | } |
| 22 | |
| 23 | func (f *fake) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 24 | body, _ := io.ReadAll(r.Body) |
| 25 | var req map[string]any |
| 26 | _ = json.Unmarshal(body, &req) |
| 27 | f.mu.Lock() |
| 28 | f.requests = append(f.requests, req) |
| 29 | f.auth = append(f.auth, r.Header.Get("Authorization")) |
| 30 | n := len(f.requests) |
| 31 | f.mu.Unlock() |
| 32 | if r.URL.Path != "/v1/chat/completions" { |
| 33 | http.NotFound(w, r) |
| 34 | return |
| 35 | } |
| 36 | status, out := f.answer(n, req) |
| 37 | w.Header().Set("Content-Type", "application/json") |
| 38 | w.WriteHeader(status) |
| 39 | io.WriteString(w, out) |
| 40 | } |
| 41 | |
| 42 | func completion(content, finish string) string { |
| 43 | b, _ := json.Marshal(map[string]any{"choices": []any{map[string]any{ |
| 44 | "message": map[string]any{"role": "assistant", "content": content}, "finish_reason": finish}}}) |
| 45 | return string(b) |
| 46 | } |
| 47 | |
| 48 | func serve(t *testing.T, f *fake) *Client { |
| 49 | t.Helper() |
| 50 | srv := httptest.NewServer(f) |
| 51 | t.Cleanup(srv.Close) |
| 52 | c, err := NewAt("secret-key", srv.URL+"/v1") |
| 53 | if err != nil { |
| 54 | t.Fatal(err) |
| 55 | } |
| 56 | return c |
| 57 | } |
| 58 | |
| 59 | func TestCompleteAsksForJSONAndReturnsTheContent(t *testing.T) { |
| 60 | f := &fake{answer: func(int, map[string]any) (int, string) { return 200, completion(`{"ops":[]}`, "stop") }} |
| 61 | c := serve(t, f) |
| 62 | got, err := c.Complete(context.Background(), "deepseek/x", []Message{{Role: "user", Content: "hi"}}) |
| 63 | if err != nil || got != `{"ops":[]}` { |
| 64 | t.Fatalf("Complete = %q, %v", got, err) |
| 65 | } |
| 66 | req := f.requests[0] |
| 67 | if req["model"] != "deepseek/x" || req["response_format"].(map[string]any)["type"] != "json_object" || req["max_tokens"].(float64) != MaxTokens { |
| 68 | t.Errorf("request = %v", req) |
| 69 | } |
| 70 | if f.auth[0] != "Bearer secret-key" { |
| 71 | t.Errorf("Authorization = %q", f.auth[0]) |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | func TestCompleteRetriesWithoutJSONModeOnA400(t *testing.T) { |
| 76 | f := &fake{answer: func(n int, req map[string]any) (int, string) { |
| 77 | if _, json := req["response_format"]; json { |
| 78 | return 400, `{"error":{"message":"response_format unsupported, you said: SECRET DECK TEXT"}}` |
| 79 | } |
| 80 | return 200, completion("ok", "stop") |
| 81 | }} |
| 82 | got, err := serve(t, f).Complete(context.Background(), "m", nil) |
| 83 | if err != nil || got != "ok" || len(f.requests) != 2 { |
| 84 | t.Fatalf("Complete = %q, %v after %d requests", got, err, len(f.requests)) |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | func TestCompleteFailuresCarryNoContent(t *testing.T) { |
| 89 | for name, tc := range map[string]struct { |
| 90 | status int |
| 91 | body string |
| 92 | want error |
| 93 | }{ |
| 94 | "a 500": {500, `{"error":"SECRET DECK TEXT"}`, nil}, |
| 95 | "cut short": {200, completion("SECRET DECK TEXT", "length"), ErrTruncated}, |
| 96 | "a content filter": {200, completion("SECRET DECK TEXT", "content_filter"), ErrMalformed}, |
| 97 | "two choices": {200, `{"choices":[{"finish_reason":"stop"},{"finish_reason":"stop"}]}`, ErrMalformed}, |
| 98 | "not json": {200, `SECRET DECK TEXT`, ErrMalformed}, |
| 99 | "over the cap": {200, `{"x":"` + strings.Repeat("a", maxResponse) + `"}`, ErrTooLarge}, |
| 100 | } { |
| 101 | t.Run(name, func(t *testing.T) { |
| 102 | f := &fake{answer: func(int, map[string]any) (int, string) { return tc.status, tc.body }} |
| 103 | _, err := serve(t, f).Complete(context.Background(), "m", nil) |
| 104 | if err == nil { |
| 105 | t.Fatal("no error") |
| 106 | } |
| 107 | if strings.Contains(err.Error(), "SECRET") { |
| 108 | t.Errorf("the error quotes the response: %v", err) |
| 109 | } |
| 110 | var status *StatusError |
| 111 | if tc.want == nil && !errors.As(err, &status) { |
| 112 | t.Errorf("err = %v, want a StatusError", err) |
| 113 | } |
| 114 | if tc.want != nil && !errors.Is(err, tc.want) { |
| 115 | t.Errorf("err = %v, want %v", err, tc.want) |
| 116 | } |
| 117 | }) |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | func TestClientDialsOnlyItsOwnHostAndFollowsNoRedirect(t *testing.T) { |
| 122 | other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 123 | t.Error("the other server was reached") |
| 124 | })) |
| 125 | defer other.Close() |
| 126 | redirect := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 127 | http.Redirect(w, r, other.URL+"/v1/chat/completions", http.StatusTemporaryRedirect) |
| 128 | })) |
| 129 | defer redirect.Close() |
| 130 | c, err := NewAt("k", redirect.URL+"/v1") |
| 131 | if err != nil { |
| 132 | t.Fatal(err) |
| 133 | } |
| 134 | if _, err := c.Complete(context.Background(), "m", nil); !errors.Is(err, ErrForbiddenHost) { |
| 135 | t.Errorf("a redirect: err = %v, want ErrForbiddenHost", err) |
| 136 | } |
| 137 | // The pin, directly: a request to another port on the same host. |
| 138 | c.base = other.URL + "/v1" |
| 139 | if _, err := c.Complete(context.Background(), "m", nil); !errors.Is(err, ErrForbiddenHost) { |
| 140 | t.Errorf("another port: err = %v, want ErrForbiddenHost", err) |
| 141 | } |
| 142 | if _, err := New(""); !errors.Is(err, ErrMissingKey) { |
| 143 | t.Errorf("New without a key: %v", err) |
| 144 | } |
| 145 | for _, base := range []string{"ftp://example.com/v1", "https://user:pw@example.com/v1", "not a url"} { |
| 146 | if _, err := NewAt("k", base); !errors.Is(err, ErrForbiddenHost) { |
| 147 | t.Errorf("NewAt(%q): %v", base, err) |
| 148 | } |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | func TestParseReplyTakesTheObjectOutOfItsWrapping(t *testing.T) { |
| 153 | for name, content := range map[string]string{ |
| 154 | "bare": `{"summary":"Done.","ops":[{"op":"set_meta","title":"x"}]}`, |
| 155 | "fenced": "```json\n{\"summary\":\"Done.\",\"ops\":[{\"op\":\"set_meta\",\"title\":\"x\"}]}\n```", |
| 156 | "chatty": "Here you go:\n{\"summary\":\"Done.\",\"ops\":[{\"op\":\"set_meta\",\"title\":\"x\"}],\"thoughts\":\"ignored\"}", |
| 157 | } { |
| 158 | t.Run(name, func(t *testing.T) { |
| 159 | r, err := ParseReply(content) |
| 160 | if err != nil || r.Summary != "Done." || len(r.Ops) != 1 || string(r.Ops[0]["op"]) != `"set_meta"` { |
| 161 | t.Errorf("ParseReply = %+v, %v", r, err) |
| 162 | } |
| 163 | }) |
| 164 | } |
| 165 | for name, content := range map[string]string{ |
| 166 | "no object": "I cannot do that.", |
| 167 | "no ops": `{"summary":"x"}`, |
| 168 | "ops not a list": `{"ops":{"op":"x"}}`, |
| 169 | "a null op": `{"ops":[null]}`, |
| 170 | "two objects": `{"ops":[]} {"ops":[{"op":"remove_slide"}]}`, |
| 171 | "summary not text": `{"ops":[],"summary":["x"]}`, |
| 172 | } { |
| 173 | t.Run(name, func(t *testing.T) { |
| 174 | if _, err := ParseReply(content); !errors.Is(err, ErrMalformed) { |
| 175 | t.Errorf("err = %v, want ErrMalformed", err) |
| 176 | } |
| 177 | }) |
| 178 | } |
| 179 | long, _ := ParseReply(`{"ops":[],"summary":"` + strings.Repeat("word ", 200) + `"}`) |
| 180 | if n := len([]rune(long.Summary)); n > MaxSummary+1 || !strings.HasSuffix(long.Summary, "…") { |
| 181 | t.Errorf("a long summary is %d runes: %q", n, long.Summary) |
| 182 | } |
| 183 | } |
| 184 | |