openai_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. package openai
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "encoding/json"
  6. "io"
  7. "net/http"
  8. "net/http/httptest"
  9. "strings"
  10. "testing"
  11. "time"
  12. "github.com/gin-gonic/gin"
  13. "github.com/stretchr/testify/assert"
  14. "github.com/ollama/ollama/api"
  15. )
  16. const (
  17. prefix = `data:image/jpeg;base64,`
  18. image = `iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=`
  19. imageURL = prefix + image
  20. )
  21. func prepareRequest(req *http.Request, body any) {
  22. bodyBytes, _ := json.Marshal(body)
  23. req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
  24. req.Header.Set("Content-Type", "application/json")
  25. }
  26. func captureRequestMiddleware(capturedRequest any) gin.HandlerFunc {
  27. return func(c *gin.Context) {
  28. bodyBytes, _ := io.ReadAll(c.Request.Body)
  29. c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
  30. err := json.Unmarshal(bodyBytes, capturedRequest)
  31. if err != nil {
  32. c.AbortWithStatusJSON(http.StatusInternalServerError, "failed to unmarshal request")
  33. }
  34. c.Next()
  35. }
  36. }
  37. func TestChatMiddleware(t *testing.T) {
  38. type testCase struct {
  39. Name string
  40. Setup func(t *testing.T, req *http.Request)
  41. Expected func(t *testing.T, req *api.ChatRequest, resp *httptest.ResponseRecorder)
  42. }
  43. var capturedRequest *api.ChatRequest
  44. testCases := []testCase{
  45. {
  46. Name: "chat handler",
  47. Setup: func(t *testing.T, req *http.Request) {
  48. body := ChatCompletionRequest{
  49. Model: "test-model",
  50. Messages: []Message{{Role: "user", Content: "Hello"}},
  51. }
  52. prepareRequest(req, body)
  53. },
  54. Expected: func(t *testing.T, req *api.ChatRequest, resp *httptest.ResponseRecorder) {
  55. if resp.Code != http.StatusOK {
  56. t.Fatalf("expected 200, got %d", resp.Code)
  57. }
  58. if req.Messages[0].Role != "user" {
  59. t.Fatalf("expected 'user', got %s", req.Messages[0].Role)
  60. }
  61. if req.Messages[0].Content != "Hello" {
  62. t.Fatalf("expected 'Hello', got %s", req.Messages[0].Content)
  63. }
  64. },
  65. },
  66. {
  67. Name: "chat handler with image content",
  68. Setup: func(t *testing.T, req *http.Request) {
  69. body := ChatCompletionRequest{
  70. Model: "test-model",
  71. Messages: []Message{
  72. {
  73. Role: "user", Content: []map[string]any{
  74. {"type": "text", "text": "Hello"},
  75. {"type": "image_url", "image_url": map[string]string{"url": imageURL}},
  76. },
  77. },
  78. },
  79. }
  80. prepareRequest(req, body)
  81. },
  82. Expected: func(t *testing.T, req *api.ChatRequest, resp *httptest.ResponseRecorder) {
  83. if resp.Code != http.StatusOK {
  84. t.Fatalf("expected 200, got %d", resp.Code)
  85. }
  86. if req.Messages[0].Role != "user" {
  87. t.Fatalf("expected 'user', got %s", req.Messages[0].Role)
  88. }
  89. if req.Messages[0].Content != "Hello" {
  90. t.Fatalf("expected 'Hello', got %s", req.Messages[0].Content)
  91. }
  92. img, _ := base64.StdEncoding.DecodeString(imageURL[len(prefix):])
  93. if req.Messages[1].Role != "user" {
  94. t.Fatalf("expected 'user', got %s", req.Messages[1].Role)
  95. }
  96. if !bytes.Equal(req.Messages[1].Images[0], img) {
  97. t.Fatalf("expected image encoding, got %s", req.Messages[1].Images[0])
  98. }
  99. },
  100. },
  101. {
  102. Name: "chat handler with tools",
  103. Setup: func(t *testing.T, req *http.Request) {
  104. body := ChatCompletionRequest{
  105. Model: "test-model",
  106. Messages: []Message{
  107. {Role: "user", Content: "What's the weather like in Paris Today?"},
  108. {Role: "assistant", ToolCalls: []ToolCall{{
  109. ID: "id",
  110. Type: "function",
  111. Function: struct {
  112. Name string `json:"name"`
  113. Arguments string `json:"arguments"`
  114. }{
  115. Name: "get_current_weather",
  116. Arguments: "{\"location\": \"Paris, France\", \"format\": \"celsius\"}",
  117. },
  118. }}},
  119. },
  120. }
  121. prepareRequest(req, body)
  122. },
  123. Expected: func(t *testing.T, req *api.ChatRequest, resp *httptest.ResponseRecorder) {
  124. if resp.Code != 200 {
  125. t.Fatalf("expected 200, got %d", resp.Code)
  126. }
  127. if req.Messages[0].Content != "What's the weather like in Paris Today?" {
  128. t.Fatalf("expected What's the weather like in Paris Today?, got %s", req.Messages[0].Content)
  129. }
  130. if req.Messages[1].ToolCalls[0].Function.Arguments["location"] != "Paris, France" {
  131. t.Fatalf("expected 'Paris, France', got %v", req.Messages[1].ToolCalls[0].Function.Arguments["location"])
  132. }
  133. if req.Messages[1].ToolCalls[0].Function.Arguments["format"] != "celsius" {
  134. t.Fatalf("expected celsius, got %v", req.Messages[1].ToolCalls[0].Function.Arguments["format"])
  135. }
  136. },
  137. },
  138. {
  139. Name: "chat handler error forwarding",
  140. Setup: func(t *testing.T, req *http.Request) {
  141. body := ChatCompletionRequest{
  142. Model: "test-model",
  143. Messages: []Message{{Role: "user", Content: 2}},
  144. }
  145. prepareRequest(req, body)
  146. },
  147. Expected: func(t *testing.T, req *api.ChatRequest, resp *httptest.ResponseRecorder) {
  148. if resp.Code != http.StatusBadRequest {
  149. t.Fatalf("expected 400, got %d", resp.Code)
  150. }
  151. if !strings.Contains(resp.Body.String(), "invalid message content type") {
  152. t.Fatalf("error was not forwarded")
  153. }
  154. },
  155. },
  156. }
  157. endpoint := func(c *gin.Context) {
  158. c.Status(http.StatusOK)
  159. }
  160. gin.SetMode(gin.TestMode)
  161. router := gin.New()
  162. router.Use(ChatMiddleware(), captureRequestMiddleware(&capturedRequest))
  163. router.Handle(http.MethodPost, "/api/chat", endpoint)
  164. for _, tc := range testCases {
  165. t.Run(tc.Name, func(t *testing.T) {
  166. req, _ := http.NewRequest(http.MethodPost, "/api/chat", nil)
  167. tc.Setup(t, req)
  168. resp := httptest.NewRecorder()
  169. router.ServeHTTP(resp, req)
  170. tc.Expected(t, capturedRequest, resp)
  171. capturedRequest = nil
  172. })
  173. }
  174. }
  175. func TestCompletionsMiddleware(t *testing.T) {
  176. type testCase struct {
  177. Name string
  178. Setup func(t *testing.T, req *http.Request)
  179. Expected func(t *testing.T, req *api.GenerateRequest, resp *httptest.ResponseRecorder)
  180. }
  181. var capturedRequest *api.GenerateRequest
  182. testCases := []testCase{
  183. {
  184. Name: "completions handler",
  185. Setup: func(t *testing.T, req *http.Request) {
  186. temp := float32(0.8)
  187. body := CompletionRequest{
  188. Model: "test-model",
  189. Prompt: "Hello",
  190. Temperature: &temp,
  191. Stop: []string{"\n", "stop"},
  192. Suffix: "suffix",
  193. }
  194. prepareRequest(req, body)
  195. },
  196. Expected: func(t *testing.T, req *api.GenerateRequest, resp *httptest.ResponseRecorder) {
  197. if req.Prompt != "Hello" {
  198. t.Fatalf("expected 'Hello', got %s", req.Prompt)
  199. }
  200. if req.Options["temperature"] != 1.6 {
  201. t.Fatalf("expected 1.6, got %f", req.Options["temperature"])
  202. }
  203. stopTokens, ok := req.Options["stop"].([]any)
  204. if !ok {
  205. t.Fatalf("expected stop tokens to be a list")
  206. }
  207. if stopTokens[0] != "\n" || stopTokens[1] != "stop" {
  208. t.Fatalf("expected ['\\n', 'stop'], got %v", stopTokens)
  209. }
  210. if req.Suffix != "suffix" {
  211. t.Fatalf("expected 'suffix', got %s", req.Suffix)
  212. }
  213. },
  214. },
  215. {
  216. Name: "completions handler error forwarding",
  217. Setup: func(t *testing.T, req *http.Request) {
  218. body := CompletionRequest{
  219. Model: "test-model",
  220. Prompt: "Hello",
  221. Temperature: nil,
  222. Stop: []int{1, 2},
  223. Suffix: "suffix",
  224. }
  225. prepareRequest(req, body)
  226. },
  227. Expected: func(t *testing.T, req *api.GenerateRequest, resp *httptest.ResponseRecorder) {
  228. if resp.Code != http.StatusBadRequest {
  229. t.Fatalf("expected 400, got %d", resp.Code)
  230. }
  231. if !strings.Contains(resp.Body.String(), "invalid type for 'stop' field") {
  232. t.Fatalf("error was not forwarded")
  233. }
  234. },
  235. },
  236. }
  237. endpoint := func(c *gin.Context) {
  238. c.Status(http.StatusOK)
  239. }
  240. gin.SetMode(gin.TestMode)
  241. router := gin.New()
  242. router.Use(CompletionsMiddleware(), captureRequestMiddleware(&capturedRequest))
  243. router.Handle(http.MethodPost, "/api/generate", endpoint)
  244. for _, tc := range testCases {
  245. t.Run(tc.Name, func(t *testing.T) {
  246. req, _ := http.NewRequest(http.MethodPost, "/api/generate", nil)
  247. tc.Setup(t, req)
  248. resp := httptest.NewRecorder()
  249. router.ServeHTTP(resp, req)
  250. tc.Expected(t, capturedRequest, resp)
  251. capturedRequest = nil
  252. })
  253. }
  254. }
  255. func TestEmbeddingsMiddleware(t *testing.T) {
  256. type testCase struct {
  257. Name string
  258. Setup func(t *testing.T, req *http.Request)
  259. Expected func(t *testing.T, req *api.EmbedRequest, resp *httptest.ResponseRecorder)
  260. }
  261. var capturedRequest *api.EmbedRequest
  262. testCases := []testCase{
  263. {
  264. Name: "embed handler single input",
  265. Setup: func(t *testing.T, req *http.Request) {
  266. body := EmbedRequest{
  267. Input: "Hello",
  268. Model: "test-model",
  269. }
  270. prepareRequest(req, body)
  271. },
  272. Expected: func(t *testing.T, req *api.EmbedRequest, resp *httptest.ResponseRecorder) {
  273. if req.Input != "Hello" {
  274. t.Fatalf("expected 'Hello', got %s", req.Input)
  275. }
  276. if req.Model != "test-model" {
  277. t.Fatalf("expected 'test-model', got %s", req.Model)
  278. }
  279. },
  280. },
  281. {
  282. Name: "embed handler batch input",
  283. Setup: func(t *testing.T, req *http.Request) {
  284. body := EmbedRequest{
  285. Input: []string{"Hello", "World"},
  286. Model: "test-model",
  287. }
  288. prepareRequest(req, body)
  289. },
  290. Expected: func(t *testing.T, req *api.EmbedRequest, resp *httptest.ResponseRecorder) {
  291. input, ok := req.Input.([]any)
  292. if !ok {
  293. t.Fatalf("expected input to be a list")
  294. }
  295. if input[0].(string) != "Hello" {
  296. t.Fatalf("expected 'Hello', got %s", input[0])
  297. }
  298. if input[1].(string) != "World" {
  299. t.Fatalf("expected 'World', got %s", input[1])
  300. }
  301. if req.Model != "test-model" {
  302. t.Fatalf("expected 'test-model', got %s", req.Model)
  303. }
  304. },
  305. },
  306. {
  307. Name: "embed handler error forwarding",
  308. Setup: func(t *testing.T, req *http.Request) {
  309. body := EmbedRequest{
  310. Model: "test-model",
  311. }
  312. prepareRequest(req, body)
  313. },
  314. Expected: func(t *testing.T, req *api.EmbedRequest, resp *httptest.ResponseRecorder) {
  315. if resp.Code != http.StatusBadRequest {
  316. t.Fatalf("expected 400, got %d", resp.Code)
  317. }
  318. if !strings.Contains(resp.Body.String(), "invalid input") {
  319. t.Fatalf("error was not forwarded")
  320. }
  321. },
  322. },
  323. }
  324. endpoint := func(c *gin.Context) {
  325. c.Status(http.StatusOK)
  326. }
  327. gin.SetMode(gin.TestMode)
  328. router := gin.New()
  329. router.Use(EmbeddingsMiddleware(), captureRequestMiddleware(&capturedRequest))
  330. router.Handle(http.MethodPost, "/api/embed", endpoint)
  331. for _, tc := range testCases {
  332. t.Run(tc.Name, func(t *testing.T) {
  333. req, _ := http.NewRequest(http.MethodPost, "/api/embed", nil)
  334. tc.Setup(t, req)
  335. resp := httptest.NewRecorder()
  336. router.ServeHTTP(resp, req)
  337. tc.Expected(t, capturedRequest, resp)
  338. capturedRequest = nil
  339. })
  340. }
  341. }
  342. func TestMiddlewareResponses(t *testing.T) {
  343. type testCase struct {
  344. Name string
  345. Method string
  346. Path string
  347. TestPath string
  348. Handler func() gin.HandlerFunc
  349. Endpoint func(c *gin.Context)
  350. Setup func(t *testing.T, req *http.Request)
  351. Expected func(t *testing.T, resp *httptest.ResponseRecorder)
  352. }
  353. testCases := []testCase{
  354. {
  355. Name: "list handler",
  356. Method: http.MethodGet,
  357. Path: "/api/tags",
  358. TestPath: "/api/tags",
  359. Handler: ListMiddleware,
  360. Endpoint: func(c *gin.Context) {
  361. c.JSON(http.StatusOK, api.ListResponse{
  362. Models: []api.ListModelResponse{
  363. {
  364. Name: "Test Model",
  365. },
  366. },
  367. })
  368. },
  369. Expected: func(t *testing.T, resp *httptest.ResponseRecorder) {
  370. var listResp ListCompletion
  371. if err := json.NewDecoder(resp.Body).Decode(&listResp); err != nil {
  372. t.Fatal(err)
  373. }
  374. if listResp.Object != "list" {
  375. t.Fatalf("expected list, got %s", listResp.Object)
  376. }
  377. if len(listResp.Data) != 1 {
  378. t.Fatalf("expected 1, got %d", len(listResp.Data))
  379. }
  380. if listResp.Data[0].Id != "Test Model" {
  381. t.Fatalf("expected Test Model, got %s", listResp.Data[0].Id)
  382. }
  383. },
  384. },
  385. {
  386. Name: "retrieve model",
  387. Method: http.MethodGet,
  388. Path: "/api/show/:model",
  389. TestPath: "/api/show/test-model",
  390. Handler: RetrieveMiddleware,
  391. Endpoint: func(c *gin.Context) {
  392. c.JSON(http.StatusOK, api.ShowResponse{
  393. ModifiedAt: time.Date(2024, 6, 17, 13, 45, 0, 0, time.UTC),
  394. })
  395. },
  396. Expected: func(t *testing.T, resp *httptest.ResponseRecorder) {
  397. var retrieveResp Model
  398. if err := json.NewDecoder(resp.Body).Decode(&retrieveResp); err != nil {
  399. t.Fatal(err)
  400. }
  401. if retrieveResp.Object != "model" {
  402. t.Fatalf("Expected object to be model, got %s", retrieveResp.Object)
  403. }
  404. if retrieveResp.Id != "test-model" {
  405. t.Fatalf("Expected id to be test-model, got %s", retrieveResp.Id)
  406. }
  407. },
  408. },
  409. }
  410. gin.SetMode(gin.TestMode)
  411. router := gin.New()
  412. for _, tc := range testCases {
  413. t.Run(tc.Name, func(t *testing.T) {
  414. router = gin.New()
  415. router.Use(tc.Handler())
  416. router.Handle(tc.Method, tc.Path, tc.Endpoint)
  417. req, _ := http.NewRequest(tc.Method, tc.TestPath, nil)
  418. if tc.Setup != nil {
  419. tc.Setup(t, req)
  420. }
  421. resp := httptest.NewRecorder()
  422. router.ServeHTTP(resp, req)
  423. assert.Equal(t, http.StatusOK, resp.Code)
  424. tc.Expected(t, resp)
  425. })
  426. }
  427. }