|
| 1 | +package chromem_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "io" |
| 8 | + "net/http" |
| 9 | + "net/http/httptest" |
| 10 | + "slices" |
| 11 | + "strings" |
| 12 | + "testing" |
| 13 | + |
| 14 | + "github.com/philippgille/chromem-go" |
| 15 | +) |
| 16 | + |
| 17 | +type openAIResponse struct { |
| 18 | + Data []struct { |
| 19 | + Embedding []float32 `json:"embedding"` |
| 20 | + } `json:"data"` |
| 21 | +} |
| 22 | + |
| 23 | +func TestNewEmbeddingFuncOpenAICompat(t *testing.T) { |
| 24 | + apiKey := "secret" |
| 25 | + model := "model-small" |
| 26 | + baseURLSuffix := "/v1" |
| 27 | + document := "hello world" |
| 28 | + |
| 29 | + wantBody, err := json.Marshal(map[string]string{ |
| 30 | + "input": document, |
| 31 | + "model": model, |
| 32 | + }) |
| 33 | + if err != nil { |
| 34 | + t.Error("unexpected error:", err) |
| 35 | + } |
| 36 | + wantRes := []float32{-0.1, 0.1, 0.2} |
| 37 | + |
| 38 | + // Mock server |
| 39 | + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 40 | + // Check URL |
| 41 | + if !strings.HasSuffix(r.URL.Path, baseURLSuffix+"/embeddings") { |
| 42 | + t.Error("expected URL", baseURLSuffix+"/embedding", "got", r.URL.Path) |
| 43 | + } |
| 44 | + // Check method |
| 45 | + if r.Method != "POST" { |
| 46 | + t.Error("expected method POST, got", r.Method) |
| 47 | + } |
| 48 | + // Check headers |
| 49 | + if r.Header.Get("Authorization") != "Bearer "+apiKey { |
| 50 | + t.Error("expected Authorization header", "Bearer "+apiKey, "got", r.Header.Get("Authorization")) |
| 51 | + } |
| 52 | + if r.Header.Get("Content-Type") != "application/json" { |
| 53 | + t.Error("expected Content-Type header", "application/json", "got", r.Header.Get("Content-Type")) |
| 54 | + } |
| 55 | + // Check body |
| 56 | + body, err := io.ReadAll(r.Body) |
| 57 | + if err != nil { |
| 58 | + t.Error("unexpected error:", err) |
| 59 | + } |
| 60 | + if !bytes.Equal(body, wantBody) { |
| 61 | + t.Error("expected body", wantBody, "got", body) |
| 62 | + } |
| 63 | + |
| 64 | + // Write response |
| 65 | + resp := openAIResponse{ |
| 66 | + Data: []struct { |
| 67 | + Embedding []float32 `json:"embedding"` |
| 68 | + }{ |
| 69 | + {Embedding: wantRes}, |
| 70 | + }, |
| 71 | + } |
| 72 | + w.WriteHeader(http.StatusOK) |
| 73 | + _ = json.NewEncoder(w).Encode(resp) |
| 74 | + })) |
| 75 | + defer ts.Close() |
| 76 | + baseURL := ts.URL + baseURLSuffix |
| 77 | + |
| 78 | + f := chromem.NewEmbeddingFuncOpenAICompat(baseURL, apiKey, model) |
| 79 | + res, err := f(context.Background(), document) |
| 80 | + if err != nil { |
| 81 | + t.Error("expected nil, got", err) |
| 82 | + } |
| 83 | + if slices.Compare[[]float32](wantRes, res) != 0 { |
| 84 | + t.Error("expected res", wantRes, "got", res) |
| 85 | + } |
| 86 | +} |
0 commit comments