routes.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128
  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/gpu"
  26. "github.com/jmorganca/ollama/llm"
  27. "github.com/jmorganca/ollama/parser"
  28. "github.com/jmorganca/ollama/version"
  29. )
  30. var mode string = gin.DebugMode
  31. type Server struct {
  32. WorkDir string
  33. }
  34. func init() {
  35. switch mode {
  36. case gin.DebugMode:
  37. case gin.ReleaseMode:
  38. case gin.TestMode:
  39. default:
  40. mode = gin.DebugMode
  41. }
  42. gin.SetMode(mode)
  43. }
  44. var loaded struct {
  45. mu sync.Mutex
  46. runner llm.LLM
  47. expireAt time.Time
  48. expireTimer *time.Timer
  49. *Model
  50. *api.Options
  51. }
  52. var defaultSessionDuration = 5 * time.Minute
  53. // 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
  54. func load(c *gin.Context, model *Model, opts api.Options, sessionDuration time.Duration) error {
  55. workDir := c.GetString("workDir")
  56. needLoad := loaded.runner == nil || // is there a model loaded?
  57. loaded.ModelPath != model.ModelPath || // has the base model changed?
  58. !reflect.DeepEqual(loaded.AdapterPaths, model.AdapterPaths) || // have the adapters changed?
  59. !reflect.DeepEqual(loaded.Options.Runner, opts.Runner) // have the runner options changed?
  60. if needLoad {
  61. if loaded.runner != nil {
  62. log.Println("changing loaded model")
  63. loaded.runner.Close()
  64. loaded.runner = nil
  65. loaded.Model = nil
  66. loaded.Options = nil
  67. }
  68. llmRunner, err := llm.New(workDir, model.ModelPath, model.AdapterPaths, model.ProjectorPaths, opts)
  69. if err != nil {
  70. // some older models are not compatible with newer versions of llama.cpp
  71. // show a generalized compatibility error until there is a better way to
  72. // check for model compatibility
  73. if errors.Is(llm.ErrUnsupportedFormat, err) || strings.Contains(err.Error(), "failed to load model") {
  74. 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)
  75. }
  76. return err
  77. }
  78. loaded.Model = model
  79. loaded.runner = llmRunner
  80. loaded.Options = &opts
  81. }
  82. loaded.expireAt = time.Now().Add(sessionDuration)
  83. if loaded.expireTimer == nil {
  84. loaded.expireTimer = time.AfterFunc(sessionDuration, func() {
  85. loaded.mu.Lock()
  86. defer loaded.mu.Unlock()
  87. if time.Now().Before(loaded.expireAt) {
  88. return
  89. }
  90. if loaded.runner != nil {
  91. loaded.runner.Close()
  92. }
  93. loaded.runner = nil
  94. loaded.Model = nil
  95. loaded.Options = nil
  96. })
  97. }
  98. loaded.expireTimer.Reset(sessionDuration)
  99. return nil
  100. }
  101. func modelOptions(model *Model, requestOpts map[string]interface{}) (api.Options, error) {
  102. opts := api.DefaultOptions()
  103. if err := opts.FromMap(model.Options); err != nil {
  104. return api.Options{}, err
  105. }
  106. if err := opts.FromMap(requestOpts); err != nil {
  107. return api.Options{}, err
  108. }
  109. return opts, nil
  110. }
  111. func GenerateHandler(c *gin.Context) {
  112. loaded.mu.Lock()
  113. defer loaded.mu.Unlock()
  114. checkpointStart := time.Now()
  115. var req api.GenerateRequest
  116. err := c.ShouldBindJSON(&req)
  117. switch {
  118. case errors.Is(err, io.EOF):
  119. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  120. return
  121. case err != nil:
  122. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  123. return
  124. }
  125. // validate the request
  126. switch {
  127. case req.Model == "":
  128. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  129. return
  130. case len(req.Format) > 0 && req.Format != "json":
  131. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "format must be json"})
  132. return
  133. case req.Raw && (req.Template != "" || req.System != "" || len(req.Context) > 0):
  134. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "raw mode does not support template, system, or context"})
  135. return
  136. }
  137. model, err := GetModel(req.Model)
  138. if err != nil {
  139. var pErr *fs.PathError
  140. if errors.As(err, &pErr) {
  141. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
  142. return
  143. }
  144. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  145. return
  146. }
  147. opts, err := modelOptions(model, req.Options)
  148. if err != nil {
  149. if errors.Is(err, api.ErrInvalidOpts) {
  150. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  151. return
  152. }
  153. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  154. return
  155. }
  156. sessionDuration := defaultSessionDuration
  157. if err := load(c, model, opts, sessionDuration); err != nil {
  158. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  159. return
  160. }
  161. // an empty request loads the model
  162. if req.Prompt == "" && req.Template == "" && req.System == "" {
  163. c.JSON(http.StatusOK, api.GenerateResponse{
  164. CreatedAt: time.Now().UTC(),
  165. Model: req.Model,
  166. Done: true})
  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. log.Printf("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. if req.Name == "" {
  520. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "name is required"})
  521. return
  522. }
  523. resp, err := GetModelInfo(req.Name)
  524. if err != nil {
  525. if os.IsNotExist(err) {
  526. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  527. } else {
  528. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  529. }
  530. return
  531. }
  532. c.JSON(http.StatusOK, resp)
  533. }
  534. func GetModelInfo(name string) (*api.ShowResponse, error) {
  535. model, err := GetModel(name)
  536. if err != nil {
  537. return nil, err
  538. }
  539. modelDetails := api.ModelDetails{
  540. Format: model.Config.ModelFormat,
  541. Family: model.Config.ModelFamily,
  542. Families: model.Config.ModelFamilies,
  543. ParameterSize: model.Config.ModelType,
  544. QuantizationLevel: model.Config.FileType,
  545. }
  546. resp := &api.ShowResponse{
  547. License: strings.Join(model.License, "\n"),
  548. System: model.System,
  549. Template: model.Template,
  550. Details: modelDetails,
  551. }
  552. mf, err := ShowModelfile(model)
  553. if err != nil {
  554. return nil, err
  555. }
  556. resp.Modelfile = mf
  557. var params []string
  558. cs := 30
  559. for k, v := range model.Options {
  560. switch val := v.(type) {
  561. case string:
  562. params = append(params, fmt.Sprintf("%-*s %s", cs, k, val))
  563. case int:
  564. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.Itoa(val)))
  565. case float64:
  566. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatFloat(val, 'f', 0, 64)))
  567. case bool:
  568. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatBool(val)))
  569. case []interface{}:
  570. for _, nv := range val {
  571. switch nval := nv.(type) {
  572. case string:
  573. params = append(params, fmt.Sprintf("%-*s %s", cs, k, nval))
  574. case int:
  575. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.Itoa(nval)))
  576. case float64:
  577. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatFloat(nval, 'f', 0, 64)))
  578. case bool:
  579. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatBool(nval)))
  580. }
  581. }
  582. }
  583. }
  584. resp.Parameters = strings.Join(params, "\n")
  585. return resp, nil
  586. }
  587. func ListModelsHandler(c *gin.Context) {
  588. models := make([]api.ModelResponse, 0)
  589. fp, err := GetManifestPath()
  590. if err != nil {
  591. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  592. return
  593. }
  594. modelResponse := func(modelName string) (api.ModelResponse, error) {
  595. model, err := GetModel(modelName)
  596. if err != nil {
  597. return api.ModelResponse{}, err
  598. }
  599. modelDetails := api.ModelDetails{
  600. Format: model.Config.ModelFormat,
  601. Family: model.Config.ModelFamily,
  602. Families: model.Config.ModelFamilies,
  603. ParameterSize: model.Config.ModelType,
  604. QuantizationLevel: model.Config.FileType,
  605. }
  606. return api.ModelResponse{
  607. Name: model.ShortName,
  608. Size: model.Size,
  609. Digest: model.Digest,
  610. Details: modelDetails,
  611. }, nil
  612. }
  613. walkFunc := func(path string, info os.FileInfo, _ error) error {
  614. if !info.IsDir() {
  615. dir, file := filepath.Split(path)
  616. dir = strings.Trim(strings.TrimPrefix(dir, fp), string(os.PathSeparator))
  617. tag := strings.Join([]string{dir, file}, ":")
  618. resp, err := modelResponse(tag)
  619. if err != nil {
  620. log.Printf("skipping file: %s", fp)
  621. return nil
  622. }
  623. resp.ModifiedAt = info.ModTime()
  624. models = append(models, resp)
  625. }
  626. return nil
  627. }
  628. if err := filepath.Walk(fp, walkFunc); err != nil {
  629. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  630. return
  631. }
  632. c.JSON(http.StatusOK, api.ListResponse{Models: models})
  633. }
  634. func CopyModelHandler(c *gin.Context) {
  635. var req api.CopyRequest
  636. err := c.ShouldBindJSON(&req)
  637. switch {
  638. case errors.Is(err, io.EOF):
  639. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  640. return
  641. case err != nil:
  642. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  643. return
  644. }
  645. if req.Source == "" || req.Destination == "" {
  646. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "source add destination are required"})
  647. return
  648. }
  649. if err := ParseModelPath(req.Destination).Validate(); err != nil {
  650. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  651. return
  652. }
  653. if err := CopyModel(req.Source, req.Destination); err != nil {
  654. if os.IsNotExist(err) {
  655. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Source)})
  656. } else {
  657. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  658. }
  659. return
  660. }
  661. }
  662. func HeadBlobHandler(c *gin.Context) {
  663. path, err := GetBlobsPath(c.Param("digest"))
  664. if err != nil {
  665. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  666. return
  667. }
  668. if _, err := os.Stat(path); err != nil {
  669. c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("blob %q not found", c.Param("digest"))})
  670. return
  671. }
  672. c.Status(http.StatusOK)
  673. }
  674. func CreateBlobHandler(c *gin.Context) {
  675. layer, err := NewLayer(c.Request.Body, "")
  676. if err != nil {
  677. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  678. return
  679. }
  680. if layer.Digest != c.Param("digest") {
  681. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("digest mismatch, expected %q, got %q", c.Param("digest"), layer.Digest)})
  682. return
  683. }
  684. if _, err := layer.Commit(); err != nil {
  685. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  686. return
  687. }
  688. c.Status(http.StatusCreated)
  689. }
  690. var defaultAllowOrigins = []string{
  691. "localhost",
  692. "127.0.0.1",
  693. "0.0.0.0",
  694. }
  695. func NewServer() (*Server, error) {
  696. workDir, err := os.MkdirTemp("", "ollama")
  697. if err != nil {
  698. return nil, err
  699. }
  700. return &Server{
  701. WorkDir: workDir,
  702. }, nil
  703. }
  704. func (s *Server) GenerateRoutes() http.Handler {
  705. var origins []string
  706. if o := os.Getenv("OLLAMA_ORIGINS"); o != "" {
  707. origins = strings.Split(o, ",")
  708. }
  709. config := cors.DefaultConfig()
  710. config.AllowWildcard = true
  711. config.AllowOrigins = origins
  712. for _, allowOrigin := range defaultAllowOrigins {
  713. config.AllowOrigins = append(config.AllowOrigins,
  714. fmt.Sprintf("http://%s", allowOrigin),
  715. fmt.Sprintf("https://%s", allowOrigin),
  716. fmt.Sprintf("http://%s:*", allowOrigin),
  717. fmt.Sprintf("https://%s:*", allowOrigin),
  718. )
  719. }
  720. r := gin.Default()
  721. r.Use(
  722. cors.New(config),
  723. func(c *gin.Context) {
  724. c.Set("workDir", s.WorkDir)
  725. c.Next()
  726. },
  727. )
  728. r.POST("/api/pull", PullModelHandler)
  729. r.POST("/api/generate", GenerateHandler)
  730. r.POST("/api/chat", ChatHandler)
  731. r.POST("/api/embeddings", EmbeddingHandler)
  732. r.POST("/api/create", CreateModelHandler)
  733. r.POST("/api/push", PushModelHandler)
  734. r.POST("/api/copy", CopyModelHandler)
  735. r.DELETE("/api/delete", DeleteModelHandler)
  736. r.POST("/api/show", ShowModelHandler)
  737. r.POST("/api/blobs/:digest", CreateBlobHandler)
  738. r.HEAD("/api/blobs/:digest", HeadBlobHandler)
  739. for _, method := range []string{http.MethodGet, http.MethodHead} {
  740. r.Handle(method, "/", func(c *gin.Context) {
  741. c.String(http.StatusOK, "Ollama is running")
  742. })
  743. r.Handle(method, "/api/tags", ListModelsHandler)
  744. r.Handle(method, "/api/version", func(c *gin.Context) {
  745. c.JSON(http.StatusOK, gin.H{"version": version.Version})
  746. })
  747. }
  748. return r
  749. }
  750. func Serve(ln net.Listener) error {
  751. if noprune := os.Getenv("OLLAMA_NOPRUNE"); noprune == "" {
  752. // clean up unused layers and manifests
  753. if err := PruneLayers(); err != nil {
  754. return err
  755. }
  756. manifestsPath, err := GetManifestPath()
  757. if err != nil {
  758. return err
  759. }
  760. if err := PruneDirectory(manifestsPath); err != nil {
  761. return err
  762. }
  763. }
  764. s, err := NewServer()
  765. if err != nil {
  766. return err
  767. }
  768. r := s.GenerateRoutes()
  769. log.Printf("Listening on %s (version %s)", ln.Addr(), version.Version)
  770. srvr := &http.Server{
  771. Handler: r,
  772. }
  773. // listen for a ctrl+c and stop any loaded llm
  774. signals := make(chan os.Signal, 1)
  775. signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
  776. go func() {
  777. <-signals
  778. if loaded.runner != nil {
  779. loaded.runner.Close()
  780. }
  781. os.RemoveAll(s.WorkDir)
  782. os.Exit(0)
  783. }()
  784. if err := llm.Init(s.WorkDir); err != nil {
  785. return fmt.Errorf("unable to initialize llm library %w", err)
  786. }
  787. if runtime.GOOS == "linux" { // TODO - windows too
  788. // check compatibility to log warnings
  789. if _, err := gpu.CheckVRAM(); err != nil {
  790. log.Print(err.Error())
  791. }
  792. }
  793. return srvr.Serve(ln)
  794. }
  795. func waitForStream(c *gin.Context, ch chan interface{}) {
  796. c.Header("Content-Type", "application/json")
  797. for resp := range ch {
  798. switch r := resp.(type) {
  799. case api.ProgressResponse:
  800. if r.Status == "success" {
  801. c.JSON(http.StatusOK, r)
  802. return
  803. }
  804. case gin.H:
  805. if errorMsg, ok := r["error"].(string); ok {
  806. c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
  807. return
  808. } else {
  809. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in progress response"})
  810. return
  811. }
  812. default:
  813. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected progress response"})
  814. return
  815. }
  816. }
  817. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected end of progress response"})
  818. }
  819. func streamResponse(c *gin.Context, ch chan any) {
  820. c.Header("Content-Type", "application/x-ndjson")
  821. c.Stream(func(w io.Writer) bool {
  822. val, ok := <-ch
  823. if !ok {
  824. return false
  825. }
  826. bts, err := json.Marshal(val)
  827. if err != nil {
  828. log.Printf("streamResponse: json.Marshal failed with %s", err)
  829. return false
  830. }
  831. // Delineate chunks with new-line delimiter
  832. bts = append(bts, '\n')
  833. if _, err := w.Write(bts); err != nil {
  834. log.Printf("streamResponse: w.Write failed with %s", err)
  835. return false
  836. }
  837. return true
  838. })
  839. }
  840. func ChatHandler(c *gin.Context) {
  841. loaded.mu.Lock()
  842. defer loaded.mu.Unlock()
  843. checkpointStart := time.Now()
  844. var req api.ChatRequest
  845. err := c.ShouldBindJSON(&req)
  846. switch {
  847. case errors.Is(err, io.EOF):
  848. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  849. return
  850. case err != nil:
  851. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  852. return
  853. }
  854. // validate the request
  855. switch {
  856. case req.Model == "":
  857. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  858. return
  859. case len(req.Format) > 0 && req.Format != "json":
  860. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "format must be json"})
  861. return
  862. }
  863. model, err := GetModel(req.Model)
  864. if err != nil {
  865. var pErr *fs.PathError
  866. if errors.As(err, &pErr) {
  867. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
  868. return
  869. }
  870. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  871. return
  872. }
  873. opts, err := modelOptions(model, req.Options)
  874. if err != nil {
  875. if errors.Is(err, api.ErrInvalidOpts) {
  876. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  877. return
  878. }
  879. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  880. return
  881. }
  882. sessionDuration := defaultSessionDuration
  883. if err := load(c, model, opts, sessionDuration); err != nil {
  884. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  885. return
  886. }
  887. // an empty request loads the model
  888. if len(req.Messages) == 0 {
  889. c.JSON(http.StatusOK, api.ChatResponse{CreatedAt: time.Now().UTC(), Model: req.Model, Done: true, Message: api.Message{Role: "assistant"}})
  890. return
  891. }
  892. checkpointLoaded := time.Now()
  893. prompt, images, err := model.ChatPrompt(req.Messages)
  894. if err != nil {
  895. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  896. return
  897. }
  898. ch := make(chan any)
  899. go func() {
  900. defer close(ch)
  901. fn := func(r llm.PredictResult) {
  902. // Update model expiration
  903. loaded.expireAt = time.Now().Add(sessionDuration)
  904. loaded.expireTimer.Reset(sessionDuration)
  905. resp := api.ChatResponse{
  906. Model: req.Model,
  907. CreatedAt: time.Now().UTC(),
  908. Message: api.Message{Role: "assistant", Content: r.Content},
  909. Done: r.Done,
  910. Metrics: api.Metrics{
  911. PromptEvalCount: r.PromptEvalCount,
  912. PromptEvalDuration: r.PromptEvalDuration,
  913. EvalCount: r.EvalCount,
  914. EvalDuration: r.EvalDuration,
  915. },
  916. }
  917. if r.Done {
  918. resp.TotalDuration = time.Since(checkpointStart)
  919. resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)
  920. }
  921. ch <- resp
  922. }
  923. // Start prediction
  924. predictReq := llm.PredictOpts{
  925. Prompt: prompt,
  926. Format: req.Format,
  927. Images: images,
  928. Options: opts,
  929. }
  930. if err := loaded.runner.Predict(c.Request.Context(), predictReq, fn); err != nil {
  931. ch <- gin.H{"error": err.Error()}
  932. }
  933. }()
  934. if req.Stream != nil && !*req.Stream {
  935. // Accumulate responses into the final response
  936. var final api.ChatResponse
  937. var sb strings.Builder
  938. for resp := range ch {
  939. switch r := resp.(type) {
  940. case api.ChatResponse:
  941. sb.WriteString(r.Message.Content)
  942. final = r
  943. case gin.H:
  944. if errorMsg, ok := r["error"].(string); ok {
  945. c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
  946. return
  947. } else {
  948. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in response"})
  949. return
  950. }
  951. default:
  952. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error"})
  953. return
  954. }
  955. }
  956. final.Message = api.Message{Role: "assistant", Content: sb.String()}
  957. c.JSON(http.StatusOK, final)
  958. return
  959. }
  960. streamResponse(c, ch)
  961. }