routes.go 27 KB

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