routes.go 27 KB

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