routes.go 26 KB

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