openai_test.go 10.1 KB
Newer Older
1
2
3
4
package openai

import (
	"bytes"
5
	"encoding/base64"
6
7
8
9
	"encoding/json"
	"io"
	"net/http"
	"net/http/httptest"
10
	"strings"
11
12
13
14
15
16
17
18
	"testing"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/ollama/ollama/api"
	"github.com/stretchr/testify/assert"
)

19
20
21
22
const prefix = `data:image/jpeg;base64,`
const image = `iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=`
const imageURL = prefix + image

royjhan's avatar
royjhan committed
23
func TestMiddlewareRequests(t *testing.T) {
24
25
26
27
28
29
	type testCase struct {
		Name     string
		Method   string
		Path     string
		Handler  func() gin.HandlerFunc
		Setup    func(t *testing.T, req *http.Request)
royjhan's avatar
royjhan committed
30
		Expected func(t *testing.T, req *http.Request)
31
32
	}

royjhan's avatar
royjhan committed
33
	var capturedRequest *http.Request
34

royjhan's avatar
royjhan committed
35
36
37
38
39
40
41
42
	captureRequestMiddleware := func() gin.HandlerFunc {
		return func(c *gin.Context) {
			bodyBytes, _ := io.ReadAll(c.Request.Body)
			c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
			capturedRequest = c.Request
			c.Next()
		}
	}
43

royjhan's avatar
royjhan committed
44
45
46
47
48
49
	testCases := []testCase{
		{
			Name:    "chat handler",
			Method:  http.MethodPost,
			Path:    "/api/chat",
			Handler: ChatMiddleware,
50
51
52
53
54
55
56
57
58
59
60
			Setup: func(t *testing.T, req *http.Request) {
				body := ChatCompletionRequest{
					Model:    "test-model",
					Messages: []Message{{Role: "user", Content: "Hello"}},
				}

				bodyBytes, _ := json.Marshal(body)

				req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
				req.Header.Set("Content-Type", "application/json")
			},
royjhan's avatar
royjhan committed
61
62
63
			Expected: func(t *testing.T, req *http.Request) {
				var chatReq api.ChatRequest
				if err := json.NewDecoder(req.Body).Decode(&chatReq); err != nil {
64
65
66
					t.Fatal(err)
				}

royjhan's avatar
royjhan committed
67
68
				if chatReq.Messages[0].Role != "user" {
					t.Fatalf("expected 'user', got %s", chatReq.Messages[0].Role)
69
70
				}

royjhan's avatar
royjhan committed
71
72
				if chatReq.Messages[0].Content != "Hello" {
					t.Fatalf("expected 'Hello', got %s", chatReq.Messages[0].Content)
73
74
75
				}
			},
		},
76
		{
royjhan's avatar
royjhan committed
77
78
79
80
			Name:    "completions handler",
			Method:  http.MethodPost,
			Path:    "/api/generate",
			Handler: CompletionsMiddleware,
81
			Setup: func(t *testing.T, req *http.Request) {
royjhan's avatar
royjhan committed
82
				temp := float32(0.8)
83
				body := CompletionRequest{
royjhan's avatar
royjhan committed
84
85
86
					Model:       "test-model",
					Prompt:      "Hello",
					Temperature: &temp,
87
					Stop:        []string{"\n", "stop"},
88
					Suffix:      "suffix",
89
90
91
92
93
94
95
				}

				bodyBytes, _ := json.Marshal(body)

				req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
				req.Header.Set("Content-Type", "application/json")
			},
royjhan's avatar
royjhan committed
96
97
98
			Expected: func(t *testing.T, req *http.Request) {
				var genReq api.GenerateRequest
				if err := json.NewDecoder(req.Body).Decode(&genReq); err != nil {
99
100
101
					t.Fatal(err)
				}

royjhan's avatar
royjhan committed
102
103
				if genReq.Prompt != "Hello" {
					t.Fatalf("expected 'Hello', got %s", genReq.Prompt)
104
105
				}

royjhan's avatar
royjhan committed
106
107
				if genReq.Options["temperature"] != 1.6 {
					t.Fatalf("expected 1.6, got %f", genReq.Options["temperature"])
108
				}
109
110
111
112
113
114
115
116
117
118

				stopTokens, ok := genReq.Options["stop"].([]any)

				if !ok {
					t.Fatalf("expected stop tokens to be a list")
				}

				if stopTokens[0] != "\n" || stopTokens[1] != "stop" {
					t.Fatalf("expected ['\\n', 'stop'], got %v", stopTokens)
				}
119
120
121
122

				if genReq.Suffix != "suffix" {
					t.Fatalf("expected 'suffix', got %s", genReq.Suffix)
				}
123
124
			},
		},
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
		{
			Name:    "chat handler with image content",
			Method:  http.MethodPost,
			Path:    "/api/chat",
			Handler: ChatMiddleware,
			Setup: func(t *testing.T, req *http.Request) {
				body := ChatCompletionRequest{
					Model: "test-model",
					Messages: []Message{
						{
							Role: "user", Content: []map[string]any{
								{"type": "text", "text": "Hello"},
								{"type": "image_url", "image_url": map[string]string{"url": imageURL}},
							},
						},
					},
				}

				bodyBytes, _ := json.Marshal(body)

				req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
				req.Header.Set("Content-Type", "application/json")
			},
			Expected: func(t *testing.T, req *http.Request) {
				var chatReq api.ChatRequest
				if err := json.NewDecoder(req.Body).Decode(&chatReq); err != nil {
					t.Fatal(err)
				}

				if chatReq.Messages[0].Role != "user" {
					t.Fatalf("expected 'user', got %s", chatReq.Messages[0].Role)
				}

				if chatReq.Messages[0].Content != "Hello" {
					t.Fatalf("expected 'Hello', got %s", chatReq.Messages[0].Content)
				}

				img, _ := base64.StdEncoding.DecodeString(imageURL[len(prefix):])

164
165
166
167
168
169
				if chatReq.Messages[1].Role != "user" {
					t.Fatalf("expected 'user', got %s", chatReq.Messages[1].Role)
				}

				if !bytes.Equal(chatReq.Messages[1].Images[0], img) {
					t.Fatalf("expected image encoding, got %s", chatReq.Messages[1].Images[0])
170
171
172
				}
			},
		},
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
		{
			Name:    "embed handler single input",
			Method:  http.MethodPost,
			Path:    "/api/embed",
			Handler: EmbeddingsMiddleware,
			Setup: func(t *testing.T, req *http.Request) {
				body := EmbedRequest{
					Input: "Hello",
					Model: "test-model",
				}

				bodyBytes, _ := json.Marshal(body)

				req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
				req.Header.Set("Content-Type", "application/json")
			},
			Expected: func(t *testing.T, req *http.Request) {
				var embedReq api.EmbedRequest
				if err := json.NewDecoder(req.Body).Decode(&embedReq); err != nil {
					t.Fatal(err)
				}

				if embedReq.Input != "Hello" {
					t.Fatalf("expected 'Hello', got %s", embedReq.Input)
				}

				if embedReq.Model != "test-model" {
					t.Fatalf("expected 'test-model', got %s", embedReq.Model)
				}
			},
		},
		{
			Name:    "embed handler batch input",
			Method:  http.MethodPost,
			Path:    "/api/embed",
			Handler: EmbeddingsMiddleware,
			Setup: func(t *testing.T, req *http.Request) {
				body := EmbedRequest{
					Input: []string{"Hello", "World"},
					Model: "test-model",
				}

				bodyBytes, _ := json.Marshal(body)

				req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
				req.Header.Set("Content-Type", "application/json")
			},
			Expected: func(t *testing.T, req *http.Request) {
				var embedReq api.EmbedRequest
				if err := json.NewDecoder(req.Body).Decode(&embedReq); err != nil {
					t.Fatal(err)
				}

				input, ok := embedReq.Input.([]any)

				if !ok {
					t.Fatalf("expected input to be a list")
				}

				if input[0].(string) != "Hello" {
					t.Fatalf("expected 'Hello', got %s", input[0])
				}

				if input[1].(string) != "World" {
					t.Fatalf("expected 'World', got %s", input[1])
				}

				if embedReq.Model != "test-model" {
					t.Fatalf("expected 'test-model', got %s", embedReq.Model)
				}
			},
		},
royjhan's avatar
royjhan committed
245
	}
246

royjhan's avatar
royjhan committed
247
248
	gin.SetMode(gin.TestMode)
	router := gin.New()
249

royjhan's avatar
royjhan committed
250
251
252
	endpoint := func(c *gin.Context) {
		c.Status(http.StatusOK)
	}
253

royjhan's avatar
royjhan committed
254
255
256
257
258
259
260
	for _, tc := range testCases {
		t.Run(tc.Name, func(t *testing.T) {
			router = gin.New()
			router.Use(captureRequestMiddleware())
			router.Use(tc.Handler())
			router.Handle(tc.Method, tc.Path, endpoint)
			req, _ := http.NewRequest(tc.Method, tc.Path, nil)
261

royjhan's avatar
royjhan committed
262
263
264
			if tc.Setup != nil {
				tc.Setup(t, req)
			}
265

royjhan's avatar
royjhan committed
266
267
			resp := httptest.NewRecorder()
			router.ServeHTTP(resp, req)
268

royjhan's avatar
royjhan committed
269
270
271
272
			tc.Expected(t, capturedRequest)
		})
	}
}
273

royjhan's avatar
royjhan committed
274
275
276
277
278
279
280
281
282
283
284
285
286
func TestMiddlewareResponses(t *testing.T) {
	type testCase struct {
		Name     string
		Method   string
		Path     string
		TestPath string
		Handler  func() gin.HandlerFunc
		Endpoint func(c *gin.Context)
		Setup    func(t *testing.T, req *http.Request)
		Expected func(t *testing.T, resp *httptest.ResponseRecorder)
	}

	testCases := []testCase{
287
		{
royjhan's avatar
royjhan committed
288
			Name:     "completions handler error forwarding",
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
			Method:   http.MethodPost,
			Path:     "/api/generate",
			TestPath: "/api/generate",
			Handler:  CompletionsMiddleware,
			Endpoint: func(c *gin.Context) {
				c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
			},
			Setup: func(t *testing.T, req *http.Request) {
				body := CompletionRequest{
					Model:  "test-model",
					Prompt: "Hello",
				}

				bodyBytes, _ := json.Marshal(body)

				req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
				req.Header.Set("Content-Type", "application/json")
			},
			Expected: func(t *testing.T, resp *httptest.ResponseRecorder) {
				if resp.Code != http.StatusBadRequest {
					t.Fatalf("expected 400, got %d", resp.Code)
				}

				if !strings.Contains(resp.Body.String(), `"invalid request"`) {
					t.Fatalf("error was not forwarded")
				}
			},
		},
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
		{
			Name:     "list handler",
			Method:   http.MethodGet,
			Path:     "/api/tags",
			TestPath: "/api/tags",
			Handler:  ListMiddleware,
			Endpoint: func(c *gin.Context) {
				c.JSON(http.StatusOK, api.ListResponse{
					Models: []api.ListModelResponse{
						{
							Name: "Test Model",
						},
					},
				})
			},
			Expected: func(t *testing.T, resp *httptest.ResponseRecorder) {
333
334
				assert.Equal(t, http.StatusOK, resp.Code)

335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
				var listResp ListCompletion
				if err := json.NewDecoder(resp.Body).Decode(&listResp); err != nil {
					t.Fatal(err)
				}

				if listResp.Object != "list" {
					t.Fatalf("expected list, got %s", listResp.Object)
				}

				if len(listResp.Data) != 1 {
					t.Fatalf("expected 1, got %d", len(listResp.Data))
				}

				if listResp.Data[0].Id != "Test Model" {
					t.Fatalf("expected Test Model, got %s", listResp.Data[0].Id)
				}
			},
		},
		{
			Name:     "retrieve model",
			Method:   http.MethodGet,
			Path:     "/api/show/:model",
			TestPath: "/api/show/test-model",
			Handler:  RetrieveMiddleware,
			Endpoint: func(c *gin.Context) {
				c.JSON(http.StatusOK, api.ShowResponse{
					ModifiedAt: time.Date(2024, 6, 17, 13, 45, 0, 0, time.UTC),
				})
			},
			Expected: func(t *testing.T, resp *httptest.ResponseRecorder) {
				var retrieveResp Model
				if err := json.NewDecoder(resp.Body).Decode(&retrieveResp); err != nil {
					t.Fatal(err)
				}

				if retrieveResp.Object != "model" {
					t.Fatalf("Expected object to be model, got %s", retrieveResp.Object)
				}

				if retrieveResp.Id != "test-model" {
					t.Fatalf("Expected id to be test-model, got %s", retrieveResp.Id)
				}
			},
		},
	}

	gin.SetMode(gin.TestMode)
	router := gin.New()

	for _, tc := range testCases {
		t.Run(tc.Name, func(t *testing.T) {
			router = gin.New()
			router.Use(tc.Handler())
			router.Handle(tc.Method, tc.Path, tc.Endpoint)
			req, _ := http.NewRequest(tc.Method, tc.TestPath, nil)

			if tc.Setup != nil {
				tc.Setup(t, req)
			}

			resp := httptest.NewRecorder()
			router.ServeHTTP(resp, req)

			tc.Expected(t, resp)
		})
	}
}