openai_test.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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. Stop: []string{"\n", "stop"},
  73. }
  74. bodyBytes, _ := json.Marshal(body)
  75. req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
  76. req.Header.Set("Content-Type", "application/json")
  77. },
  78. Expected: func(t *testing.T, req *http.Request) {
  79. var genReq api.GenerateRequest
  80. if err := json.NewDecoder(req.Body).Decode(&genReq); err != nil {
  81. t.Fatal(err)
  82. }
  83. if genReq.Prompt != "Hello" {
  84. t.Fatalf("expected 'Hello', got %s", genReq.Prompt)
  85. }
  86. if genReq.Options["temperature"] != 1.6 {
  87. t.Fatalf("expected 1.6, got %f", genReq.Options["temperature"])
  88. }
  89. stopTokens, ok := genReq.Options["stop"].([]any)
  90. if !ok {
  91. t.Fatalf("expected stop tokens to be a list")
  92. }
  93. if stopTokens[0] != "\n" || stopTokens[1] != "stop" {
  94. t.Fatalf("expected ['\\n', 'stop'], got %v", stopTokens)
  95. }
  96. },
  97. },
  98. }
  99. gin.SetMode(gin.TestMode)
  100. router := gin.New()
  101. endpoint := func(c *gin.Context) {
  102. c.Status(http.StatusOK)
  103. }
  104. for _, tc := range testCases {
  105. t.Run(tc.Name, func(t *testing.T) {
  106. router = gin.New()
  107. router.Use(captureRequestMiddleware())
  108. router.Use(tc.Handler())
  109. router.Handle(tc.Method, tc.Path, endpoint)
  110. req, _ := http.NewRequest(tc.Method, tc.Path, nil)
  111. if tc.Setup != nil {
  112. tc.Setup(t, req)
  113. }
  114. resp := httptest.NewRecorder()
  115. router.ServeHTTP(resp, req)
  116. tc.Expected(t, capturedRequest)
  117. })
  118. }
  119. }
  120. func TestMiddlewareResponses(t *testing.T) {
  121. type testCase struct {
  122. Name string
  123. Method string
  124. Path string
  125. TestPath string
  126. Handler func() gin.HandlerFunc
  127. Endpoint func(c *gin.Context)
  128. Setup func(t *testing.T, req *http.Request)
  129. Expected func(t *testing.T, resp *httptest.ResponseRecorder)
  130. }
  131. testCases := []testCase{
  132. {
  133. Name: "completions handler error forwarding",
  134. Method: http.MethodPost,
  135. Path: "/api/generate",
  136. TestPath: "/api/generate",
  137. Handler: CompletionsMiddleware,
  138. Endpoint: func(c *gin.Context) {
  139. c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
  140. },
  141. Setup: func(t *testing.T, req *http.Request) {
  142. body := CompletionRequest{
  143. Model: "test-model",
  144. Prompt: "Hello",
  145. }
  146. bodyBytes, _ := json.Marshal(body)
  147. req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
  148. req.Header.Set("Content-Type", "application/json")
  149. },
  150. Expected: func(t *testing.T, resp *httptest.ResponseRecorder) {
  151. if resp.Code != http.StatusBadRequest {
  152. t.Fatalf("expected 400, got %d", resp.Code)
  153. }
  154. if !strings.Contains(resp.Body.String(), `"invalid request"`) {
  155. t.Fatalf("error was not forwarded")
  156. }
  157. },
  158. },
  159. {
  160. Name: "list handler",
  161. Method: http.MethodGet,
  162. Path: "/api/tags",
  163. TestPath: "/api/tags",
  164. Handler: ListMiddleware,
  165. Endpoint: func(c *gin.Context) {
  166. c.JSON(http.StatusOK, api.ListResponse{
  167. Models: []api.ListModelResponse{
  168. {
  169. Name: "Test Model",
  170. },
  171. },
  172. })
  173. },
  174. Expected: func(t *testing.T, resp *httptest.ResponseRecorder) {
  175. assert.Equal(t, http.StatusOK, resp.Code)
  176. var listResp ListCompletion
  177. if err := json.NewDecoder(resp.Body).Decode(&listResp); err != nil {
  178. t.Fatal(err)
  179. }
  180. if listResp.Object != "list" {
  181. t.Fatalf("expected list, got %s", listResp.Object)
  182. }
  183. if len(listResp.Data) != 1 {
  184. t.Fatalf("expected 1, got %d", len(listResp.Data))
  185. }
  186. if listResp.Data[0].Id != "Test Model" {
  187. t.Fatalf("expected Test Model, got %s", listResp.Data[0].Id)
  188. }
  189. },
  190. },
  191. {
  192. Name: "retrieve model",
  193. Method: http.MethodGet,
  194. Path: "/api/show/:model",
  195. TestPath: "/api/show/test-model",
  196. Handler: RetrieveMiddleware,
  197. Endpoint: func(c *gin.Context) {
  198. c.JSON(http.StatusOK, api.ShowResponse{
  199. ModifiedAt: time.Date(2024, 6, 17, 13, 45, 0, 0, time.UTC),
  200. })
  201. },
  202. Expected: func(t *testing.T, resp *httptest.ResponseRecorder) {
  203. var retrieveResp Model
  204. if err := json.NewDecoder(resp.Body).Decode(&retrieveResp); err != nil {
  205. t.Fatal(err)
  206. }
  207. if retrieveResp.Object != "model" {
  208. t.Fatalf("Expected object to be model, got %s", retrieveResp.Object)
  209. }
  210. if retrieveResp.Id != "test-model" {
  211. t.Fatalf("Expected id to be test-model, got %s", retrieveResp.Id)
  212. }
  213. },
  214. },
  215. }
  216. gin.SetMode(gin.TestMode)
  217. router := gin.New()
  218. for _, tc := range testCases {
  219. t.Run(tc.Name, func(t *testing.T) {
  220. router = gin.New()
  221. router.Use(tc.Handler())
  222. router.Handle(tc.Method, tc.Path, tc.Endpoint)
  223. req, _ := http.NewRequest(tc.Method, tc.TestPath, nil)
  224. if tc.Setup != nil {
  225. tc.Setup(t, req)
  226. }
  227. resp := httptest.NewRecorder()
  228. router.ServeHTTP(resp, req)
  229. tc.Expected(t, resp)
  230. })
  231. }
  232. }