routes.go 28 KB

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