routes.go 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234
  1. package server
  2. import (
  3. "bytes"
  4. "cmp"
  5. "context"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "log/slog"
  11. "net"
  12. "net/http"
  13. "net/netip"
  14. "os"
  15. "os/signal"
  16. "path/filepath"
  17. "slices"
  18. "strings"
  19. "syscall"
  20. "time"
  21. "github.com/gin-contrib/cors"
  22. "github.com/gin-gonic/gin"
  23. "github.com/ollama/ollama/api"
  24. "github.com/ollama/ollama/envconfig"
  25. "github.com/ollama/ollama/gpu"
  26. "github.com/ollama/ollama/llm"
  27. "github.com/ollama/ollama/openai"
  28. "github.com/ollama/ollama/parser"
  29. "github.com/ollama/ollama/template"
  30. "github.com/ollama/ollama/types/errtypes"
  31. "github.com/ollama/ollama/types/model"
  32. "github.com/ollama/ollama/version"
  33. )
  34. var mode string = gin.DebugMode
  35. type Server struct {
  36. addr net.Addr
  37. sched *Scheduler
  38. }
  39. func init() {
  40. switch mode {
  41. case gin.DebugMode:
  42. case gin.ReleaseMode:
  43. case gin.TestMode:
  44. default:
  45. mode = gin.DebugMode
  46. }
  47. gin.SetMode(mode)
  48. }
  49. var errRequired = errors.New("is required")
  50. func modelOptions(model *Model, requestOpts map[string]interface{}) (api.Options, error) {
  51. opts := api.DefaultOptions()
  52. if err := opts.FromMap(model.Options); err != nil {
  53. return api.Options{}, err
  54. }
  55. if err := opts.FromMap(requestOpts); err != nil {
  56. return api.Options{}, err
  57. }
  58. return opts, nil
  59. }
  60. // scheduleRunner schedules a runner after validating inputs such as capabilities and model options.
  61. // It returns the allocated runner, model instance, and consolidated options if successful and error otherwise.
  62. func (s *Server) scheduleRunner(ctx context.Context, name string, caps []Capability, requestOpts map[string]any, keepAlive *api.Duration) (llm.LlamaServer, *Model, *api.Options, error) {
  63. if name == "" {
  64. return nil, nil, nil, fmt.Errorf("model %w", errRequired)
  65. }
  66. model, err := GetModel(name)
  67. if err != nil {
  68. return nil, nil, nil, err
  69. }
  70. if err := model.CheckCapabilities(caps...); err != nil {
  71. return nil, nil, nil, fmt.Errorf("%s %w", name, err)
  72. }
  73. opts, err := modelOptions(model, requestOpts)
  74. if err != nil {
  75. return nil, nil, nil, err
  76. }
  77. runnerCh, errCh := s.sched.GetRunner(ctx, model, opts, keepAlive)
  78. var runner *runnerRef
  79. select {
  80. case runner = <-runnerCh:
  81. case err = <-errCh:
  82. return nil, nil, nil, err
  83. }
  84. return runner.llama, model, &opts, nil
  85. }
  86. func (s *Server) GenerateHandler(c *gin.Context) {
  87. var req api.GenerateRequest
  88. if err := c.ShouldBindJSON(&req); errors.Is(err, io.EOF) {
  89. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  90. return
  91. } else if err != nil {
  92. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  93. return
  94. }
  95. if req.Format != "" && req.Format != "json" {
  96. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "format must be empty or \"json\""})
  97. return
  98. } else if req.Raw && (req.Template != "" || req.System != "" || len(req.Context) > 0) {
  99. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "raw mode does not support template, system, or context"})
  100. return
  101. }
  102. caps := []Capability{CapabilityCompletion}
  103. r, m, opts, err := s.scheduleRunner(c.Request.Context(), req.Model, caps, req.Options, req.KeepAlive)
  104. if errors.Is(err, errCapabilityCompletion) {
  105. c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("%q does not support generate", req.Model)})
  106. return
  107. } else if err != nil {
  108. handleScheduleError(c, req.Model, err)
  109. return
  110. }
  111. if req.Prompt == "" {
  112. c.JSON(http.StatusOK, api.GenerateResponse{
  113. Model: req.Model,
  114. CreatedAt: time.Now().UTC(),
  115. Done: true,
  116. DoneReason: "load",
  117. })
  118. return
  119. }
  120. images := make([]llm.ImageData, len(req.Images))
  121. for i := range req.Images {
  122. images[i] = llm.ImageData{ID: i, Data: req.Images[i]}
  123. }
  124. prompt := req.Prompt
  125. if !req.Raw {
  126. var msgs []api.Message
  127. if req.System != "" {
  128. msgs = append(msgs, api.Message{Role: "system", Content: req.System})
  129. } else if m.System != "" {
  130. msgs = append(msgs, api.Message{Role: "system", Content: m.System})
  131. }
  132. for _, i := range images {
  133. msgs = append(msgs, api.Message{Role: "user", Content: fmt.Sprintf("[img-%d]", i.ID)})
  134. }
  135. msgs = append(msgs, api.Message{Role: "user", Content: req.Prompt})
  136. tmpl := m.Template
  137. if req.Template != "" {
  138. tmpl, err = template.Parse(req.Template)
  139. if err != nil {
  140. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  141. return
  142. }
  143. }
  144. var b bytes.Buffer
  145. if req.Context != nil {
  146. s, err := r.Detokenize(c.Request.Context(), req.Context)
  147. if err != nil {
  148. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  149. return
  150. }
  151. b.WriteString(s)
  152. }
  153. if err := tmpl.Execute(&b, template.Values{Messages: msgs}); err != nil {
  154. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  155. return
  156. }
  157. prompt = b.String()
  158. }
  159. slog.Debug("generate request", "prompt", prompt, "images", images)
  160. ch := make(chan any)
  161. go func() {
  162. defer close(ch)
  163. if err := r.Completion(c.Request.Context(), llm.CompletionRequest{
  164. Prompt: prompt,
  165. Images: images,
  166. Format: req.Format,
  167. Options: opts,
  168. }, func(r llm.CompletionResponse) {
  169. ch <- api.GenerateResponse{
  170. Model: req.Model,
  171. CreatedAt: time.Now().UTC(),
  172. Response: r.Content,
  173. Done: r.Done,
  174. DoneReason: r.DoneReason,
  175. Metrics: api.Metrics{
  176. PromptEvalCount: r.PromptEvalCount,
  177. PromptEvalDuration: r.PromptEvalDuration,
  178. EvalCount: r.EvalCount,
  179. EvalDuration: r.EvalDuration,
  180. },
  181. }
  182. }); err != nil {
  183. ch <- gin.H{"error": err.Error()}
  184. }
  185. }()
  186. if req.Stream != nil && !*req.Stream {
  187. var r api.GenerateResponse
  188. var sb strings.Builder
  189. for rr := range ch {
  190. switch t := rr.(type) {
  191. case api.GenerateResponse:
  192. sb.WriteString(t.Response)
  193. r = t
  194. case gin.H:
  195. msg, ok := t["error"].(string)
  196. if !ok {
  197. msg = "unexpected error format in response"
  198. }
  199. c.JSON(http.StatusInternalServerError, gin.H{"error": msg})
  200. return
  201. default:
  202. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected response"})
  203. return
  204. }
  205. }
  206. r.Response = sb.String()
  207. c.JSON(http.StatusOK, r)
  208. return
  209. }
  210. streamResponse(c, ch)
  211. }
  212. func (s *Server) EmbeddingsHandler(c *gin.Context) {
  213. var req api.EmbeddingRequest
  214. if err := c.ShouldBindJSON(&req); errors.Is(err, io.EOF) {
  215. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  216. return
  217. } else if err != nil {
  218. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  219. return
  220. }
  221. r, _, _, err := s.scheduleRunner(c.Request.Context(), req.Model, []Capability{}, req.Options, req.KeepAlive)
  222. if err != nil {
  223. handleScheduleError(c, req.Model, err)
  224. return
  225. }
  226. // an empty request loads the model
  227. if req.Prompt == "" {
  228. c.JSON(http.StatusOK, api.EmbeddingResponse{Embedding: []float64{}})
  229. return
  230. }
  231. embedding, err := r.Embedding(c.Request.Context(), req.Prompt)
  232. if err != nil {
  233. slog.Info(fmt.Sprintf("embedding generation failed: %v", err))
  234. c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate embedding"})
  235. return
  236. }
  237. c.JSON(http.StatusOK, api.EmbeddingResponse{Embedding: embedding})
  238. }
  239. func (s *Server) PullModelHandler(c *gin.Context) {
  240. var req api.PullRequest
  241. err := c.ShouldBindJSON(&req)
  242. switch {
  243. case errors.Is(err, io.EOF):
  244. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  245. return
  246. case err != nil:
  247. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  248. return
  249. }
  250. name := model.ParseName(cmp.Or(req.Model, req.Name))
  251. if !name.IsValid() {
  252. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "invalid model name"})
  253. return
  254. }
  255. if err := checkNameExists(name); err != nil {
  256. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  257. return
  258. }
  259. ch := make(chan any)
  260. go func() {
  261. defer close(ch)
  262. fn := func(r api.ProgressResponse) {
  263. ch <- r
  264. }
  265. regOpts := &registryOptions{
  266. Insecure: req.Insecure,
  267. }
  268. ctx, cancel := context.WithCancel(c.Request.Context())
  269. defer cancel()
  270. if err := PullModel(ctx, name.DisplayShortest(), regOpts, fn); err != nil {
  271. ch <- gin.H{"error": err.Error()}
  272. }
  273. }()
  274. if req.Stream != nil && !*req.Stream {
  275. waitForStream(c, ch)
  276. return
  277. }
  278. streamResponse(c, ch)
  279. }
  280. func (s *Server) PushModelHandler(c *gin.Context) {
  281. var req api.PushRequest
  282. err := c.ShouldBindJSON(&req)
  283. switch {
  284. case errors.Is(err, io.EOF):
  285. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  286. return
  287. case err != nil:
  288. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  289. return
  290. }
  291. var model string
  292. if req.Model != "" {
  293. model = req.Model
  294. } else if req.Name != "" {
  295. model = req.Name
  296. } else {
  297. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  298. return
  299. }
  300. ch := make(chan any)
  301. go func() {
  302. defer close(ch)
  303. fn := func(r api.ProgressResponse) {
  304. ch <- r
  305. }
  306. regOpts := &registryOptions{
  307. Insecure: req.Insecure,
  308. }
  309. ctx, cancel := context.WithCancel(c.Request.Context())
  310. defer cancel()
  311. if err := PushModel(ctx, model, regOpts, fn); err != nil {
  312. ch <- gin.H{"error": err.Error()}
  313. }
  314. }()
  315. if req.Stream != nil && !*req.Stream {
  316. waitForStream(c, ch)
  317. return
  318. }
  319. streamResponse(c, ch)
  320. }
  321. func checkNameExists(name model.Name) error {
  322. names, err := Manifests()
  323. if err != nil {
  324. return err
  325. }
  326. for n := range names {
  327. if strings.EqualFold(n.Filepath(), name.Filepath()) && n != name {
  328. return fmt.Errorf("a model with that name already exists")
  329. }
  330. }
  331. return nil
  332. }
  333. func (s *Server) CreateModelHandler(c *gin.Context) {
  334. var r api.CreateRequest
  335. if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
  336. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  337. return
  338. } else if err != nil {
  339. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  340. return
  341. }
  342. name := model.ParseName(cmp.Or(r.Model, r.Name))
  343. if !name.IsValid() {
  344. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": errtypes.InvalidModelNameErrMsg})
  345. return
  346. }
  347. if err := checkNameExists(name); err != nil {
  348. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  349. return
  350. }
  351. if r.Path == "" && r.Modelfile == "" {
  352. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "path or modelfile are required"})
  353. return
  354. }
  355. var sr io.Reader = strings.NewReader(r.Modelfile)
  356. if r.Path != "" && r.Modelfile == "" {
  357. f, err := os.Open(r.Path)
  358. if err != nil {
  359. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error reading modelfile: %s", err)})
  360. return
  361. }
  362. defer f.Close()
  363. sr = f
  364. }
  365. f, err := parser.ParseFile(sr)
  366. if err != nil {
  367. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  368. return
  369. }
  370. ch := make(chan any)
  371. go func() {
  372. defer close(ch)
  373. fn := func(resp api.ProgressResponse) {
  374. ch <- resp
  375. }
  376. ctx, cancel := context.WithCancel(c.Request.Context())
  377. defer cancel()
  378. quantization := cmp.Or(r.Quantize, r.Quantization)
  379. if err := CreateModel(ctx, name, filepath.Dir(r.Path), strings.ToUpper(quantization), f, fn); err != nil {
  380. ch <- gin.H{"error": err.Error()}
  381. }
  382. }()
  383. if r.Stream != nil && !*r.Stream {
  384. waitForStream(c, ch)
  385. return
  386. }
  387. streamResponse(c, ch)
  388. }
  389. func (s *Server) DeleteModelHandler(c *gin.Context) {
  390. var r api.DeleteRequest
  391. if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
  392. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  393. return
  394. } else if err != nil {
  395. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  396. return
  397. }
  398. n := model.ParseName(cmp.Or(r.Model, r.Name))
  399. if !n.IsValid() {
  400. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("name %q is invalid", cmp.Or(r.Model, r.Name))})
  401. return
  402. }
  403. m, err := ParseNamedManifest(n)
  404. if err != nil {
  405. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  406. return
  407. }
  408. if err := m.Remove(); err != nil {
  409. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  410. return
  411. }
  412. if err := m.RemoveLayers(); err != nil {
  413. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  414. return
  415. }
  416. }
  417. func (s *Server) ShowModelHandler(c *gin.Context) {
  418. var req api.ShowRequest
  419. err := c.ShouldBindJSON(&req)
  420. switch {
  421. case errors.Is(err, io.EOF):
  422. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  423. return
  424. case err != nil:
  425. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  426. return
  427. }
  428. if req.Model != "" {
  429. // noop
  430. } else if req.Name != "" {
  431. req.Model = req.Name
  432. } else {
  433. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  434. return
  435. }
  436. resp, err := GetModelInfo(req)
  437. if err != nil {
  438. switch {
  439. case os.IsNotExist(err):
  440. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
  441. case err.Error() == "invalid model name":
  442. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  443. default:
  444. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  445. }
  446. return
  447. }
  448. c.JSON(http.StatusOK, resp)
  449. }
  450. func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
  451. m, err := GetModel(req.Model)
  452. if err != nil {
  453. return nil, err
  454. }
  455. modelDetails := api.ModelDetails{
  456. ParentModel: m.ParentModel,
  457. Format: m.Config.ModelFormat,
  458. Family: m.Config.ModelFamily,
  459. Families: m.Config.ModelFamilies,
  460. ParameterSize: m.Config.ModelType,
  461. QuantizationLevel: m.Config.FileType,
  462. }
  463. if req.System != "" {
  464. m.System = req.System
  465. }
  466. if req.Template != "" {
  467. m.Template, err = template.Parse(req.Template)
  468. if err != nil {
  469. return nil, err
  470. }
  471. }
  472. msgs := make([]api.Message, len(m.Messages))
  473. for i, msg := range m.Messages {
  474. msgs[i] = api.Message{Role: msg.Role, Content: msg.Content}
  475. }
  476. n := model.ParseName(req.Model)
  477. if !n.IsValid() {
  478. return nil, fmt.Errorf("invalid model name")
  479. }
  480. manifest, err := ParseNamedManifest(n)
  481. if err != nil {
  482. return nil, err
  483. }
  484. resp := &api.ShowResponse{
  485. License: strings.Join(m.License, "\n"),
  486. System: m.System,
  487. Template: m.Template.String(),
  488. Details: modelDetails,
  489. Messages: msgs,
  490. ModifiedAt: manifest.fi.ModTime(),
  491. }
  492. var params []string
  493. cs := 30
  494. for k, v := range m.Options {
  495. switch val := v.(type) {
  496. case []interface{}:
  497. for _, nv := range val {
  498. params = append(params, fmt.Sprintf("%-*s %#v", cs, k, nv))
  499. }
  500. default:
  501. params = append(params, fmt.Sprintf("%-*s %#v", cs, k, v))
  502. }
  503. }
  504. resp.Parameters = strings.Join(params, "\n")
  505. for k, v := range req.Options {
  506. if _, ok := req.Options[k]; ok {
  507. m.Options[k] = v
  508. }
  509. }
  510. var sb strings.Builder
  511. fmt.Fprintln(&sb, "# Modelfile generated by \"ollama show\"")
  512. fmt.Fprintln(&sb, "# To build a new Modelfile based on this, replace FROM with:")
  513. fmt.Fprintf(&sb, "# FROM %s\n\n", m.ShortName)
  514. fmt.Fprint(&sb, m.String())
  515. resp.Modelfile = sb.String()
  516. kvData, err := getKVData(m.ModelPath, req.Verbose)
  517. if err != nil {
  518. return nil, err
  519. }
  520. delete(kvData, "general.name")
  521. delete(kvData, "tokenizer.chat_template")
  522. resp.ModelInfo = kvData
  523. if len(m.ProjectorPaths) > 0 {
  524. projectorData, err := getKVData(m.ProjectorPaths[0], req.Verbose)
  525. if err != nil {
  526. return nil, err
  527. }
  528. resp.ProjectorInfo = projectorData
  529. }
  530. return resp, nil
  531. }
  532. func getKVData(digest string, verbose bool) (llm.KV, error) {
  533. maxArraySize := 0
  534. if verbose {
  535. maxArraySize = -1
  536. }
  537. kvData, err := llm.LoadModel(digest, maxArraySize)
  538. if err != nil {
  539. return nil, err
  540. }
  541. kv := kvData.KV()
  542. if !verbose {
  543. for k := range kv {
  544. if t, ok := kv[k].([]any); len(t) > 5 && ok {
  545. kv[k] = []any{}
  546. }
  547. }
  548. }
  549. return kv, nil
  550. }
  551. func (s *Server) ListModelsHandler(c *gin.Context) {
  552. ms, err := Manifests()
  553. if err != nil {
  554. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  555. return
  556. }
  557. models := []api.ListModelResponse{}
  558. for n, m := range ms {
  559. f, err := m.Config.Open()
  560. if err != nil {
  561. slog.Warn("bad manifest filepath", "name", n, "error", err)
  562. continue
  563. }
  564. defer f.Close()
  565. var cf ConfigV2
  566. if err := json.NewDecoder(f).Decode(&cf); err != nil {
  567. slog.Warn("bad manifest config", "name", n, "error", err)
  568. continue
  569. }
  570. // tag should never be masked
  571. models = append(models, api.ListModelResponse{
  572. Model: n.DisplayShortest(),
  573. Name: n.DisplayShortest(),
  574. Size: m.Size(),
  575. Digest: m.digest,
  576. ModifiedAt: m.fi.ModTime(),
  577. Details: api.ModelDetails{
  578. Format: cf.ModelFormat,
  579. Family: cf.ModelFamily,
  580. Families: cf.ModelFamilies,
  581. ParameterSize: cf.ModelType,
  582. QuantizationLevel: cf.FileType,
  583. },
  584. })
  585. }
  586. slices.SortStableFunc(models, func(i, j api.ListModelResponse) int {
  587. // most recently modified first
  588. return cmp.Compare(j.ModifiedAt.Unix(), i.ModifiedAt.Unix())
  589. })
  590. c.JSON(http.StatusOK, api.ListResponse{Models: models})
  591. }
  592. func (s *Server) CopyModelHandler(c *gin.Context) {
  593. var r api.CopyRequest
  594. if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
  595. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  596. return
  597. } else if err != nil {
  598. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  599. return
  600. }
  601. src := model.ParseName(r.Source)
  602. if !src.IsValid() {
  603. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("source %q is invalid", r.Source)})
  604. return
  605. }
  606. dst := model.ParseName(r.Destination)
  607. if !dst.IsValid() {
  608. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("destination %q is invalid", r.Destination)})
  609. return
  610. }
  611. if err := checkNameExists(dst); err != nil {
  612. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  613. return
  614. }
  615. if err := CopyModel(src, dst); errors.Is(err, os.ErrNotExist) {
  616. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model %q not found", r.Source)})
  617. } else if err != nil {
  618. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  619. }
  620. }
  621. func (s *Server) HeadBlobHandler(c *gin.Context) {
  622. path, err := GetBlobsPath(c.Param("digest"))
  623. if err != nil {
  624. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  625. return
  626. }
  627. if _, err := os.Stat(path); err != nil {
  628. c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("blob %q not found", c.Param("digest"))})
  629. return
  630. }
  631. c.Status(http.StatusOK)
  632. }
  633. func (s *Server) CreateBlobHandler(c *gin.Context) {
  634. if ib, ok := intermediateBlobs[c.Param("digest")]; ok {
  635. p, err := GetBlobsPath(ib)
  636. if err != nil {
  637. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  638. return
  639. }
  640. if _, err := os.Stat(p); errors.Is(err, os.ErrNotExist) {
  641. slog.Info("evicting intermediate blob which no longer exists", "digest", ib)
  642. delete(intermediateBlobs, c.Param("digest"))
  643. } else if err != nil {
  644. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  645. return
  646. } else {
  647. c.Status(http.StatusOK)
  648. return
  649. }
  650. }
  651. path, err := GetBlobsPath(c.Param("digest"))
  652. if err != nil {
  653. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  654. return
  655. }
  656. _, err = os.Stat(path)
  657. switch {
  658. case errors.Is(err, os.ErrNotExist):
  659. // noop
  660. case err != nil:
  661. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  662. return
  663. default:
  664. c.Status(http.StatusOK)
  665. return
  666. }
  667. layer, err := NewLayer(c.Request.Body, "")
  668. if err != nil {
  669. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  670. return
  671. }
  672. if layer.Digest != c.Param("digest") {
  673. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("digest mismatch, expected %q, got %q", c.Param("digest"), layer.Digest)})
  674. return
  675. }
  676. c.Status(http.StatusCreated)
  677. }
  678. func isLocalIP(ip netip.Addr) bool {
  679. if interfaces, err := net.Interfaces(); err == nil {
  680. for _, iface := range interfaces {
  681. addrs, err := iface.Addrs()
  682. if err != nil {
  683. continue
  684. }
  685. for _, a := range addrs {
  686. if parsed, _, err := net.ParseCIDR(a.String()); err == nil {
  687. if parsed.String() == ip.String() {
  688. return true
  689. }
  690. }
  691. }
  692. }
  693. }
  694. return false
  695. }
  696. func allowedHost(host string) bool {
  697. if host == "" || host == "localhost" {
  698. return true
  699. }
  700. if hostname, err := os.Hostname(); err == nil && host == hostname {
  701. return true
  702. }
  703. var tlds = []string{
  704. "localhost",
  705. "local",
  706. "internal",
  707. }
  708. // check if the host is a local TLD
  709. for _, tld := range tlds {
  710. if strings.HasSuffix(host, "."+tld) {
  711. return true
  712. }
  713. }
  714. return false
  715. }
  716. func allowedHostsMiddleware(addr net.Addr) gin.HandlerFunc {
  717. return func(c *gin.Context) {
  718. if addr == nil {
  719. c.Next()
  720. return
  721. }
  722. if addr, err := netip.ParseAddrPort(addr.String()); err == nil && !addr.Addr().IsLoopback() {
  723. c.Next()
  724. return
  725. }
  726. host, _, err := net.SplitHostPort(c.Request.Host)
  727. if err != nil {
  728. host = c.Request.Host
  729. }
  730. if addr, err := netip.ParseAddr(host); err == nil {
  731. if addr.IsLoopback() || addr.IsPrivate() || addr.IsUnspecified() || isLocalIP(addr) {
  732. c.Next()
  733. return
  734. }
  735. }
  736. if allowedHost(host) {
  737. if c.Request.Method == http.MethodOptions {
  738. c.AbortWithStatus(http.StatusNoContent)
  739. return
  740. }
  741. c.Next()
  742. return
  743. }
  744. c.AbortWithStatus(http.StatusForbidden)
  745. }
  746. }
  747. func (s *Server) GenerateRoutes() http.Handler {
  748. config := cors.DefaultConfig()
  749. config.AllowWildcard = true
  750. config.AllowBrowserExtensions = true
  751. config.AllowHeaders = []string{"Authorization", "Content-Type", "User-Agent", "Accept", "X-Requested-With"}
  752. openAIProperties := []string{"lang", "package-version", "os", "arch", "runtime", "runtime-version", "async"}
  753. for _, prop := range openAIProperties {
  754. config.AllowHeaders = append(config.AllowHeaders, "x-stainless-"+prop)
  755. }
  756. config.AllowOrigins = envconfig.AllowOrigins
  757. r := gin.Default()
  758. r.Use(
  759. cors.New(config),
  760. allowedHostsMiddleware(s.addr),
  761. )
  762. r.POST("/api/pull", s.PullModelHandler)
  763. r.POST("/api/generate", s.GenerateHandler)
  764. r.POST("/api/chat", s.ChatHandler)
  765. r.POST("/api/embeddings", s.EmbeddingsHandler)
  766. r.POST("/api/create", s.CreateModelHandler)
  767. r.POST("/api/push", s.PushModelHandler)
  768. r.POST("/api/copy", s.CopyModelHandler)
  769. r.DELETE("/api/delete", s.DeleteModelHandler)
  770. r.POST("/api/show", s.ShowModelHandler)
  771. r.POST("/api/blobs/:digest", s.CreateBlobHandler)
  772. r.HEAD("/api/blobs/:digest", s.HeadBlobHandler)
  773. r.GET("/api/ps", s.ProcessHandler)
  774. // Compatibility endpoints
  775. r.POST("/v1/chat/completions", openai.ChatMiddleware(), s.ChatHandler)
  776. r.POST("/v1/completions", openai.CompletionsMiddleware(), s.GenerateHandler)
  777. r.GET("/v1/models", openai.ListMiddleware(), s.ListModelsHandler)
  778. r.GET("/v1/models/:model", openai.RetrieveMiddleware(), s.ShowModelHandler)
  779. for _, method := range []string{http.MethodGet, http.MethodHead} {
  780. r.Handle(method, "/", func(c *gin.Context) {
  781. c.String(http.StatusOK, "Ollama is running")
  782. })
  783. r.Handle(method, "/api/tags", s.ListModelsHandler)
  784. r.Handle(method, "/api/version", func(c *gin.Context) {
  785. c.JSON(http.StatusOK, gin.H{"version": version.Version})
  786. })
  787. }
  788. return r
  789. }
  790. func Serve(ln net.Listener) error {
  791. level := slog.LevelInfo
  792. if envconfig.Debug {
  793. level = slog.LevelDebug
  794. }
  795. slog.Info("server config", "env", envconfig.Values())
  796. handler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
  797. Level: level,
  798. AddSource: true,
  799. ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
  800. if attr.Key == slog.SourceKey {
  801. source := attr.Value.Any().(*slog.Source)
  802. source.File = filepath.Base(source.File)
  803. }
  804. return attr
  805. },
  806. })
  807. slog.SetDefault(slog.New(handler))
  808. blobsDir, err := GetBlobsPath("")
  809. if err != nil {
  810. return err
  811. }
  812. if err := fixBlobs(blobsDir); err != nil {
  813. return err
  814. }
  815. if !envconfig.NoPrune {
  816. // clean up unused layers and manifests
  817. if err := PruneLayers(); err != nil {
  818. return err
  819. }
  820. manifestsPath, err := GetManifestPath()
  821. if err != nil {
  822. return err
  823. }
  824. if err := PruneDirectory(manifestsPath); err != nil {
  825. return err
  826. }
  827. }
  828. ctx, done := context.WithCancel(context.Background())
  829. schedCtx, schedDone := context.WithCancel(ctx)
  830. sched := InitScheduler(schedCtx)
  831. s := &Server{addr: ln.Addr(), sched: sched}
  832. http.Handle("/", s.GenerateRoutes())
  833. slog.Info(fmt.Sprintf("Listening on %s (version %s)", ln.Addr(), version.Version))
  834. srvr := &http.Server{
  835. // Use http.DefaultServeMux so we get net/http/pprof for
  836. // free.
  837. //
  838. // TODO(bmizerany): Decide if we want to make this
  839. // configurable so it is not exposed by default, or allow
  840. // users to bind it to a different port. This was a quick
  841. // and easy way to get pprof, but it may not be the best
  842. // way.
  843. Handler: nil,
  844. }
  845. // listen for a ctrl+c and stop any loaded llm
  846. signals := make(chan os.Signal, 1)
  847. signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
  848. go func() {
  849. <-signals
  850. srvr.Close()
  851. schedDone()
  852. sched.unloadAllRunners()
  853. gpu.Cleanup()
  854. done()
  855. }()
  856. if err := llm.Init(); err != nil {
  857. return fmt.Errorf("unable to initialize llm library %w", err)
  858. }
  859. s.sched.Run(schedCtx)
  860. // At startup we retrieve GPU information so we can get log messages before loading a model
  861. // This will log warnings to the log in case we have problems with detected GPUs
  862. gpus := gpu.GetGPUInfo()
  863. gpus.LogDetails()
  864. err = srvr.Serve(ln)
  865. // If server is closed from the signal handler, wait for the ctx to be done
  866. // otherwise error out quickly
  867. if !errors.Is(err, http.ErrServerClosed) {
  868. return err
  869. }
  870. <-ctx.Done()
  871. return nil
  872. }
  873. func waitForStream(c *gin.Context, ch chan interface{}) {
  874. c.Header("Content-Type", "application/json")
  875. for resp := range ch {
  876. switch r := resp.(type) {
  877. case api.ProgressResponse:
  878. if r.Status == "success" {
  879. c.JSON(http.StatusOK, r)
  880. return
  881. }
  882. case gin.H:
  883. if errorMsg, ok := r["error"].(string); ok {
  884. c.JSON(http.StatusInternalServerError, gin.H{"error": errorMsg})
  885. return
  886. } else {
  887. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected error format in progress response"})
  888. return
  889. }
  890. default:
  891. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected progress response"})
  892. return
  893. }
  894. }
  895. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected end of progress response"})
  896. }
  897. func streamResponse(c *gin.Context, ch chan any) {
  898. c.Header("Content-Type", "application/x-ndjson")
  899. c.Stream(func(w io.Writer) bool {
  900. val, ok := <-ch
  901. if !ok {
  902. return false
  903. }
  904. bts, err := json.Marshal(val)
  905. if err != nil {
  906. slog.Info(fmt.Sprintf("streamResponse: json.Marshal failed with %s", err))
  907. return false
  908. }
  909. // Delineate chunks with new-line delimiter
  910. bts = append(bts, '\n')
  911. if _, err := w.Write(bts); err != nil {
  912. slog.Info(fmt.Sprintf("streamResponse: w.Write failed with %s", err))
  913. return false
  914. }
  915. return true
  916. })
  917. }
  918. func (s *Server) ProcessHandler(c *gin.Context) {
  919. models := []api.ProcessModelResponse{}
  920. for _, v := range s.sched.loaded {
  921. model := v.model
  922. modelDetails := api.ModelDetails{
  923. Format: model.Config.ModelFormat,
  924. Family: model.Config.ModelFamily,
  925. Families: model.Config.ModelFamilies,
  926. ParameterSize: model.Config.ModelType,
  927. QuantizationLevel: model.Config.FileType,
  928. }
  929. mr := api.ProcessModelResponse{
  930. Model: model.ShortName,
  931. Name: model.ShortName,
  932. Size: int64(v.estimatedTotal),
  933. SizeVRAM: int64(v.estimatedVRAM),
  934. Digest: model.Digest,
  935. Details: modelDetails,
  936. ExpiresAt: v.expiresAt,
  937. }
  938. // The scheduler waits to set expiresAt, so if a model is loading it's
  939. // possible that it will be set to the unix epoch. For those cases, just
  940. // calculate the time w/ the sessionDuration instead.
  941. var epoch time.Time
  942. if v.expiresAt == epoch {
  943. mr.ExpiresAt = time.Now().Add(v.sessionDuration)
  944. }
  945. models = append(models, mr)
  946. }
  947. slices.SortStableFunc(models, func(i, j api.ProcessModelResponse) int {
  948. // longest duration remaining listed first
  949. return cmp.Compare(j.ExpiresAt.Unix(), i.ExpiresAt.Unix())
  950. })
  951. c.JSON(http.StatusOK, api.ProcessResponse{Models: models})
  952. }
  953. func (s *Server) ChatHandler(c *gin.Context) {
  954. var req api.ChatRequest
  955. if err := c.ShouldBindJSON(&req); errors.Is(err, io.EOF) {
  956. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  957. return
  958. } else if err != nil {
  959. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  960. return
  961. }
  962. caps := []Capability{CapabilityCompletion}
  963. r, m, opts, err := s.scheduleRunner(c.Request.Context(), req.Model, caps, req.Options, req.KeepAlive)
  964. if errors.Is(err, errCapabilityCompletion) {
  965. c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("%q does not support chat", req.Model)})
  966. return
  967. } else if err != nil {
  968. handleScheduleError(c, req.Model, err)
  969. return
  970. }
  971. if len(req.Messages) == 0 {
  972. c.JSON(http.StatusOK, api.ChatResponse{
  973. Model: req.Model,
  974. CreatedAt: time.Now().UTC(),
  975. Message: api.Message{Role: "assistant"},
  976. Done: true,
  977. DoneReason: "load",
  978. })
  979. return
  980. }
  981. prompt, images, err := chatPrompt(c.Request.Context(), m, r.Tokenize, opts, req.Messages)
  982. if err != nil {
  983. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  984. return
  985. }
  986. slog.Debug("chat request", "images", len(images), "prompt", prompt)
  987. ch := make(chan any)
  988. go func() {
  989. defer close(ch)
  990. if err := r.Completion(c.Request.Context(), llm.CompletionRequest{
  991. Prompt: prompt,
  992. Images: images,
  993. Format: req.Format,
  994. Options: opts,
  995. }, func(r llm.CompletionResponse) {
  996. ch <- api.ChatResponse{
  997. Model: req.Model,
  998. CreatedAt: time.Now().UTC(),
  999. Message: api.Message{Role: "assistant", Content: r.Content},
  1000. Done: r.Done,
  1001. DoneReason: r.DoneReason,
  1002. Metrics: api.Metrics{
  1003. PromptEvalCount: r.PromptEvalCount,
  1004. PromptEvalDuration: r.PromptEvalDuration,
  1005. EvalCount: r.EvalCount,
  1006. EvalDuration: r.EvalDuration,
  1007. },
  1008. }
  1009. }); err != nil {
  1010. ch <- gin.H{"error": err.Error()}
  1011. }
  1012. }()
  1013. if req.Stream != nil && !*req.Stream {
  1014. var r api.ChatResponse
  1015. var sb strings.Builder
  1016. for rr := range ch {
  1017. switch t := rr.(type) {
  1018. case api.ChatResponse:
  1019. sb.WriteString(t.Message.Content)
  1020. r = t
  1021. case gin.H:
  1022. msg, ok := t["error"].(string)
  1023. if !ok {
  1024. msg = "unexpected error format in response"
  1025. }
  1026. c.JSON(http.StatusInternalServerError, gin.H{"error": msg})
  1027. return
  1028. default:
  1029. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected response"})
  1030. return
  1031. }
  1032. }
  1033. r.Message.Content = sb.String()
  1034. c.JSON(http.StatusOK, r)
  1035. return
  1036. }
  1037. streamResponse(c, ch)
  1038. }
  1039. func handleScheduleError(c *gin.Context, name string, err error) {
  1040. switch {
  1041. case errors.Is(err, errRequired):
  1042. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  1043. case errors.Is(err, context.Canceled):
  1044. c.JSON(499, gin.H{"error": "request canceled"})
  1045. case errors.Is(err, ErrMaxQueue):
  1046. c.JSON(http.StatusServiceUnavailable, gin.H{"error": err.Error()})
  1047. case errors.Is(err, os.ErrNotExist):
  1048. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model %q not found, try pulling it first", name)})
  1049. default:
  1050. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  1051. }
  1052. }