openai_test.go 12.9 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
	"testing"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/assert"
Michael Yang's avatar
lint  
Michael Yang committed
16
17

	"github.com/ollama/ollama/api"
18
19
)

Michael Yang's avatar
lint  
Michael Yang committed
20
21
22
23
24
const (
	prefix   = `data:image/jpeg;base64,`
	image    = `iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=`
	imageURL = prefix + image
)
25

26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
func prepareRequest(req *http.Request, body any) {
	bodyBytes, _ := json.Marshal(body)
	req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
	req.Header.Set("Content-Type", "application/json")
}

func captureRequestMiddleware(capturedRequest any) gin.HandlerFunc {
	return func(c *gin.Context) {
		bodyBytes, _ := io.ReadAll(c.Request.Body)
		c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
		err := json.Unmarshal(bodyBytes, capturedRequest)
		if err != nil {
			c.AbortWithStatusJSON(http.StatusInternalServerError, "failed to unmarshal request")
		}
		c.Next()
	}
}

func TestChatMiddleware(t *testing.T) {
45
46
47
	type testCase struct {
		Name     string
		Setup    func(t *testing.T, req *http.Request)
48
		Expected func(t *testing.T, req *api.ChatRequest, resp *httptest.ResponseRecorder)
49
50
	}

51
	var capturedRequest *api.ChatRequest
52

royjhan's avatar
royjhan committed
53
54
	testCases := []testCase{
		{
55
			Name: "chat handler",
56
57
58
59
60
			Setup: func(t *testing.T, req *http.Request) {
				body := ChatCompletionRequest{
					Model:    "test-model",
					Messages: []Message{{Role: "user", Content: "Hello"}},
				}
61
62
63
64
65
66
				prepareRequest(req, body)
			},
			Expected: func(t *testing.T, req *api.ChatRequest, resp *httptest.ResponseRecorder) {
				if resp.Code != http.StatusOK {
					t.Fatalf("expected 200, got %d", resp.Code)
				}
67

68
69
70
				if req.Messages[0].Role != "user" {
					t.Fatalf("expected 'user', got %s", req.Messages[0].Role)
				}
71

72
73
74
				if req.Messages[0].Content != "Hello" {
					t.Fatalf("expected 'Hello', got %s", req.Messages[0].Content)
				}
75
			},
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
		},
		{
			Name: "chat handler with image content",
			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}},
							},
						},
					},
				}
				prepareRequest(req, body)
			},
			Expected: func(t *testing.T, req *api.ChatRequest, resp *httptest.ResponseRecorder) {
				if resp.Code != http.StatusOK {
					t.Fatalf("expected 200, got %d", resp.Code)
				}

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

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

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

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

				if !bytes.Equal(req.Messages[1].Images[0], img) {
					t.Fatalf("expected image encoding, got %s", req.Messages[1].Images[0])
				}
			},
		},
		{
			Name: "chat handler with tools",
			Setup: func(t *testing.T, req *http.Request) {
				body := ChatCompletionRequest{
					Model: "test-model",
					Messages: []Message{
						{Role: "user", Content: "What's the weather like in Paris Today?"},
						{Role: "assistant", ToolCalls: []ToolCall{{
							ID:   "id",
							Type: "function",
							Function: struct {
								Name      string `json:"name"`
								Arguments string `json:"arguments"`
							}{
								Name:      "get_current_weather",
								Arguments: "{\"location\": \"Paris, France\", \"format\": \"celsius\"}",
							},
						}}},
					},
				}
				prepareRequest(req, body)
			},
			Expected: func(t *testing.T, req *api.ChatRequest, resp *httptest.ResponseRecorder) {
				if resp.Code != 200 {
					t.Fatalf("expected 200, got %d", resp.Code)
				}

				if req.Messages[0].Content != "What's the weather like in Paris Today?" {
					t.Fatalf("expected What's the weather like in Paris Today?, got %s", req.Messages[0].Content)
146
147
				}

148
149
				if req.Messages[1].ToolCalls[0].Function.Arguments["location"] != "Paris, France" {
					t.Fatalf("expected 'Paris, France', got %v", req.Messages[1].ToolCalls[0].Function.Arguments["location"])
150
151
				}

152
153
				if req.Messages[1].ToolCalls[0].Function.Arguments["format"] != "celsius" {
					t.Fatalf("expected celsius, got %v", req.Messages[1].ToolCalls[0].Function.Arguments["format"])
154
155
156
				}
			},
		},
157
		{
158
159
160
161
162
163
164
165
166
167
168
169
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
			Name: "chat handler error forwarding",
			Setup: func(t *testing.T, req *http.Request) {
				body := ChatCompletionRequest{
					Model:    "test-model",
					Messages: []Message{{Role: "user", Content: 2}},
				}
				prepareRequest(req, body)
			},
			Expected: func(t *testing.T, req *api.ChatRequest, resp *httptest.ResponseRecorder) {
				if resp.Code != http.StatusBadRequest {
					t.Fatalf("expected 400, got %d", resp.Code)
				}

				if !strings.Contains(resp.Body.String(), "invalid message content type") {
					t.Fatalf("error was not forwarded")
				}
			},
		},
	}

	endpoint := func(c *gin.Context) {
		c.Status(http.StatusOK)
	}

	gin.SetMode(gin.TestMode)
	router := gin.New()
	router.Use(ChatMiddleware(), captureRequestMiddleware(&capturedRequest))
	router.Handle(http.MethodPost, "/api/chat", endpoint)

	for _, tc := range testCases {
		t.Run(tc.Name, func(t *testing.T) {
			req, _ := http.NewRequest(http.MethodPost, "/api/chat", nil)

			tc.Setup(t, req)

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

			tc.Expected(t, capturedRequest, resp)

			capturedRequest = nil
		})
	}
}

func TestCompletionsMiddleware(t *testing.T) {
	type testCase struct {
		Name     string
		Setup    func(t *testing.T, req *http.Request)
		Expected func(t *testing.T, req *api.GenerateRequest, resp *httptest.ResponseRecorder)
	}

	var capturedRequest *api.GenerateRequest

	testCases := []testCase{
		{
			Name: "completions handler",
215
			Setup: func(t *testing.T, req *http.Request) {
royjhan's avatar
royjhan committed
216
				temp := float32(0.8)
217
				body := CompletionRequest{
royjhan's avatar
royjhan committed
218
219
220
					Model:       "test-model",
					Prompt:      "Hello",
					Temperature: &temp,
221
					Stop:        []string{"\n", "stop"},
222
					Suffix:      "suffix",
223
				}
224
				prepareRequest(req, body)
225
			},
226
227
228
			Expected: func(t *testing.T, req *api.GenerateRequest, resp *httptest.ResponseRecorder) {
				if req.Prompt != "Hello" {
					t.Fatalf("expected 'Hello', got %s", req.Prompt)
229
230
				}

231
232
				if req.Options["temperature"] != 1.6 {
					t.Fatalf("expected 1.6, got %f", req.Options["temperature"])
233
				}
234

235
				stopTokens, ok := req.Options["stop"].([]any)
236
237
238
239
240
241
242
243

				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)
				}
244

245
246
				if req.Suffix != "suffix" {
					t.Fatalf("expected 'suffix', got %s", req.Suffix)
247
				}
248
249
			},
		},
250
		{
251
			Name: "completions handler error forwarding",
252
			Setup: func(t *testing.T, req *http.Request) {
253
254
255
256
257
258
				body := CompletionRequest{
					Model:       "test-model",
					Prompt:      "Hello",
					Temperature: nil,
					Stop:        []int{1, 2},
					Suffix:      "suffix",
259
				}
260
				prepareRequest(req, body)
261
			},
262
263
264
			Expected: func(t *testing.T, req *api.GenerateRequest, resp *httptest.ResponseRecorder) {
				if resp.Code != http.StatusBadRequest {
					t.Fatalf("expected 400, got %d", resp.Code)
265
266
				}

267
268
				if !strings.Contains(resp.Body.String(), "invalid type for 'stop' field") {
					t.Fatalf("error was not forwarded")
269
				}
270
271
272
			},
		},
	}
273

274
275
276
	endpoint := func(c *gin.Context) {
		c.Status(http.StatusOK)
	}
277

278
279
280
281
	gin.SetMode(gin.TestMode)
	router := gin.New()
	router.Use(CompletionsMiddleware(), captureRequestMiddleware(&capturedRequest))
	router.Handle(http.MethodPost, "/api/generate", endpoint)
282

283
284
285
	for _, tc := range testCases {
		t.Run(tc.Name, func(t *testing.T) {
			req, _ := http.NewRequest(http.MethodPost, "/api/generate", nil)
286

287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
			tc.Setup(t, req)

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

			tc.Expected(t, capturedRequest, resp)

			capturedRequest = nil
		})
	}
}

func TestEmbeddingsMiddleware(t *testing.T) {
	type testCase struct {
		Name     string
		Setup    func(t *testing.T, req *http.Request)
		Expected func(t *testing.T, req *api.EmbedRequest, resp *httptest.ResponseRecorder)
	}

	var capturedRequest *api.EmbedRequest

	testCases := []testCase{
309
		{
310
			Name: "embed handler single input",
311
312
313
314
315
			Setup: func(t *testing.T, req *http.Request) {
				body := EmbedRequest{
					Input: "Hello",
					Model: "test-model",
				}
316
				prepareRequest(req, body)
317
			},
318
319
320
			Expected: func(t *testing.T, req *api.EmbedRequest, resp *httptest.ResponseRecorder) {
				if req.Input != "Hello" {
					t.Fatalf("expected 'Hello', got %s", req.Input)
321
322
				}

323
324
				if req.Model != "test-model" {
					t.Fatalf("expected 'test-model', got %s", req.Model)
325
326
327
328
				}
			},
		},
		{
329
			Name: "embed handler batch input",
330
331
332
333
334
			Setup: func(t *testing.T, req *http.Request) {
				body := EmbedRequest{
					Input: []string{"Hello", "World"},
					Model: "test-model",
				}
335
				prepareRequest(req, body)
336
			},
337
338
			Expected: func(t *testing.T, req *api.EmbedRequest, resp *httptest.ResponseRecorder) {
				input, ok := req.Input.([]any)
339
340
341
342
343
344
345
346
347
348
349
350
351

				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])
				}

352
353
				if req.Model != "test-model" {
					t.Fatalf("expected 'test-model', got %s", req.Model)
354
355
356
				}
			},
		},
357
358
359
360
361
362
363
364
365
366
367
368
		{
			Name: "embed handler error forwarding",
			Setup: func(t *testing.T, req *http.Request) {
				body := EmbedRequest{
					Model: "test-model",
				}
				prepareRequest(req, body)
			},
			Expected: func(t *testing.T, req *api.EmbedRequest, resp *httptest.ResponseRecorder) {
				if resp.Code != http.StatusBadRequest {
					t.Fatalf("expected 400, got %d", resp.Code)
				}
369

370
371
372
373
374
375
				if !strings.Contains(resp.Body.String(), "invalid input") {
					t.Fatalf("error was not forwarded")
				}
			},
		},
	}
376

royjhan's avatar
royjhan committed
377
378
379
	endpoint := func(c *gin.Context) {
		c.Status(http.StatusOK)
	}
380

381
382
383
384
385
	gin.SetMode(gin.TestMode)
	router := gin.New()
	router.Use(EmbeddingsMiddleware(), captureRequestMiddleware(&capturedRequest))
	router.Handle(http.MethodPost, "/api/embed", endpoint)

royjhan's avatar
royjhan committed
386
387
	for _, tc := range testCases {
		t.Run(tc.Name, func(t *testing.T) {
388
			req, _ := http.NewRequest(http.MethodPost, "/api/embed", nil)
389

390
			tc.Setup(t, req)
391

royjhan's avatar
royjhan committed
392
393
			resp := httptest.NewRecorder()
			router.ServeHTTP(resp, req)
394

395
396
397
			tc.Expected(t, capturedRequest, resp)

			capturedRequest = nil
royjhan's avatar
royjhan committed
398
399
400
		})
	}
}
401

royjhan's avatar
royjhan committed
402
403
404
405
406
407
408
409
410
411
412
413
414
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{
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
		{
			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) {
				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)

494
495
			assert.Equal(t, http.StatusOK, resp.Code)

496
497
498
499
			tc.Expected(t, resp)
		})
	}
}