routes.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149
  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. 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 string:
  569. params = append(params, fmt.Sprintf("%-*s %s", cs, k, val))
  570. case int:
  571. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.Itoa(val)))
  572. case float64:
  573. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatFloat(val, 'f', 0, 64)))
  574. case bool:
  575. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatBool(val)))
  576. case []interface{}:
  577. for _, nv := range val {
  578. switch nval := nv.(type) {
  579. case string:
  580. params = append(params, fmt.Sprintf("%-*s %s", cs, k, nval))
  581. case int:
  582. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.Itoa(nval)))
  583. case float64:
  584. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatFloat(nval, 'f', 0, 64)))
  585. case bool:
  586. params = append(params, fmt.Sprintf("%-*s %s", cs, k, strconv.FormatBool(nval)))
  587. }
  588. }
  589. }
  590. }
  591. resp.Parameters = strings.Join(params, "\n")
  592. for k, v := range req.Options {
  593. if _, ok := req.Options[k]; ok {
  594. model.Options[k] = v
  595. }
  596. }
  597. mf, err := ShowModelfile(model)
  598. if err != nil {
  599. return nil, err
  600. }
  601. resp.Modelfile = mf
  602. return resp, nil
  603. }
  604. func ListModelsHandler(c *gin.Context) {
  605. models := make([]api.ModelResponse, 0)
  606. fp, err := GetManifestPath()
  607. if err != nil {
  608. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  609. return
  610. }
  611. modelResponse := func(modelName string) (api.ModelResponse, error) {
  612. model, err := GetModel(modelName)
  613. if err != nil {
  614. return api.ModelResponse{}, err
  615. }
  616. modelDetails := api.ModelDetails{
  617. Format: model.Config.ModelFormat,
  618. Family: model.Config.ModelFamily,
  619. Families: model.Config.ModelFamilies,
  620. ParameterSize: model.Config.ModelType,
  621. QuantizationLevel: model.Config.FileType,
  622. }
  623. return api.ModelResponse{
  624. Name: model.ShortName,
  625. Size: model.Size,
  626. Digest: model.Digest,
  627. Details: modelDetails,
  628. }, nil
  629. }
  630. walkFunc := func(path string, info os.FileInfo, _ error) error {
  631. if !info.IsDir() {
  632. dir, file := filepath.Split(path)
  633. dir = strings.Trim(strings.TrimPrefix(dir, fp), string(os.PathSeparator))
  634. tag := strings.Join([]string{dir, file}, ":")
  635. resp, err := modelResponse(tag)
  636. if err != nil {
  637. log.Printf("skipping file: %s", fp)
  638. return nil
  639. }
  640. resp.ModifiedAt = info.ModTime()
  641. models = append(models, resp)
  642. }
  643. return nil
  644. }
  645. if err := filepath.Walk(fp, walkFunc); err != nil {
  646. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  647. return
  648. }
  649. c.JSON(http.StatusOK, api.ListResponse{Models: models})
  650. }
  651. func CopyModelHandler(c *gin.Context) {
  652. var req api.CopyRequest
  653. err := c.ShouldBindJSON(&req)
  654. switch {
  655. case errors.Is(err, io.EOF):
  656. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  657. return
  658. case err != nil:
  659. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  660. return
  661. }
  662. if req.Source == "" || req.Destination == "" {
  663. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "source add destination are required"})
  664. return
  665. }
  666. if err := ParseModelPath(req.Destination).Validate(); err != nil {
  667. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  668. return
  669. }
  670. if err := CopyModel(req.Source, req.Destination); err != nil {
  671. if os.IsNotExist(err) {
  672. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Source)})
  673. } else {
  674. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  675. }
  676. return
  677. }
  678. }
  679. func HeadBlobHandler(c *gin.Context) {
  680. path, err := GetBlobsPath(c.Param("digest"))
  681. if err != nil {
  682. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  683. return
  684. }
  685. if _, err := os.Stat(path); err != nil {
  686. c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("blob %q not found", c.Param("digest"))})
  687. return
  688. }
  689. c.Status(http.StatusOK)
  690. }
  691. func CreateBlobHandler(c *gin.Context) {
  692. layer, err := NewLayer(c.Request.Body, "")
  693. if err != nil {
  694. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  695. return
  696. }
  697. if layer.Digest != c.Param("digest") {
  698. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("digest mismatch, expected %q, got %q", c.Param("digest"), layer.Digest)})
  699. return
  700. }
  701. if _, err := layer.Commit(); err != nil {
  702. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  703. return
  704. }
  705. c.Status(http.StatusCreated)
  706. }
  707. var defaultAllowOrigins = []string{
  708. "localhost",
  709. "127.0.0.1",
  710. "0.0.0.0",
  711. }
  712. func NewServer() (*Server, error) {
  713. workDir, err := os.MkdirTemp("", "ollama")
  714. if err != nil {
  715. return nil, err
  716. }
  717. return &Server{
  718. WorkDir: workDir,
  719. }, nil
  720. }
  721. func (s *Server) GenerateRoutes() http.Handler {
  722. var origins []string
  723. if o := os.Getenv("OLLAMA_ORIGINS"); o != "" {
  724. origins = strings.Split(o, ",")
  725. }
  726. config := cors.DefaultConfig()
  727. config.AllowWildcard = true
  728. config.AllowBrowserExtensions = true
  729. config.AllowOrigins = origins
  730. for _, allowOrigin := range defaultAllowOrigins {
  731. config.AllowOrigins = append(config.AllowOrigins,
  732. fmt.Sprintf("http://%s", allowOrigin),
  733. fmt.Sprintf("https://%s", allowOrigin),
  734. fmt.Sprintf("http://%s:*", allowOrigin),
  735. fmt.Sprintf("https://%s:*", allowOrigin),
  736. )
  737. }
  738. r := gin.Default()
  739. r.Use(
  740. cors.New(config),
  741. func(c *gin.Context) {
  742. c.Set("workDir", s.WorkDir)
  743. c.Next()
  744. },
  745. )
  746. r.POST("/api/pull", PullModelHandler)
  747. r.POST("/api/generate", GenerateHandler)
  748. r.POST("/api/chat", ChatHandler)
  749. r.POST("/api/embeddings", EmbeddingHandler)
  750. r.POST("/api/create", CreateModelHandler)
  751. r.POST("/api/push", PushModelHandler)
  752. r.POST("/api/copy", CopyModelHandler)
  753. r.DELETE("/api/delete", DeleteModelHandler)
  754. r.POST("/api/show", ShowModelHandler)
  755. r.POST("/api/blobs/:digest", CreateBlobHandler)
  756. r.HEAD("/api/blobs/:digest", HeadBlobHandler)
  757. for _, method := range []string{http.MethodGet, http.MethodHead} {
  758. r.Handle(method, "/", func(c *gin.Context) {
  759. c.String(http.StatusOK, "Ollama is running")
  760. })
  761. r.Handle(method, "/api/tags", ListModelsHandler)
  762. r.Handle(method, "/api/version", func(c *gin.Context) {
  763. c.JSON(http.StatusOK, gin.H{"version": version.Version})
  764. })
  765. }
  766. return r
  767. }
  768. func Serve(ln net.Listener) error {
  769. if noprune := os.Getenv("OLLAMA_NOPRUNE"); noprune == "" {
  770. // clean up unused layers and manifests
  771. if err := PruneLayers(); err != nil {
  772. return err
  773. }
  774. manifestsPath, err := GetManifestPath()
  775. if err != nil {
  776. return err
  777. }
  778. if err := PruneDirectory(manifestsPath); err != nil {
  779. return err
  780. }
  781. }
  782. s, err := NewServer()
  783. if err != nil {
  784. return err
  785. }
  786. r := s.GenerateRoutes()
  787. log.Printf("Listening on %s (version %s)", ln.Addr(), version.Version)
  788. srvr := &http.Server{
  789. Handler: r,
  790. }
  791. // listen for a ctrl+c and stop any loaded llm
  792. signals := make(chan os.Signal, 1)
  793. signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
  794. go func() {
  795. <-signals
  796. if loaded.runner != nil {
  797. loaded.runner.Close()
  798. }
  799. os.RemoveAll(s.WorkDir)
  800. os.Exit(0)
  801. }()
  802. if err := llm.Init(s.WorkDir); err != nil {
  803. return fmt.Errorf("unable to initialize llm library %w", err)
  804. }
  805. if runtime.GOOS == "linux" { // TODO - windows too
  806. // check compatibility to log warnings
  807. if _, err := gpu.CheckVRAM(); err != nil {
  808. log.Print(err.Error())
  809. }
  810. }
  811. return srvr.Serve(ln)
  812. }
  813. func waitForStream(c *gin.Context, ch chan interface{}) {
  814. c.Header("Content-Type", "application/json")
  815. for resp := range ch {
  816. switch r := resp.(type) {
  817. case api.ProgressResponse:
  818. if r.Status == "success" {
  819. c.JSON(http.StatusOK, r)
  820. return
  821. }
  822. case gin.H:
  823. if errorMsg, ok := r["error"].(string); ok {
  824. c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
  825. return
  826. } else {
  827. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in progress response"})
  828. return
  829. }
  830. default:
  831. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected progress response"})
  832. return
  833. }
  834. }
  835. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected end of progress response"})
  836. }
  837. func streamResponse(c *gin.Context, ch chan any) {
  838. c.Header("Content-Type", "application/x-ndjson")
  839. c.Stream(func(w io.Writer) bool {
  840. val, ok := <-ch
  841. if !ok {
  842. return false
  843. }
  844. bts, err := json.Marshal(val)
  845. if err != nil {
  846. log.Printf("streamResponse: json.Marshal failed with %s", err)
  847. return false
  848. }
  849. // Delineate chunks with new-line delimiter
  850. bts = append(bts, '\n')
  851. if _, err := w.Write(bts); err != nil {
  852. log.Printf("streamResponse: w.Write failed with %s", err)
  853. return false
  854. }
  855. return true
  856. })
  857. }
  858. func ChatHandler(c *gin.Context) {
  859. loaded.mu.Lock()
  860. defer loaded.mu.Unlock()
  861. checkpointStart := time.Now()
  862. var req api.ChatRequest
  863. err := c.ShouldBindJSON(&req)
  864. switch {
  865. case errors.Is(err, io.EOF):
  866. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  867. return
  868. case err != nil:
  869. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  870. return
  871. }
  872. // validate the request
  873. switch {
  874. case req.Model == "":
  875. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  876. return
  877. case len(req.Format) > 0 && req.Format != "json":
  878. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "format must be json"})
  879. return
  880. }
  881. model, err := GetModel(req.Model)
  882. if err != nil {
  883. var pErr *fs.PathError
  884. if errors.As(err, &pErr) {
  885. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found, try pulling it first", req.Model)})
  886. return
  887. }
  888. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  889. return
  890. }
  891. opts, err := modelOptions(model, req.Options)
  892. if err != nil {
  893. if errors.Is(err, api.ErrInvalidOpts) {
  894. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  895. return
  896. }
  897. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  898. return
  899. }
  900. sessionDuration := defaultSessionDuration
  901. if err := load(c, model, opts, sessionDuration); err != nil {
  902. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  903. return
  904. }
  905. // an empty request loads the model
  906. if len(req.Messages) == 0 {
  907. c.JSON(http.StatusOK, api.ChatResponse{CreatedAt: time.Now().UTC(), Model: req.Model, Done: true, Message: api.Message{Role: "assistant"}})
  908. return
  909. }
  910. checkpointLoaded := time.Now()
  911. prompt, images, err := model.ChatPrompt(req.Messages)
  912. if err != nil {
  913. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  914. return
  915. }
  916. ch := make(chan any)
  917. go func() {
  918. defer close(ch)
  919. fn := func(r llm.PredictResult) {
  920. // Update model expiration
  921. loaded.expireAt = time.Now().Add(sessionDuration)
  922. loaded.expireTimer.Reset(sessionDuration)
  923. resp := api.ChatResponse{
  924. Model: req.Model,
  925. CreatedAt: time.Now().UTC(),
  926. Message: api.Message{Role: "assistant", Content: r.Content},
  927. Done: r.Done,
  928. Metrics: api.Metrics{
  929. PromptEvalCount: r.PromptEvalCount,
  930. PromptEvalDuration: r.PromptEvalDuration,
  931. EvalCount: r.EvalCount,
  932. EvalDuration: r.EvalDuration,
  933. },
  934. }
  935. if r.Done {
  936. resp.TotalDuration = time.Since(checkpointStart)
  937. resp.LoadDuration = checkpointLoaded.Sub(checkpointStart)
  938. }
  939. ch <- resp
  940. }
  941. // Start prediction
  942. predictReq := llm.PredictOpts{
  943. Prompt: prompt,
  944. Format: req.Format,
  945. Images: images,
  946. Options: opts,
  947. }
  948. if err := loaded.runner.Predict(c.Request.Context(), predictReq, fn); err != nil {
  949. ch <- gin.H{"error": err.Error()}
  950. }
  951. }()
  952. if req.Stream != nil && !*req.Stream {
  953. // Accumulate responses into the final response
  954. var final api.ChatResponse
  955. var sb strings.Builder
  956. for resp := range ch {
  957. switch r := resp.(type) {
  958. case api.ChatResponse:
  959. sb.WriteString(r.Message.Content)
  960. final = r
  961. case gin.H:
  962. if errorMsg, ok := r["error"].(string); ok {
  963. c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
  964. return
  965. } else {
  966. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in response"})
  967. return
  968. }
  969. default:
  970. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error"})
  971. return
  972. }
  973. }
  974. final.Message = api.Message{Role: "assistant", Content: sb.String()}
  975. c.JSON(http.StatusOK, final)
  976. return
  977. }
  978. streamResponse(c, ch)
  979. }