routes.go 28 KB

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