routes.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  1. package server
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/fs"
  9. "log"
  10. "net"
  11. "net/http"
  12. "os"
  13. "os/signal"
  14. "path/filepath"
  15. "reflect"
  16. "runtime"
  17. "strconv"
  18. "strings"
  19. "sync"
  20. "syscall"
  21. "time"
  22. "github.com/gin-contrib/cors"
  23. "github.com/gin-gonic/gin"
  24. "github.com/jmorganca/ollama/api"
  25. "github.com/jmorganca/ollama/llm"
  26. "github.com/jmorganca/ollama/parser"
  27. "github.com/jmorganca/ollama/version"
  28. )
  29. var mode string = gin.DebugMode
  30. type Server struct {
  31. WorkDir string
  32. }
  33. func init() {
  34. switch mode {
  35. case gin.DebugMode:
  36. case gin.ReleaseMode:
  37. case gin.TestMode:
  38. default:
  39. mode = gin.DebugMode
  40. }
  41. gin.SetMode(mode)
  42. }
  43. var loaded struct {
  44. mu sync.Mutex
  45. runner llm.LLM
  46. expireAt time.Time
  47. expireTimer *time.Timer
  48. *Model
  49. *api.Options
  50. }
  51. var defaultSessionDuration = 5 * time.Minute
  52. // load a model into memory if it is not already loaded, it is up to the caller to lock loaded.mu before calling this function
  53. func load(c *gin.Context, modelName string, reqOpts map[string]interface{}, sessionDuration time.Duration) (*Model, error) {
  54. model, err := GetModel(modelName)
  55. if err != nil {
  56. return nil, err
  57. }
  58. workDir := c.GetString("workDir")
  59. opts := api.DefaultOptions()
  60. if err := opts.FromMap(model.Options); err != nil {
  61. log.Printf("could not load model options: %v", err)
  62. return nil, err
  63. }
  64. if err := opts.FromMap(reqOpts); err != nil {
  65. return nil, err
  66. }
  67. ctx := c.Request.Context()
  68. // check if the loaded model is still running in a subprocess, in case something unexpected happened
  69. if loaded.runner != nil {
  70. if err := loaded.runner.Ping(ctx); err != nil {
  71. log.Print("loaded llm process not responding, closing now")
  72. // the subprocess is no longer running, so close it
  73. loaded.runner.Close()
  74. loaded.runner = nil
  75. loaded.Model = nil
  76. loaded.Options = nil
  77. }
  78. }
  79. needLoad := loaded.runner == nil || // is there a model loaded?
  80. loaded.ModelPath != model.ModelPath || // has the base model changed?
  81. !reflect.DeepEqual(loaded.AdapterPaths, model.AdapterPaths) || // have the adapters changed?
  82. !reflect.DeepEqual(loaded.Options.Runner, opts.Runner) // have the runner options changed?
  83. if needLoad {
  84. if loaded.runner != nil {
  85. log.Println("changing loaded model")
  86. loaded.runner.Close()
  87. loaded.runner = nil
  88. loaded.Model = nil
  89. loaded.Options = nil
  90. }
  91. llmRunner, err := llm.New(workDir, model.ModelPath, model.AdapterPaths, model.ProjectorPaths, opts)
  92. if err != nil {
  93. // some older models are not compatible with newer versions of llama.cpp
  94. // show a generalized compatibility error until there is a better way to
  95. // check for model compatibility
  96. if errors.Is(llm.ErrUnsupportedFormat, err) || strings.Contains(err.Error(), "failed to load model") {
  97. err = fmt.Errorf("%v: this model may be incompatible with your version of Ollama. If you previously pulled this model, try updating it by running `ollama pull %s`", err, model.ShortName)
  98. }
  99. return nil, err
  100. }
  101. loaded.Model = model
  102. loaded.runner = llmRunner
  103. loaded.Options = &opts
  104. }
  105. loaded.expireAt = time.Now().Add(sessionDuration)
  106. if loaded.expireTimer == nil {
  107. loaded.expireTimer = time.AfterFunc(sessionDuration, func() {
  108. loaded.mu.Lock()
  109. defer loaded.mu.Unlock()
  110. if time.Now().Before(loaded.expireAt) {
  111. return
  112. }
  113. if loaded.runner != nil {
  114. loaded.runner.Close()
  115. }
  116. loaded.runner = nil
  117. loaded.Model = nil
  118. loaded.Options = nil
  119. })
  120. }
  121. loaded.expireTimer.Reset(sessionDuration)
  122. return model, nil
  123. }
  124. func GenerateHandler(c *gin.Context) {
  125. loaded.mu.Lock()
  126. defer loaded.mu.Unlock()
  127. checkpointStart := time.Now()
  128. var req api.GenerateRequest
  129. err := c.ShouldBindJSON(&req)
  130. switch {
  131. case errors.Is(err, io.EOF):
  132. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  133. return
  134. case err != nil:
  135. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  136. return
  137. }
  138. // validate the request
  139. switch {
  140. case req.Model == "":
  141. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  142. return
  143. case len(req.Format) > 0 && req.Format != "json":
  144. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "format must be json"})
  145. return
  146. case req.Raw && (req.Template != "" || req.System != "" || len(req.Context) > 0):
  147. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "raw mode does not support template, system, or context"})
  148. return
  149. }
  150. sessionDuration := defaultSessionDuration
  151. model, err := load(c, req.Model, req.Options, sessionDuration)
  152. if err != nil {
  153. var pErr *fs.PathError
  154. switch {
  155. case errors.As(err, &pErr):
  156. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
  157. case errors.Is(err, api.ErrInvalidOpts):
  158. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  159. default:
  160. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  161. }
  162. return
  163. }
  164. // an empty request loads the model
  165. if req.Prompt == "" && req.Template == "" && req.System == "" {
  166. c.JSON(http.StatusOK, api.GenerateResponse{
  167. CreatedAt: time.Now().UTC(),
  168. Model: req.Model,
  169. Done: true})
  170. return
  171. }
  172. checkpointLoaded := time.Now()
  173. var prompt string
  174. switch {
  175. case req.Raw:
  176. prompt = req.Prompt
  177. case req.Prompt != "":
  178. if req.Template != "" {
  179. // override the default model template
  180. model.Template = req.Template
  181. }
  182. var rebuild strings.Builder
  183. if req.Context != nil {
  184. // TODO: context is deprecated, at some point the context logic within this conditional should be removed
  185. prevCtx, err := loaded.runner.Decode(c.Request.Context(), req.Context)
  186. if err != nil {
  187. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  188. return
  189. }
  190. // Remove leading spaces from prevCtx if present
  191. prevCtx = strings.TrimPrefix(prevCtx, " ")
  192. rebuild.WriteString(prevCtx)
  193. }
  194. p, err := model.Prompt(PromptVars{
  195. System: req.System,
  196. Prompt: req.Prompt,
  197. First: len(req.Context) == 0,
  198. })
  199. if err != nil {
  200. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  201. return
  202. }
  203. rebuild.WriteString(p)
  204. prompt = rebuild.String()
  205. }
  206. ch := make(chan any)
  207. var generated strings.Builder
  208. go func() {
  209. defer close(ch)
  210. fn := func(r llm.PredictResult) {
  211. // Update model expiration
  212. loaded.expireAt = time.Now().Add(sessionDuration)
  213. loaded.expireTimer.Reset(sessionDuration)
  214. // Build up the full response
  215. if _, err := generated.WriteString(r.Content); err != nil {
  216. ch <- gin.H{"error": err.Error()}
  217. return
  218. }
  219. resp := api.GenerateResponse{
  220. Model: req.Model,
  221. CreatedAt: time.Now().UTC(),
  222. Done: r.Done,
  223. Response: r.Content,
  224. Metrics: api.Metrics{
  225. PromptEvalCount: r.PromptEvalCount,
  226. PromptEvalDuration: r.PromptEvalDuration,
  227. EvalCount: r.EvalCount,
  228. EvalDuration: r.EvalDuration,
  229. },
  230. }
  231. if r.Done {
  232. resp.TotalDuration = time.Since(checkpointStart)
  233. resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)
  234. if !req.Raw {
  235. embd, err := loaded.runner.Encode(c.Request.Context(), prompt+generated.String())
  236. if err != nil {
  237. ch <- gin.H{"error": err.Error()}
  238. return
  239. }
  240. resp.Context = embd
  241. }
  242. }
  243. ch <- resp
  244. }
  245. // Start prediction
  246. predictReq := llm.PredictOpts{
  247. Prompt: prompt,
  248. Format: req.Format,
  249. Images: req.Images,
  250. }
  251. if err := loaded.runner.Predict(c.Request.Context(), predictReq, fn); err != nil {
  252. ch <- gin.H{"error": err.Error()}
  253. }
  254. }()
  255. if req.Stream != nil && !*req.Stream {
  256. // Accumulate responses into the final response
  257. var final api.GenerateResponse
  258. var sb strings.Builder
  259. for resp := range ch {
  260. switch r := resp.(type) {
  261. case api.GenerateResponse:
  262. sb.WriteString(r.Response)
  263. final = r
  264. case gin.H:
  265. if errorMsg, ok := r["error"].(string); ok {
  266. c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
  267. return
  268. } else {
  269. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in response"})
  270. return
  271. }
  272. default:
  273. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error"})
  274. return
  275. }
  276. }
  277. final.Response = sb.String()
  278. c.JSON(http.StatusOK, final)
  279. return
  280. }
  281. streamResponse(c, ch)
  282. }
  283. func EmbeddingHandler(c *gin.Context) {
  284. loaded.mu.Lock()
  285. defer loaded.mu.Unlock()
  286. var req api.EmbeddingRequest
  287. err := c.ShouldBindJSON(&req)
  288. switch {
  289. case errors.Is(err, io.EOF):
  290. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  291. return
  292. case err != nil:
  293. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  294. return
  295. }
  296. if req.Model == "" {
  297. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  298. return
  299. }
  300. sessionDuration := defaultSessionDuration
  301. _, err = load(c, req.Model, req.Options, sessionDuration)
  302. if err != nil {
  303. var pErr *fs.PathError
  304. switch {
  305. case errors.As(err, &pErr):
  306. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
  307. case errors.Is(err, api.ErrInvalidOpts):
  308. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  309. default:
  310. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  311. }
  312. return
  313. }
  314. if !loaded.Options.EmbeddingOnly {
  315. c.JSON(http.StatusBadRequest, gin.H{"error": "embedding option must be set to true"})
  316. return
  317. }
  318. embedding, err := loaded.runner.Embedding(c.Request.Context(), req.Prompt)
  319. if err != nil {
  320. log.Printf("embedding generation failed: %v", err)
  321. c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate embedding"})
  322. return
  323. }
  324. resp := api.EmbeddingResponse{
  325. Embedding: embedding,
  326. }
  327. c.JSON(http.StatusOK, resp)
  328. }
  329. func PullModelHandler(c *gin.Context) {
  330. var req api.PullRequest
  331. err := c.ShouldBindJSON(&req)
  332. switch {
  333. case errors.Is(err, io.EOF):
  334. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  335. return
  336. case err != nil:
  337. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  338. return
  339. }
  340. if req.Name == "" {
  341. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  342. return
  343. }
  344. ch := make(chan any)
  345. go func() {
  346. defer close(ch)
  347. fn := func(r api.ProgressResponse) {
  348. ch <- r
  349. }
  350. regOpts := &RegistryOptions{
  351. Insecure: req.Insecure,
  352. }
  353. ctx, cancel := context.WithCancel(c.Request.Context())
  354. defer cancel()
  355. if err := PullModel(ctx, req.Name, regOpts, fn); err != nil {
  356. ch <- gin.H{"error": err.Error()}
  357. }
  358. }()
  359. if req.Stream != nil && !*req.Stream {
  360. waitForStream(c, ch)
  361. return
  362. }
  363. streamResponse(c, ch)
  364. }
  365. func PushModelHandler(c *gin.Context) {
  366. var req api.PushRequest
  367. err := c.ShouldBindJSON(&req)
  368. switch {
  369. case errors.Is(err, io.EOF):
  370. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  371. return
  372. case err != nil:
  373. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  374. return
  375. }
  376. if req.Name == "" {
  377. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  378. return
  379. }
  380. ch := make(chan any)
  381. go func() {
  382. defer close(ch)
  383. fn := func(r api.ProgressResponse) {
  384. ch <- r
  385. }
  386. regOpts := &RegistryOptions{
  387. Insecure: req.Insecure,
  388. }
  389. ctx, cancel := context.WithCancel(c.Request.Context())
  390. defer cancel()
  391. if err := PushModel(ctx, req.Name, regOpts, fn); err != nil {
  392. ch <- gin.H{"error": err.Error()}
  393. }
  394. }()
  395. if req.Stream != nil && !*req.Stream {
  396. waitForStream(c, ch)
  397. return
  398. }
  399. streamResponse(c, ch)
  400. }
  401. func CreateModelHandler(c *gin.Context) {
  402. var req api.CreateRequest
  403. err := c.ShouldBindJSON(&req)
  404. switch {
  405. case errors.Is(err, io.EOF):
  406. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  407. return
  408. case err != nil:
  409. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  410. return
  411. }
  412. if req.Name == "" {
  413. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  414. return
  415. }
  416. if err := ParseModelPath(req.Name).Validate(); err != nil {
  417. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  418. return
  419. }
  420. if req.Path == "" && req.Modelfile == "" {
  421. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "path or modelfile are required"})
  422. return
  423. }
  424. var modelfile io.Reader = strings.NewReader(req.Modelfile)
  425. if req.Path != "" && req.Modelfile == "" {
  426. mf, err := os.Open(req.Path)
  427. if err != nil {
  428. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error reading modelfile: %s", err)})
  429. return
  430. }
  431. defer mf.Close()
  432. modelfile = mf
  433. }
  434. commands, err := parser.Parse(modelfile)
  435. if err != nil {
  436. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  437. return
  438. }
  439. ch := make(chan any)
  440. go func() {
  441. defer close(ch)
  442. fn := func(resp api.ProgressResponse) {
  443. ch <- resp
  444. }
  445. ctx, cancel := context.WithCancel(c.Request.Context())
  446. defer cancel()
  447. if err := CreateModel(ctx, req.Name, filepath.Dir(req.Path), commands, fn); err != nil {
  448. ch <- gin.H{"error": err.Error()}
  449. }
  450. }()
  451. if req.Stream != nil && !*req.Stream {
  452. waitForStream(c, ch)
  453. return
  454. }
  455. streamResponse(c, ch)
  456. }
  457. func DeleteModelHandler(c *gin.Context) {
  458. var req api.DeleteRequest
  459. err := c.ShouldBindJSON(&req)
  460. switch {
  461. case errors.Is(err, io.EOF):
  462. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  463. return
  464. case err != nil:
  465. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  466. return
  467. }
  468. if req.Name == "" {
  469. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  470. return
  471. }
  472. if err := DeleteModel(req.Name); err != nil {
  473. if os.IsNotExist(err) {
  474. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  475. } else {
  476. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  477. }
  478. return
  479. }
  480. manifestsPath, err := GetManifestPath()
  481. if err != nil {
  482. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  483. return
  484. }
  485. if err := PruneDirectory(manifestsPath); err != nil {
  486. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  487. return
  488. }
  489. c.JSON(http.StatusOK, nil)
  490. }
  491. func ShowModelHandler(c *gin.Context) {
  492. var req api.ShowRequest
  493. err := c.ShouldBindJSON(&req)
  494. switch {
  495. case errors.Is(err, io.EOF):
  496. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  497. return
  498. case err != nil:
  499. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  500. return
  501. }
  502. if req.Name == "" {
  503. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  504. return
  505. }
  506. resp, err := GetModelInfo(req.Name)
  507. if err != nil {
  508. if os.IsNotExist(err) {
  509. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  510. } else {
  511. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  512. }
  513. return
  514. }
  515. c.JSON(http.StatusOK, resp)
  516. }
  517. func GetModelInfo(name string) (*api.ShowResponse, error) {
  518. model, err := GetModel(name)
  519. if err != nil {
  520. return nil, err
  521. }
  522. modelDetails := api.ModelDetails{
  523. Format: model.Config.ModelFormat,
  524. Family: model.Config.ModelFamily,
  525. Families: model.Config.ModelFamilies,
  526. ParameterSize: model.Config.ModelType,
  527. QuantizationLevel: model.Config.FileType,
  528. }
  529. resp := &api.ShowResponse{
  530. License: strings.Join(model.License, "\n"),
  531. System: model.System,
  532. Template: model.Template,
  533. Details: modelDetails,
  534. }
  535. mf, err := ShowModelfile(model)
  536. if err != nil {
  537. return nil, err
  538. }
  539. resp.Modelfile = mf
  540. var params []string
  541. cs := 30
  542. for k, v := range model.Options {
  543. switch val := v.(type) {
  544. case string:
  545. params = append(params, fmt.Sprintf("%-*s %s", cs, k, val))
  546. case int:
  547. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.Itoa(val)))
  548. case float64:
  549. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatFloat(val, 'f', 0, 64)))
  550. case bool:
  551. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatBool(val)))
  552. case []interface{}:
  553. for _, nv := range val {
  554. switch nval := nv.(type) {
  555. case string:
  556. params = append(params, fmt.Sprintf("%-*s %s", cs, k, nval))
  557. case int:
  558. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.Itoa(nval)))
  559. case float64:
  560. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatFloat(nval, 'f', 0, 64)))
  561. case bool:
  562. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatBool(nval)))
  563. }
  564. }
  565. }
  566. }
  567. resp.Parameters = strings.Join(params, "\n")
  568. return resp, nil
  569. }
  570. func ListModelsHandler(c *gin.Context) {
  571. models := make([]api.ModelResponse, 0)
  572. fp, err := GetManifestPath()
  573. if err != nil {
  574. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  575. return
  576. }
  577. modelResponse := func(modelName string) (api.ModelResponse, error) {
  578. model, err := GetModel(modelName)
  579. if err != nil {
  580. return api.ModelResponse{}, err
  581. }
  582. modelDetails := api.ModelDetails{
  583. Format: model.Config.ModelFormat,
  584. Family: model.Config.ModelFamily,
  585. Families: model.Config.ModelFamilies,
  586. ParameterSize: model.Config.ModelType,
  587. QuantizationLevel: model.Config.FileType,
  588. }
  589. return api.ModelResponse{
  590. Name: model.ShortName,
  591. Size: model.Size,
  592. Digest: model.Digest,
  593. Details: modelDetails,
  594. }, nil
  595. }
  596. walkFunc := func(path string, info os.FileInfo, _ error) error {
  597. if !info.IsDir() {
  598. dir, file := filepath.Split(path)
  599. dir = strings.Trim(strings.TrimPrefix(dir, fp), string(os.PathSeparator))
  600. tag := strings.Join([]string{dir, file}, ":")
  601. resp, err := modelResponse(tag)
  602. if err != nil {
  603. log.Printf("skipping file: %s", fp)
  604. return nil
  605. }
  606. resp.ModifiedAt = info.ModTime()
  607. models = append(models, resp)
  608. }
  609. return nil
  610. }
  611. if err := filepath.Walk(fp, walkFunc); err != nil {
  612. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  613. return
  614. }
  615. c.JSON(http.StatusOK, api.ListResponse{Models: models})
  616. }
  617. func CopyModelHandler(c *gin.Context) {
  618. var req api.CopyRequest
  619. err := c.ShouldBindJSON(&req)
  620. switch {
  621. case errors.Is(err, io.EOF):
  622. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  623. return
  624. case err != nil:
  625. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  626. return
  627. }
  628. if req.Source == "" || req.Destination == "" {
  629. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "source add destination are required"})
  630. return
  631. }
  632. if err := ParseModelPath(req.Destination).Validate(); err != nil {
  633. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  634. return
  635. }
  636. if err := CopyModel(req.Source, req.Destination); err != nil {
  637. if os.IsNotExist(err) {
  638. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Source)})
  639. } else {
  640. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  641. }
  642. return
  643. }
  644. }
  645. func HeadBlobHandler(c *gin.Context) {
  646. path, err := GetBlobsPath(c.Param("digest"))
  647. if err != nil {
  648. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  649. return
  650. }
  651. if _, err := os.Stat(path); err != nil {
  652. c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("blob %q not found", c.Param("digest"))})
  653. return
  654. }
  655. c.Status(http.StatusOK)
  656. }
  657. func CreateBlobHandler(c *gin.Context) {
  658. layer, err := NewLayer(c.Request.Body, "")
  659. if err != nil {
  660. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  661. return
  662. }
  663. if layer.Digest != c.Param("digest") {
  664. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("digest mismatch, expected %q, got %q", c.Param("digest"), layer.Digest)})
  665. return
  666. }
  667. if _, err := layer.Commit(); err != nil {
  668. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  669. return
  670. }
  671. c.Status(http.StatusCreated)
  672. }
  673. var defaultAllowOrigins = []string{
  674. "localhost",
  675. "127.0.0.1",
  676. "0.0.0.0",
  677. }
  678. func NewServer() (*Server, error) {
  679. workDir, err := os.MkdirTemp("", "ollama")
  680. if err != nil {
  681. return nil, err
  682. }
  683. return &Server{
  684. WorkDir: workDir,
  685. }, nil
  686. }
  687. func (s *Server) GenerateRoutes() http.Handler {
  688. var origins []string
  689. if o := os.Getenv("OLLAMA_ORIGINS"); o != "" {
  690. origins = strings.Split(o, ",")
  691. }
  692. config := cors.DefaultConfig()
  693. config.AllowWildcard = true
  694. config.AllowOrigins = origins
  695. for _, allowOrigin := range defaultAllowOrigins {
  696. config.AllowOrigins = append(config.AllowOrigins,
  697. fmt.Sprintf("http://%s", allowOrigin),
  698. fmt.Sprintf("https://%s", allowOrigin),
  699. fmt.Sprintf("http://%s:*", allowOrigin),
  700. fmt.Sprintf("https://%s:*", allowOrigin),
  701. )
  702. }
  703. r := gin.Default()
  704. r.Use(
  705. cors.New(config),
  706. func(c *gin.Context) {
  707. c.Set("workDir", s.WorkDir)
  708. c.Next()
  709. },
  710. )
  711. r.POST("/api/pull", PullModelHandler)
  712. r.POST("/api/generate", GenerateHandler)
  713. r.POST("/api/chat", ChatHandler)
  714. r.POST("/api/embeddings", EmbeddingHandler)
  715. r.POST("/api/create", CreateModelHandler)
  716. r.POST("/api/push", PushModelHandler)
  717. r.POST("/api/copy", CopyModelHandler)
  718. r.DELETE("/api/delete", DeleteModelHandler)
  719. r.POST("/api/show", ShowModelHandler)
  720. r.POST("/api/blobs/:digest", CreateBlobHandler)
  721. r.HEAD("/api/blobs/:digest", HeadBlobHandler)
  722. for _, method := range []string{http.MethodGet, http.MethodHead} {
  723. r.Handle(method, "/", func(c *gin.Context) {
  724. c.String(http.StatusOK, "Ollama is running")
  725. })
  726. r.Handle(method, "/api/tags", ListModelsHandler)
  727. r.Handle(method, "/api/version", func(c *gin.Context) {
  728. c.JSON(http.StatusOK, gin.H{"version": version.Version})
  729. })
  730. }
  731. return r
  732. }
  733. func Serve(ln net.Listener) error {
  734. if noprune := os.Getenv("OLLAMA_NOPRUNE"); noprune == "" {
  735. // clean up unused layers and manifests
  736. if err := PruneLayers(); err != nil {
  737. return err
  738. }
  739. manifestsPath, err := GetManifestPath()
  740. if err != nil {
  741. return err
  742. }
  743. if err := PruneDirectory(manifestsPath); err != nil {
  744. return err
  745. }
  746. }
  747. s, err := NewServer()
  748. if err != nil {
  749. return err
  750. }
  751. r := s.GenerateRoutes()
  752. log.Printf("Listening on %s (version %s)", ln.Addr(), version.Version)
  753. srvr := &http.Server{
  754. Handler: r,
  755. }
  756. // listen for a ctrl+c and stop any loaded llm
  757. signals := make(chan os.Signal, 1)
  758. signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
  759. go func() {
  760. <-signals
  761. if loaded.runner != nil {
  762. loaded.runner.Close()
  763. }
  764. os.RemoveAll(s.WorkDir)
  765. os.Exit(0)
  766. }()
  767. if runtime.GOOS == "linux" {
  768. // check compatibility to log warnings
  769. if _, err := llm.CheckVRAM(); err != nil {
  770. log.Print(err.Error())
  771. }
  772. }
  773. return srvr.Serve(ln)
  774. }
  775. func waitForStream(c *gin.Context, ch chan interface{}) {
  776. c.Header("Content-Type", "application/json")
  777. for resp := range ch {
  778. switch r := resp.(type) {
  779. case api.ProgressResponse:
  780. if r.Status == "success" {
  781. c.JSON(http.StatusOK, r)
  782. return
  783. }
  784. case gin.H:
  785. if errorMsg, ok := r["error"].(string); ok {
  786. c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
  787. return
  788. } else {
  789. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in progress response"})
  790. return
  791. }
  792. default:
  793. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected progress response"})
  794. return
  795. }
  796. }
  797. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected end of progress response"})
  798. }
  799. func streamResponse(c *gin.Context, ch chan any) {
  800. c.Header("Content-Type", "application/x-ndjson")
  801. c.Stream(func(w io.Writer) bool {
  802. val, ok := <-ch
  803. if !ok {
  804. return false
  805. }
  806. bts, err := json.Marshal(val)
  807. if err != nil {
  808. log.Printf("streamResponse: json.Marshal failed with %s", err)
  809. return false
  810. }
  811. // Delineate chunks with new-line delimiter
  812. bts = append(bts, '\n')
  813. if _, err := w.Write(bts); err != nil {
  814. log.Printf("streamResponse: w.Write failed with %s", err)
  815. return false
  816. }
  817. return true
  818. })
  819. }
  820. func ChatHandler(c *gin.Context) {
  821. loaded.mu.Lock()
  822. defer loaded.mu.Unlock()
  823. checkpointStart := time.Now()
  824. var req api.ChatRequest
  825. err := c.ShouldBindJSON(&req)
  826. switch {
  827. case errors.Is(err, io.EOF):
  828. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  829. return
  830. case err != nil:
  831. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  832. return
  833. }
  834. // validate the request
  835. switch {
  836. case req.Model == "":
  837. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  838. return
  839. case len(req.Format) > 0 && req.Format != "json":
  840. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "format must be json"})
  841. return
  842. }
  843. sessionDuration := defaultSessionDuration
  844. model, err := load(c, req.Model, req.Options, sessionDuration)
  845. if err != nil {
  846. var pErr *fs.PathError
  847. switch {
  848. case errors.As(err, &pErr):
  849. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
  850. case errors.Is(err, api.ErrInvalidOpts):
  851. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  852. default:
  853. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  854. }
  855. return
  856. }
  857. // an empty request loads the model
  858. if len(req.Messages) == 0 {
  859. c.JSON(http.StatusOK, api.ChatResponse{CreatedAt: time.Now().UTC(), Model: req.Model, Done: true, Message: api.Message{Role: "assistant"}})
  860. return
  861. }
  862. checkpointLoaded := time.Now()
  863. prompt, images, err := model.ChatPrompt(req.Messages)
  864. if err != nil {
  865. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  866. return
  867. }
  868. ch := make(chan any)
  869. go func() {
  870. defer close(ch)
  871. fn := func(r llm.PredictResult) {
  872. // Update model expiration
  873. loaded.expireAt = time.Now().Add(sessionDuration)
  874. loaded.expireTimer.Reset(sessionDuration)
  875. resp := api.ChatResponse{
  876. Model: req.Model,
  877. CreatedAt: time.Now().UTC(),
  878. Message: api.Message{Role: "assistant", Content: r.Content},
  879. Done: r.Done,
  880. Metrics: api.Metrics{
  881. PromptEvalCount: r.PromptEvalCount,
  882. PromptEvalDuration: r.PromptEvalDuration,
  883. EvalCount: r.EvalCount,
  884. EvalDuration: r.EvalDuration,
  885. },
  886. }
  887. if r.Done {
  888. resp.TotalDuration = time.Since(checkpointStart)
  889. resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)
  890. }
  891. ch <- resp
  892. }
  893. // Start prediction
  894. predictReq := llm.PredictOpts{
  895. Prompt: prompt,
  896. Format: req.Format,
  897. Images: images,
  898. }
  899. if err := loaded.runner.Predict(c.Request.Context(), predictReq, fn); err != nil {
  900. ch <- gin.H{"error": err.Error()}
  901. }
  902. }()
  903. if req.Stream != nil && !*req.Stream {
  904. // Accumulate responses into the final response
  905. var final api.ChatResponse
  906. var sb strings.Builder
  907. for resp := range ch {
  908. switch r := resp.(type) {
  909. case api.ChatResponse:
  910. sb.WriteString(r.Message.Content)
  911. final = r
  912. case gin.H:
  913. if errorMsg, ok := r["error"].(string); ok {
  914. c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
  915. return
  916. } else {
  917. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in response"})
  918. return
  919. }
  920. default:
  921. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error"})
  922. return
  923. }
  924. }
  925. final.Message = api.Message{Role: "assistant", Content: sb.String()}
  926. c.JSON(http.StatusOK, final)
  927. return
  928. }
  929. streamResponse(c, ch)
  930. }