routes.go 28 KB

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