routes_test.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. package server
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/binary"
  6. "encoding/json"
  7. "fmt"
  8. "io"
  9. "math"
  10. "net/http"
  11. "net/http/httptest"
  12. "os"
  13. "sort"
  14. "strings"
  15. "testing"
  16. "github.com/ollama/ollama/api"
  17. "github.com/ollama/ollama/llm"
  18. "github.com/ollama/ollama/openai"
  19. "github.com/ollama/ollama/parser"
  20. "github.com/ollama/ollama/types/model"
  21. "github.com/ollama/ollama/version"
  22. )
  23. func createTestFile(t *testing.T, name string) string {
  24. t.Helper()
  25. f, err := os.CreateTemp(t.TempDir(), name)
  26. if err != nil {
  27. t.Fatalf("failed to create temp file: %v", err)
  28. }
  29. defer f.Close()
  30. err = binary.Write(f, binary.LittleEndian, []byte("GGUF"))
  31. if err != nil {
  32. t.Fatalf("failed to write to file: %v", err)
  33. }
  34. err = binary.Write(f, binary.LittleEndian, uint32(3))
  35. if err != nil {
  36. t.Fatalf("failed to write to file: %v", err)
  37. }
  38. err = binary.Write(f, binary.LittleEndian, uint64(0))
  39. if err != nil {
  40. t.Fatalf("failed to write to file: %v", err)
  41. }
  42. err = binary.Write(f, binary.LittleEndian, uint64(0))
  43. if err != nil {
  44. t.Fatalf("failed to write to file: %v", err)
  45. }
  46. return f.Name()
  47. }
  48. // equalStringSlices checks if two slices of strings are equal.
  49. func equalStringSlices(a, b []string) bool {
  50. if len(a) != len(b) {
  51. return false
  52. }
  53. for i := range a {
  54. if a[i] != b[i] {
  55. return false
  56. }
  57. }
  58. return true
  59. }
  60. func Test_Routes(t *testing.T) {
  61. type testCase struct {
  62. Name string
  63. Method string
  64. Path string
  65. Setup func(t *testing.T, req *http.Request)
  66. Expected func(t *testing.T, resp *http.Response)
  67. }
  68. createTestModel := func(t *testing.T, name string) {
  69. t.Helper()
  70. fname := createTestFile(t, "ollama-model")
  71. r := strings.NewReader(fmt.Sprintf("FROM %s\nPARAMETER seed 42\nPARAMETER top_p 0.9\nPARAMETER stop foo\nPARAMETER stop bar", fname))
  72. modelfile, err := parser.ParseFile(r)
  73. if err != nil {
  74. t.Fatalf("failed to parse file: %v", err)
  75. }
  76. fn := func(resp api.ProgressResponse) {
  77. t.Logf("Status: %s", resp.Status)
  78. }
  79. err = CreateModel(context.TODO(), model.ParseName(name), "", "", modelfile, fn)
  80. if err != nil {
  81. t.Fatalf("failed to create model: %v", err)
  82. }
  83. }
  84. testCases := []testCase{
  85. {
  86. Name: "Version Handler",
  87. Method: http.MethodGet,
  88. Path: "/api/version",
  89. Setup: func(t *testing.T, req *http.Request) {
  90. },
  91. Expected: func(t *testing.T, resp *http.Response) {
  92. contentType := resp.Header.Get("Content-Type")
  93. if contentType != "application/json; charset=utf-8" {
  94. t.Errorf("expected content type application/json; charset=utf-8, got %s", contentType)
  95. }
  96. body, err := io.ReadAll(resp.Body)
  97. if err != nil {
  98. t.Fatalf("failed to read response body: %v", err)
  99. }
  100. expectedBody := fmt.Sprintf(`{"version":"%s"}`, version.Version)
  101. if string(body) != expectedBody {
  102. t.Errorf("expected body %s, got %s", expectedBody, string(body))
  103. }
  104. },
  105. },
  106. {
  107. Name: "Tags Handler (no tags)",
  108. Method: http.MethodGet,
  109. Path: "/api/tags",
  110. Expected: func(t *testing.T, resp *http.Response) {
  111. contentType := resp.Header.Get("Content-Type")
  112. if contentType != "application/json; charset=utf-8" {
  113. t.Errorf("expected content type application/json; charset=utf-8, got %s", contentType)
  114. }
  115. body, err := io.ReadAll(resp.Body)
  116. if err != nil {
  117. t.Fatalf("failed to read response body: %v", err)
  118. }
  119. var modelList api.ListResponse
  120. err = json.Unmarshal(body, &modelList)
  121. if err != nil {
  122. t.Fatalf("failed to unmarshal response body: %v", err)
  123. }
  124. if modelList.Models == nil || len(modelList.Models) != 0 {
  125. t.Errorf("expected empty model list, got %v", modelList.Models)
  126. }
  127. },
  128. },
  129. {
  130. Name: "openai empty list",
  131. Method: http.MethodGet,
  132. Path: "/v1/models",
  133. Expected: func(t *testing.T, resp *http.Response) {
  134. contentType := resp.Header.Get("Content-Type")
  135. if contentType != "application/json" {
  136. t.Errorf("expected content type application/json, got %s", contentType)
  137. }
  138. body, err := io.ReadAll(resp.Body)
  139. if err != nil {
  140. t.Fatalf("failed to read response body: %v", err)
  141. }
  142. var modelList openai.ListCompletion
  143. err = json.Unmarshal(body, &modelList)
  144. if err != nil {
  145. t.Fatalf("failed to unmarshal response body: %v", err)
  146. }
  147. if modelList.Object != "list" || len(modelList.Data) != 0 {
  148. t.Errorf("expected empty model list, got %v", modelList.Data)
  149. }
  150. },
  151. },
  152. {
  153. Name: "Tags Handler (yes tags)",
  154. Method: http.MethodGet,
  155. Path: "/api/tags",
  156. Setup: func(t *testing.T, req *http.Request) {
  157. createTestModel(t, "test-model")
  158. },
  159. Expected: func(t *testing.T, resp *http.Response) {
  160. contentType := resp.Header.Get("Content-Type")
  161. if contentType != "application/json; charset=utf-8" {
  162. t.Errorf("expected content type application/json; charset=utf-8, got %s", contentType)
  163. }
  164. body, err := io.ReadAll(resp.Body)
  165. if err != nil {
  166. t.Fatalf("failed to read response body: %v", err)
  167. }
  168. if strings.Contains(string(body), "expires_at") {
  169. t.Errorf("response body should not contain 'expires_at'")
  170. }
  171. var modelList api.ListResponse
  172. err = json.Unmarshal(body, &modelList)
  173. if err != nil {
  174. t.Fatalf("failed to unmarshal response body: %v", err)
  175. }
  176. if len(modelList.Models) != 1 || modelList.Models[0].Name != "test-model:latest" {
  177. t.Errorf("expected model 'test-model:latest', got %v", modelList.Models)
  178. }
  179. },
  180. },
  181. {
  182. Name: "Delete Model Handler",
  183. Method: http.MethodDelete,
  184. Path: "/api/delete",
  185. Setup: func(t *testing.T, req *http.Request) {
  186. createTestModel(t, "model-to-delete")
  187. deleteReq := api.DeleteRequest{
  188. Name: "model-to-delete",
  189. }
  190. jsonData, err := json.Marshal(deleteReq)
  191. if err != nil {
  192. t.Fatalf("failed to marshal delete request: %v", err)
  193. }
  194. req.Body = io.NopCloser(bytes.NewReader(jsonData))
  195. },
  196. Expected: func(t *testing.T, resp *http.Response) {
  197. if resp.StatusCode != http.StatusOK {
  198. t.Errorf("expected status code 200, got %d", resp.StatusCode)
  199. }
  200. // Verify the model was deleted
  201. _, err := GetModel("model-to-delete")
  202. if err == nil || !os.IsNotExist(err) {
  203. t.Errorf("expected model to be deleted, got error %v", err)
  204. }
  205. },
  206. },
  207. {
  208. Name: "Delete Non-existent Model",
  209. Method: http.MethodDelete,
  210. Path: "/api/delete",
  211. Setup: func(t *testing.T, req *http.Request) {
  212. deleteReq := api.DeleteRequest{
  213. Name: "non-existent-model",
  214. }
  215. jsonData, err := json.Marshal(deleteReq)
  216. if err != nil {
  217. t.Fatalf("failed to marshal delete request: %v", err)
  218. }
  219. req.Body = io.NopCloser(bytes.NewReader(jsonData))
  220. },
  221. Expected: func(t *testing.T, resp *http.Response) {
  222. if resp.StatusCode != http.StatusNotFound {
  223. t.Errorf("expected status code 404, got %d", resp.StatusCode)
  224. }
  225. body, err := io.ReadAll(resp.Body)
  226. if err != nil {
  227. t.Fatalf("failed to read response body: %v", err)
  228. }
  229. var errorResp map[string]string
  230. err = json.Unmarshal(body, &errorResp)
  231. if err != nil {
  232. t.Fatalf("failed to unmarshal response body: %v", err)
  233. }
  234. if !strings.Contains(errorResp["error"], "not found") {
  235. t.Errorf("expected error message to contain 'not found', got %s", errorResp["error"])
  236. }
  237. },
  238. },
  239. {
  240. Name: "openai list models with tags",
  241. Method: http.MethodGet,
  242. Path: "/v1/models",
  243. Expected: func(t *testing.T, resp *http.Response) {
  244. contentType := resp.Header.Get("Content-Type")
  245. if contentType != "application/json" {
  246. t.Errorf("expected content type application/json, got %s", contentType)
  247. }
  248. body, err := io.ReadAll(resp.Body)
  249. if err != nil {
  250. t.Fatalf("failed to read response body: %v", err)
  251. }
  252. var modelList openai.ListCompletion
  253. err = json.Unmarshal(body, &modelList)
  254. if err != nil {
  255. t.Fatalf("failed to unmarshal response body: %v", err)
  256. }
  257. if len(modelList.Data) != 1 || modelList.Data[0].Id != "test-model:latest" || modelList.Data[0].OwnedBy != "library" {
  258. t.Errorf("expected model 'test-model:latest' owned by 'library', got %v", modelList.Data)
  259. }
  260. },
  261. },
  262. {
  263. Name: "Create Model Handler",
  264. Method: http.MethodPost,
  265. Path: "/api/create",
  266. Setup: func(t *testing.T, req *http.Request) {
  267. fname := createTestFile(t, "ollama-model")
  268. stream := false
  269. createReq := api.CreateRequest{
  270. Name: "t-bone",
  271. Modelfile: fmt.Sprintf("FROM %s", fname),
  272. Stream: &stream,
  273. }
  274. jsonData, err := json.Marshal(createReq)
  275. if err != nil {
  276. t.Fatalf("failed to marshal create request: %v", err)
  277. }
  278. req.Body = io.NopCloser(bytes.NewReader(jsonData))
  279. },
  280. Expected: func(t *testing.T, resp *http.Response) {
  281. contentType := resp.Header.Get("Content-Type")
  282. if contentType != "application/json" {
  283. t.Errorf("expected content type application/json, got %s", contentType)
  284. }
  285. _, err := io.ReadAll(resp.Body)
  286. if err != nil {
  287. t.Fatalf("failed to read response body: %v", err)
  288. }
  289. if resp.StatusCode != http.StatusOK { // Updated line
  290. t.Errorf("expected status code 200, got %d", resp.StatusCode)
  291. }
  292. model, err := GetModel("t-bone")
  293. if err != nil {
  294. t.Fatalf("failed to get model: %v", err)
  295. }
  296. if model.ShortName != "t-bone:latest" {
  297. t.Errorf("expected model name 't-bone:latest', got %s", model.ShortName)
  298. }
  299. },
  300. },
  301. {
  302. Name: "Copy Model Handler",
  303. Method: http.MethodPost,
  304. Path: "/api/copy",
  305. Setup: func(t *testing.T, req *http.Request) {
  306. createTestModel(t, "hamshank")
  307. copyReq := api.CopyRequest{
  308. Source: "hamshank",
  309. Destination: "beefsteak",
  310. }
  311. jsonData, err := json.Marshal(copyReq)
  312. if err != nil {
  313. t.Fatalf("failed to marshal copy request: %v", err)
  314. }
  315. req.Body = io.NopCloser(bytes.NewReader(jsonData))
  316. },
  317. Expected: func(t *testing.T, resp *http.Response) {
  318. model, err := GetModel("beefsteak")
  319. if err != nil {
  320. t.Fatalf("failed to get model: %v", err)
  321. }
  322. if model.ShortName != "beefsteak:latest" {
  323. t.Errorf("expected model name 'beefsteak:latest', got %s", model.ShortName)
  324. }
  325. },
  326. },
  327. {
  328. Name: "Show Model Handler",
  329. Method: http.MethodPost,
  330. Path: "/api/show",
  331. Setup: func(t *testing.T, req *http.Request) {
  332. createTestModel(t, "show-model")
  333. showReq := api.ShowRequest{Model: "show-model"}
  334. jsonData, err := json.Marshal(showReq)
  335. if err != nil {
  336. t.Fatalf("failed to marshal show request: %v", err)
  337. }
  338. req.Body = io.NopCloser(bytes.NewReader(jsonData))
  339. },
  340. Expected: func(t *testing.T, resp *http.Response) {
  341. contentType := resp.Header.Get("Content-Type")
  342. if contentType != "application/json; charset=utf-8" {
  343. t.Errorf("expected content type application/json; charset=utf-8, got %s", contentType)
  344. }
  345. body, err := io.ReadAll(resp.Body)
  346. if err != nil {
  347. t.Fatalf("failed to read response body: %v", err)
  348. }
  349. var showResp api.ShowResponse
  350. err = json.Unmarshal(body, &showResp)
  351. if err != nil {
  352. t.Fatalf("failed to unmarshal response body: %v", err)
  353. }
  354. var params []string
  355. paramsSplit := strings.Split(showResp.Parameters, "\n")
  356. for _, p := range paramsSplit {
  357. params = append(params, strings.Join(strings.Fields(p), " "))
  358. }
  359. sort.Strings(params)
  360. expectedParams := []string{
  361. "seed 42",
  362. "stop \"bar\"",
  363. "stop \"foo\"",
  364. "top_p 0.9",
  365. }
  366. if !equalStringSlices(params, expectedParams) {
  367. t.Errorf("expected parameters %v, got %v", expectedParams, params)
  368. }
  369. paramCount, ok := showResp.ModelInfo["general.parameter_count"].(float64)
  370. if !ok {
  371. t.Fatalf("expected parameter count to be a float64, got %T", showResp.ModelInfo["general.parameter_count"])
  372. }
  373. if math.Abs(paramCount) > 1e-9 {
  374. t.Errorf("expected parameter count to be 0, got %f", paramCount)
  375. }
  376. },
  377. },
  378. {
  379. Name: "openai retrieve model handler",
  380. Method: http.MethodGet,
  381. Path: "/v1/models/show-model",
  382. Expected: func(t *testing.T, resp *http.Response) {
  383. contentType := resp.Header.Get("Content-Type")
  384. if contentType != "application/json" {
  385. t.Errorf("expected content type application/json, got %s", contentType)
  386. }
  387. body, err := io.ReadAll(resp.Body)
  388. if err != nil {
  389. t.Fatalf("failed to read response body: %v", err)
  390. }
  391. var retrieveResp api.RetrieveModelResponse
  392. err = json.Unmarshal(body, &retrieveResp)
  393. if err != nil {
  394. t.Fatalf("failed to unmarshal response body: %v", err)
  395. }
  396. if retrieveResp.Id != "show-model" || retrieveResp.OwnedBy != "library" {
  397. t.Errorf("expected model 'show-model' owned by 'library', got %v", retrieveResp)
  398. }
  399. },
  400. },
  401. }
  402. t.Setenv("OLLAMA_MODELS", t.TempDir())
  403. s := &Server{}
  404. router := s.GenerateRoutes()
  405. httpSrv := httptest.NewServer(router)
  406. t.Cleanup(httpSrv.Close)
  407. for _, tc := range testCases {
  408. t.Run(tc.Name, func(t *testing.T) {
  409. u := httpSrv.URL + tc.Path
  410. req, err := http.NewRequestWithContext(context.TODO(), tc.Method, u, nil)
  411. if err != nil {
  412. t.Fatalf("failed to create request: %v", err)
  413. }
  414. if tc.Setup != nil {
  415. tc.Setup(t, req)
  416. }
  417. resp, err := httpSrv.Client().Do(req)
  418. if err != nil {
  419. t.Fatalf("failed to do request: %v", err)
  420. }
  421. defer resp.Body.Close()
  422. if tc.Expected != nil {
  423. tc.Expected(t, resp)
  424. }
  425. })
  426. }
  427. }
  428. func TestCase(t *testing.T) {
  429. t.Setenv("OLLAMA_MODELS", t.TempDir())
  430. cases := []string{
  431. "mistral",
  432. "llama3:latest",
  433. "library/phi3:q4_0",
  434. "registry.ollama.ai/library/gemma:q5_K_M",
  435. // TODO: host:port currently fails on windows (#4107)
  436. // "localhost:5000/alice/bob:latest",
  437. }
  438. var s Server
  439. for _, tt := range cases {
  440. t.Run(tt, func(t *testing.T) {
  441. w := createRequest(t, s.CreateHandler, api.CreateRequest{
  442. Name: tt,
  443. Modelfile: fmt.Sprintf("FROM %s", createBinFile(t, nil, nil)),
  444. Stream: &stream,
  445. })
  446. if w.Code != http.StatusOK {
  447. t.Fatalf("expected status 200 got %d", w.Code)
  448. }
  449. expect, err := json.Marshal(map[string]string{"error": "a model with that name already exists"})
  450. if err != nil {
  451. t.Fatal(err)
  452. }
  453. t.Run("create", func(t *testing.T) {
  454. w = createRequest(t, s.CreateHandler, api.CreateRequest{
  455. Name: strings.ToUpper(tt),
  456. Modelfile: fmt.Sprintf("FROM %s", createBinFile(t, nil, nil)),
  457. Stream: &stream,
  458. })
  459. if w.Code != http.StatusBadRequest {
  460. t.Fatalf("expected status 500 got %d", w.Code)
  461. }
  462. if !bytes.Equal(w.Body.Bytes(), expect) {
  463. t.Fatalf("expected error %s got %s", expect, w.Body.String())
  464. }
  465. })
  466. t.Run("pull", func(t *testing.T) {
  467. w := createRequest(t, s.PullHandler, api.PullRequest{
  468. Name: strings.ToUpper(tt),
  469. Stream: &stream,
  470. })
  471. if w.Code != http.StatusBadRequest {
  472. t.Fatalf("expected status 500 got %d", w.Code)
  473. }
  474. if !bytes.Equal(w.Body.Bytes(), expect) {
  475. t.Fatalf("expected error %s got %s", expect, w.Body.String())
  476. }
  477. })
  478. t.Run("copy", func(t *testing.T) {
  479. w := createRequest(t, s.CopyHandler, api.CopyRequest{
  480. Source: tt,
  481. Destination: strings.ToUpper(tt),
  482. })
  483. if w.Code != http.StatusBadRequest {
  484. t.Fatalf("expected status 500 got %d", w.Code)
  485. }
  486. if !bytes.Equal(w.Body.Bytes(), expect) {
  487. t.Fatalf("expected error %s got %s", expect, w.Body.String())
  488. }
  489. })
  490. })
  491. }
  492. }
  493. func TestShow(t *testing.T) {
  494. t.Setenv("OLLAMA_MODELS", t.TempDir())
  495. var s Server
  496. createRequest(t, s.CreateHandler, api.CreateRequest{
  497. Name: "show-model",
  498. Modelfile: fmt.Sprintf(
  499. "FROM %s\nFROM %s",
  500. createBinFile(t, llm.KV{"general.architecture": "test"}, nil),
  501. createBinFile(t, llm.KV{"general.type": "projector", "general.architecture": "clip"}, nil),
  502. ),
  503. })
  504. w := createRequest(t, s.ShowHandler, api.ShowRequest{
  505. Name: "show-model",
  506. })
  507. if w.Code != http.StatusOK {
  508. t.Fatalf("expected status code 200, actual %d", w.Code)
  509. }
  510. var resp api.ShowResponse
  511. if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
  512. t.Fatal(err)
  513. }
  514. if resp.ModelInfo["general.architecture"] != "test" {
  515. t.Fatal("Expected model architecture to be 'test', but got", resp.ModelInfo["general.architecture"])
  516. }
  517. if resp.ProjectorInfo["general.architecture"] != "clip" {
  518. t.Fatal("Expected projector architecture to be 'clip', but got", resp.ProjectorInfo["general.architecture"])
  519. }
  520. }
  521. func TestNormalize(t *testing.T) {
  522. type testCase struct {
  523. input []float32
  524. }
  525. testCases := []testCase{
  526. {input: []float32{1}},
  527. {input: []float32{0, 1, 2, 3}},
  528. {input: []float32{0.1, 0.2, 0.3}},
  529. {input: []float32{-0.1, 0.2, 0.3, -0.4}},
  530. {input: []float32{0, 0, 0}},
  531. }
  532. isNormalized := func(vec []float32) (res bool) {
  533. sum := 0.0
  534. for _, v := range vec {
  535. sum += float64(v * v)
  536. }
  537. if math.Abs(sum-1) > 1e-6 {
  538. return sum == 0
  539. } else {
  540. return true
  541. }
  542. }
  543. for _, tc := range testCases {
  544. t.Run("", func(t *testing.T) {
  545. normalized := normalize(tc.input)
  546. if !isNormalized(normalized) {
  547. t.Errorf("Vector %v is not normalized", tc.input)
  548. }
  549. })
  550. }
  551. }