routes.go 25 KB

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