openai_test.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. package openai
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "io"
  6. "net/http"
  7. "net/http/httptest"
  8. "strings"
  9. "testing"
  10. "time"
  11. "github.com/gin-gonic/gin"
  12. "github.com/ollama/ollama/api"
  13. "github.com/stretchr/testify/assert"
  14. )
  15. func TestMiddlewareRequests(t *testing.T) {
  16. type testCase struct {
  17. Name string
  18. Method string
  19. Path string
  20. Handler func() gin.HandlerFunc
  21. Setup func(t *testing.T, req *http.Request)
  22. Expected func(t *testing.T, req *http.Request)
  23. }
  24. var capturedRequest *http.Request
  25. captureRequestMiddleware := func() gin.HandlerFunc {
  26. return func(c *gin.Context) {
  27. bodyBytes, _ := io.ReadAll(c.Request.Body)
  28. c.Request.Body = io.NopCloser(bytes.NewReader(bodyBytes))
  29. capturedRequest = c.Request
  30. c.Next()
  31. }
  32. }
  33. testCases := []testCase{
  34. {
  35. Name: "chat handler",
  36. Method: http.MethodPost,
  37. Path: "/api/chat",
  38. Handler: ChatMiddleware,
  39. Setup: func(t *testing.T, req *http.Request) {
  40. body := ChatCompletionRequest{
  41. Model: "test-model",
  42. Messages: []Message{{Role: "user", Content: "Hello"}},
  43. }
  44. bodyBytes, _ := json.Marshal(body)
  45. req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
  46. req.Header.Set("Content-Type", "application/json")
  47. },
  48. Expected: func(t *testing.T, req *http.Request) {
  49. var chatReq api.ChatRequest
  50. if err := json.NewDecoder(req.Body).Decode(&chatReq); err != nil {
  51. t.Fatal(err)
  52. }
  53. if chatReq.Messages[0].Role != "user" {
  54. t.Fatalf("expected 'user', got %s", chatReq.Messages[0].Role)
  55. }
  56. if chatReq.Messages[0].Content != "Hello" {
  57. t.Fatalf("expected 'Hello', got %s", chatReq.Messages[0].Content)
  58. }
  59. },
  60. },
  61. {
  62. Name: "completions handler",
  63. Method: http.MethodPost,
  64. Path: "/api/generate",
  65. Handler: CompletionsMiddleware,
  66. Setup: func(t *testing.T, req *http.Request) {
  67. temp := float32(0.8)
  68. body := CompletionRequest{
  69. Model: "test-model",
  70. Prompt: "Hello",
  71. Temperature: &temp,
  72. }
  73. bodyBytes, _ := json.Marshal(body)
  74. req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
  75. req.Header.Set("Content-Type", "application/json")
  76. },
  77. Expected: func(t *testing.T, req *http.Request) {
  78. var genReq api.GenerateRequest
  79. if err := json.NewDecoder(req.Body).Decode(&genReq); err != nil {
  80. t.Fatal(err)
  81. }
  82. if genReq.Prompt != "Hello" {
  83. t.Fatalf("expected 'Hello', got %s", genReq.Prompt)
  84. }
  85. if genReq.Options["temperature"] != 1.6 {
  86. t.Fatalf("expected 1.6, got %f", genReq.Options["temperature"])
  87. }
  88. },
  89. },
  90. }
  91. gin.SetMode(gin.TestMode)
  92. router := gin.New()
  93. endpoint := func(c *gin.Context) {
  94. c.Status(http.StatusOK)
  95. }
  96. for _, tc := range testCases {
  97. t.Run(tc.Name, func(t *testing.T) {
  98. router = gin.New()
  99. router.Use(captureRequestMiddleware())
  100. router.Use(tc.Handler())
  101. router.Handle(tc.Method, tc.Path, endpoint)
  102. req, _ := http.NewRequest(tc.Method, tc.Path, nil)
  103. if tc.Setup != nil {
  104. tc.Setup(t, req)
  105. }
  106. resp := httptest.NewRecorder()
  107. router.ServeHTTP(resp, req)
  108. tc.Expected(t, capturedRequest)
  109. })
  110. }
  111. }
  112. func TestMiddlewareResponses(t *testing.T) {
  113. type testCase struct {
  114. Name string
  115. Method string
  116. Path string
  117. TestPath string
  118. Handler func() gin.HandlerFunc
  119. Endpoint func(c *gin.Context)
  120. Setup func(t *testing.T, req *http.Request)
  121. Expected func(t *testing.T, resp *httptest.ResponseRecorder)
  122. }
  123. testCases := []testCase{
  124. {
  125. Name: "completions handler error forwarding",
  126. Method: http.MethodPost,
  127. Path: "/api/generate",
  128. TestPath: "/api/generate",
  129. Handler: CompletionsMiddleware,
  130. Endpoint: func(c *gin.Context) {
  131. c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
  132. },
  133. Setup: func(t *testing.T, req *http.Request) {
  134. body := CompletionRequest{
  135. Model: "test-model",
  136. Prompt: "Hello",
  137. }
  138. bodyBytes, _ := json.Marshal(body)
  139. req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
  140. req.Header.Set("Content-Type", "application/json")
  141. },
  142. Expected: func(t *testing.T, resp *httptest.ResponseRecorder) {
  143. if resp.Code != http.StatusBadRequest {
  144. t.Fatalf("expected 400, got %d", resp.Code)
  145. }
  146. if !strings.Contains(resp.Body.String(), `"invalid request"`) {
  147. t.Fatalf("error was not forwarded")
  148. }
  149. },
  150. },
  151. {
  152. Name: "list handler",
  153. Method: http.MethodGet,
  154. Path: "/api/tags",
  155. TestPath: "/api/tags",
  156. Handler: ListMiddleware,
  157. Endpoint: func(c *gin.Context) {
  158. c.JSON(http.StatusOK, api.ListResponse{
  159. Models: []api.ListModelResponse{
  160. {
  161. Name: "Test Model",
  162. },
  163. },
  164. })
  165. },
  166. Expected: func(t *testing.T, resp *httptest.ResponseRecorder) {
  167. assert.Equal(t, http.StatusOK, resp.Code)
  168. var listResp ListCompletion
  169. if err := json.NewDecoder(resp.Body).Decode(&listResp); err != nil {
  170. t.Fatal(err)
  171. }
  172. if listResp.Object != "list" {
  173. t.Fatalf("expected list, got %s", listResp.Object)
  174. }
  175. if len(listResp.Data) != 1 {
  176. t.Fatalf("expected 1, got %d", len(listResp.Data))
  177. }
  178. if listResp.Data[0].Id != "Test Model" {
  179. t.Fatalf("expected Test Model, got %s", listResp.Data[0].Id)
  180. }
  181. },
  182. },
  183. {
  184. Name: "retrieve model",
  185. Method: http.MethodGet,
  186. Path: "/api/show/:model",
  187. TestPath: "/api/show/test-model",
  188. Handler: RetrieveMiddleware,
  189. Endpoint: func(c *gin.Context) {
  190. c.JSON(http.StatusOK, api.ShowResponse{
  191. ModifiedAt: time.Date(2024, 6, 17, 13, 45, 0, 0, time.UTC),
  192. })
  193. },
  194. Expected: func(t *testing.T, resp *httptest.ResponseRecorder) {
  195. var retrieveResp Model
  196. if err := json.NewDecoder(resp.Body).Decode(&retrieveResp); err != nil {
  197. t.Fatal(err)
  198. }
  199. if retrieveResp.Object != "model" {
  200. t.Fatalf("Expected object to be model, got %s", retrieveResp.Object)
  201. }
  202. if retrieveResp.Id != "test-model" {
  203. t.Fatalf("Expected id to be test-model, got %s", retrieveResp.Id)
  204. }
  205. },
  206. },
  207. }
  208. gin.SetMode(gin.TestMode)
  209. router := gin.New()
  210. for _, tc := range testCases {
  211. t.Run(tc.Name, func(t *testing.T) {
  212. router = gin.New()
  213. router.Use(tc.Handler())
  214. router.Handle(tc.Method, tc.Path, tc.Endpoint)
  215. req, _ := http.NewRequest(tc.Method, tc.TestPath, nil)
  216. if tc.Setup != nil {
  217. tc.Setup(t, req)
  218. }
  219. resp := httptest.NewRecorder()
  220. router.ServeHTTP(resp, req)
  221. tc.Expected(t, resp)
  222. })
  223. }
  224. }