routes.go 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665
  1. package server
  2. import (
  3. "bytes"
  4. "cmp"
  5. "context"
  6. "encoding/binary"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "io/fs"
  12. "log/slog"
  13. "math"
  14. "net"
  15. "net/http"
  16. "net/netip"
  17. "os"
  18. "os/signal"
  19. "path/filepath"
  20. "slices"
  21. "strings"
  22. "syscall"
  23. "time"
  24. "github.com/gin-contrib/cors"
  25. "github.com/gin-gonic/gin"
  26. "golang.org/x/sync/errgroup"
  27. "github.com/ollama/ollama/api"
  28. "github.com/ollama/ollama/discover"
  29. "github.com/ollama/ollama/envconfig"
  30. "github.com/ollama/ollama/llm"
  31. "github.com/ollama/ollama/model/mllama"
  32. "github.com/ollama/ollama/openai"
  33. "github.com/ollama/ollama/parser"
  34. "github.com/ollama/ollama/runners"
  35. "github.com/ollama/ollama/template"
  36. "github.com/ollama/ollama/types/errtypes"
  37. "github.com/ollama/ollama/types/model"
  38. "github.com/ollama/ollama/version"
  39. )
  40. var mode string = gin.DebugMode
  41. type Server struct {
  42. addr net.Addr
  43. sched *Scheduler
  44. }
  45. func init() {
  46. switch mode {
  47. case gin.DebugMode:
  48. case gin.ReleaseMode:
  49. case gin.TestMode:
  50. default:
  51. mode = gin.DebugMode
  52. }
  53. gin.SetMode(mode)
  54. }
  55. var (
  56. errRequired = errors.New("is required")
  57. errBadTemplate = errors.New("template error")
  58. )
  59. func modelOptions(model *Model, requestOpts map[string]interface{}) (api.Options, error) {
  60. opts := api.DefaultOptions()
  61. if err := opts.FromMap(model.Options); err != nil {
  62. return api.Options{}, err
  63. }
  64. if err := opts.FromMap(requestOpts); err != nil {
  65. return api.Options{}, err
  66. }
  67. return opts, nil
  68. }
  69. // scheduleRunner schedules a runner after validating inputs such as capabilities and model options.
  70. // It returns the allocated runner, model instance, and consolidated options if successful and error otherwise.
  71. func (s *Server) scheduleRunner(ctx context.Context, name string, caps []Capability, requestOpts map[string]any, keepAlive *api.Duration) (llm.LlamaServer, *Model, *api.Options, error) {
  72. if name == "" {
  73. return nil, nil, nil, fmt.Errorf("model %w", errRequired)
  74. }
  75. model, err := GetModel(name)
  76. if err != nil {
  77. return nil, nil, nil, err
  78. }
  79. if err := model.CheckCapabilities(caps...); err != nil {
  80. return nil, nil, nil, fmt.Errorf("%s %w", name, err)
  81. }
  82. opts, err := modelOptions(model, requestOpts)
  83. if err != nil {
  84. return nil, nil, nil, err
  85. }
  86. runnerCh, errCh := s.sched.GetRunner(ctx, model, opts, keepAlive)
  87. var runner *runnerRef
  88. select {
  89. case runner = <-runnerCh:
  90. case err = <-errCh:
  91. return nil, nil, nil, err
  92. }
  93. return runner.llama, model, &opts, nil
  94. }
  95. func (s *Server) GenerateHandler(c *gin.Context) {
  96. checkpointStart := time.Now()
  97. var req api.GenerateRequest
  98. if err := c.ShouldBindJSON(&req); errors.Is(err, io.EOF) {
  99. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  100. return
  101. } else if err != nil {
  102. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  103. return
  104. }
  105. name := model.ParseName(req.Model)
  106. if !name.IsValid() {
  107. // Ideally this is "invalid model name" but we're keeping with
  108. // what the API currently returns until we can change it.
  109. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
  110. return
  111. }
  112. // We cannot currently consolidate this into GetModel because all we'll
  113. // induce infinite recursion given the current code structure.
  114. name, err := getExistingName(name)
  115. if err != nil {
  116. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
  117. return
  118. }
  119. model, err := GetModel(name.String())
  120. if err != nil {
  121. switch {
  122. case errors.Is(err, fs.ErrNotExist):
  123. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
  124. case err.Error() == errtypes.InvalidModelNameErrMsg:
  125. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  126. default:
  127. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  128. }
  129. return
  130. }
  131. // expire the runner
  132. if req.Prompt == "" && req.KeepAlive != nil && int(req.KeepAlive.Seconds()) == 0 {
  133. s.sched.expireRunner(model)
  134. c.JSON(http.StatusOK, api.GenerateResponse{
  135. Model: req.Model,
  136. CreatedAt: time.Now().UTC(),
  137. Response: "",
  138. Done: true,
  139. DoneReason: "unload",
  140. })
  141. return
  142. }
  143. if req.Raw && (req.Template != "" || req.System != "" || len(req.Context) > 0) {
  144. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "raw mode does not support template, system, or context"})
  145. return
  146. }
  147. caps := []Capability{CapabilityCompletion}
  148. if req.Suffix != "" {
  149. caps = append(caps, CapabilityInsert)
  150. }
  151. r, m, opts, err := s.scheduleRunner(c.Request.Context(), name.String(), caps, req.Options, req.KeepAlive)
  152. if errors.Is(err, errCapabilityCompletion) {
  153. c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("%q does not support generate", req.Model)})
  154. return
  155. } else if err != nil {
  156. handleScheduleError(c, req.Model, err)
  157. return
  158. }
  159. checkpointLoaded := time.Now()
  160. // load the model
  161. if req.Prompt == "" {
  162. c.JSON(http.StatusOK, api.GenerateResponse{
  163. Model: req.Model,
  164. CreatedAt: time.Now().UTC(),
  165. Done: true,
  166. DoneReason: "load",
  167. })
  168. return
  169. }
  170. isMllama := checkMllamaModelFamily(model)
  171. if isMllama && len(req.Images) > 1 {
  172. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "this model only supports one image: more than one image sent"})
  173. return
  174. }
  175. images := make([]llm.ImageData, len(req.Images))
  176. for i := range req.Images {
  177. if isMllama {
  178. data, opts, err := mllama.Preprocess(bytes.NewReader(req.Images[i]))
  179. if err != nil {
  180. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "error processing image"})
  181. return
  182. }
  183. ar, ok := opts["aspectRatioIndex"].(int)
  184. if !ok {
  185. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "error processing image"})
  186. return
  187. }
  188. buf := new(bytes.Buffer)
  189. err = binary.Write(buf, binary.LittleEndian, data)
  190. if err != nil {
  191. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "error processing image"})
  192. return
  193. }
  194. images[i] = llm.ImageData{ID: i, Data: buf.Bytes(), AspectRatioID: ar}
  195. } else {
  196. images[i] = llm.ImageData{ID: i, Data: req.Images[i]}
  197. }
  198. }
  199. prompt := req.Prompt
  200. if !req.Raw {
  201. tmpl := m.Template
  202. if req.Template != "" {
  203. tmpl, err = template.Parse(req.Template)
  204. if err != nil {
  205. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  206. return
  207. }
  208. }
  209. var values template.Values
  210. if req.Suffix != "" {
  211. values.Prompt = prompt
  212. values.Suffix = req.Suffix
  213. } else {
  214. var msgs []api.Message
  215. if req.System != "" {
  216. msgs = append(msgs, api.Message{Role: "system", Content: req.System})
  217. } else if m.System != "" {
  218. msgs = append(msgs, api.Message{Role: "system", Content: m.System})
  219. }
  220. if req.Context == nil {
  221. msgs = append(msgs, m.Messages...)
  222. }
  223. for _, i := range images {
  224. imgPrompt := ""
  225. if isMllama {
  226. imgPrompt = "<|image|>"
  227. }
  228. msgs = append(msgs, api.Message{Role: "user", Content: fmt.Sprintf("[img-%d]"+imgPrompt, i.ID)})
  229. }
  230. values.Messages = append(msgs, api.Message{Role: "user", Content: req.Prompt})
  231. }
  232. var b bytes.Buffer
  233. if req.Context != nil {
  234. slog.Warn("the context field is deprecated and will be removed in a future version of Ollama")
  235. s, err := r.Detokenize(c.Request.Context(), req.Context)
  236. if err != nil {
  237. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  238. return
  239. }
  240. b.WriteString(s)
  241. }
  242. if err := tmpl.Execute(&b, values); err != nil {
  243. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  244. return
  245. }
  246. prompt = b.String()
  247. }
  248. slog.Debug("generate request", "images", len(images), "prompt", prompt)
  249. ch := make(chan any)
  250. go func() {
  251. // TODO (jmorganca): avoid building the response twice both here and below
  252. var sb strings.Builder
  253. defer close(ch)
  254. if err := r.Completion(c.Request.Context(), llm.CompletionRequest{
  255. Prompt: prompt,
  256. Images: images,
  257. Format: req.Format,
  258. Options: opts,
  259. ReturnLogits: req.ReturnLogits,
  260. }, func(cr llm.CompletionResponse) {
  261. res := api.GenerateResponse{
  262. Model: req.Model,
  263. CreatedAt: time.Now().UTC(),
  264. Response: cr.Content,
  265. Done: cr.Done,
  266. DoneReason: cr.DoneReason,
  267. Metrics: api.Metrics{
  268. PromptEvalCount: cr.PromptEvalCount,
  269. PromptEvalDuration: cr.PromptEvalDuration,
  270. EvalCount: cr.EvalCount,
  271. EvalDuration: cr.EvalDuration,
  272. },
  273. Logits: cr.Logits,
  274. }
  275. if _, err := sb.WriteString(cr.Content); err != nil {
  276. ch <- gin.H{"error": err.Error()}
  277. }
  278. if cr.Done {
  279. res.TotalDuration = time.Since(checkpointStart)
  280. res.LoadDuration = checkpointLoaded.Sub(checkpointStart)
  281. if !req.Raw {
  282. tokens, err := r.Tokenize(c.Request.Context(), prompt+sb.String())
  283. if err != nil {
  284. ch <- gin.H{"error": err.Error()}
  285. return
  286. }
  287. res.Context = tokens
  288. }
  289. }
  290. ch <- res
  291. }); err != nil {
  292. ch <- gin.H{"error": err.Error()}
  293. }
  294. }()
  295. if req.Stream != nil && !*req.Stream {
  296. var r api.GenerateResponse
  297. var sb strings.Builder
  298. for rr := range ch {
  299. switch t := rr.(type) {
  300. case api.GenerateResponse:
  301. sb.WriteString(t.Response)
  302. r = t
  303. case gin.H:
  304. msg, ok := t["error"].(string)
  305. if !ok {
  306. msg = "unexpected error format in response"
  307. }
  308. c.JSON(http.StatusInternalServerError, gin.H{"error": msg})
  309. return
  310. default:
  311. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected response"})
  312. return
  313. }
  314. }
  315. r.Response = sb.String()
  316. c.JSON(http.StatusOK, r)
  317. return
  318. }
  319. streamResponse(c, ch)
  320. }
  321. func (s *Server) EmbedHandler(c *gin.Context) {
  322. checkpointStart := time.Now()
  323. var req api.EmbedRequest
  324. err := c.ShouldBindJSON(&req)
  325. switch {
  326. case errors.Is(err, io.EOF):
  327. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  328. return
  329. case err != nil:
  330. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  331. return
  332. }
  333. truncate := true
  334. if req.Truncate != nil && !*req.Truncate {
  335. truncate = false
  336. }
  337. var input []string
  338. switch i := req.Input.(type) {
  339. case string:
  340. if len(i) > 0 {
  341. input = append(input, i)
  342. }
  343. case []any:
  344. for _, v := range i {
  345. if _, ok := v.(string); !ok {
  346. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "invalid input type"})
  347. return
  348. }
  349. input = append(input, v.(string))
  350. }
  351. default:
  352. if req.Input != nil {
  353. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "invalid input type"})
  354. return
  355. }
  356. }
  357. name, err := getExistingName(model.ParseName(req.Model))
  358. if err != nil {
  359. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
  360. return
  361. }
  362. r, m, opts, err := s.scheduleRunner(c.Request.Context(), name.String(), []Capability{}, req.Options, req.KeepAlive)
  363. if err != nil {
  364. handleScheduleError(c, req.Model, err)
  365. return
  366. }
  367. checkpointLoaded := time.Now()
  368. if len(input) == 0 {
  369. c.JSON(http.StatusOK, api.EmbedResponse{Model: req.Model, Embeddings: [][]float32{}})
  370. return
  371. }
  372. kvData, err := getKVData(m.ModelPath, false)
  373. if err != nil {
  374. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  375. return
  376. }
  377. var count int
  378. for i, s := range input {
  379. tokens, err := r.Tokenize(c.Request.Context(), s)
  380. if err != nil {
  381. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  382. return
  383. }
  384. ctxLen := min(opts.NumCtx, int(kvData.ContextLength()))
  385. if len(tokens) > ctxLen {
  386. if !truncate {
  387. c.JSON(http.StatusBadRequest, gin.H{"error": "input length exceeds maximum context length"})
  388. return
  389. }
  390. tokens = tokens[:ctxLen]
  391. s, err = r.Detokenize(c.Request.Context(), tokens)
  392. if err != nil {
  393. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  394. return
  395. }
  396. }
  397. count += len(tokens)
  398. input[i] = s
  399. }
  400. var g errgroup.Group
  401. embeddings := make([][]float32, len(input))
  402. for i, text := range input {
  403. g.Go(func() error {
  404. embedding, err := r.Embedding(c.Request.Context(), text)
  405. if err != nil {
  406. return err
  407. }
  408. embeddings[i] = normalize(embedding)
  409. return nil
  410. })
  411. }
  412. if err := g.Wait(); err != nil {
  413. slog.Error("embedding generation failed", "error", err)
  414. c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Errorf("failed to generate embeddings: %v", err)})
  415. return
  416. }
  417. resp := api.EmbedResponse{
  418. Model: req.Model,
  419. Embeddings: embeddings,
  420. TotalDuration: time.Since(checkpointStart),
  421. LoadDuration: checkpointLoaded.Sub(checkpointStart),
  422. PromptEvalCount: count,
  423. }
  424. c.JSON(http.StatusOK, resp)
  425. }
  426. func normalize(vec []float32) []float32 {
  427. var sum float32
  428. for _, v := range vec {
  429. sum += v * v
  430. }
  431. norm := float32(0.0)
  432. if sum > 0 {
  433. norm = float32(1.0 / math.Sqrt(float64(sum)))
  434. }
  435. for i := range vec {
  436. vec[i] *= norm
  437. }
  438. return vec
  439. }
  440. func (s *Server) EmbeddingsHandler(c *gin.Context) {
  441. var req api.EmbeddingRequest
  442. if err := c.ShouldBindJSON(&req); errors.Is(err, io.EOF) {
  443. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  444. return
  445. } else if err != nil {
  446. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  447. return
  448. }
  449. name := model.ParseName(req.Model)
  450. if !name.IsValid() {
  451. c.JSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  452. return
  453. }
  454. r, _, _, err := s.scheduleRunner(c.Request.Context(), name.String(), []Capability{}, req.Options, req.KeepAlive)
  455. if err != nil {
  456. handleScheduleError(c, req.Model, err)
  457. return
  458. }
  459. // an empty request loads the model
  460. if req.Prompt == "" {
  461. c.JSON(http.StatusOK, api.EmbeddingResponse{Embedding: []float64{}})
  462. return
  463. }
  464. embedding, err := r.Embedding(c.Request.Context(), req.Prompt)
  465. if err != nil {
  466. slog.Info(fmt.Sprintf("embedding generation failed: %v", err))
  467. c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Errorf("failed to generate embedding: %v", err)})
  468. return
  469. }
  470. var e []float64
  471. for _, v := range embedding {
  472. e = append(e, float64(v))
  473. }
  474. resp := api.EmbeddingResponse{
  475. Embedding: e,
  476. }
  477. c.JSON(http.StatusOK, resp)
  478. }
  479. func (s *Server) PullHandler(c *gin.Context) {
  480. var req api.PullRequest
  481. err := c.ShouldBindJSON(&req)
  482. switch {
  483. case errors.Is(err, io.EOF):
  484. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  485. return
  486. case err != nil:
  487. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  488. return
  489. }
  490. name := model.ParseName(cmp.Or(req.Model, req.Name))
  491. if !name.IsValid() {
  492. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": errtypes.InvalidModelNameErrMsg})
  493. return
  494. }
  495. name, err = getExistingName(name)
  496. if err != nil {
  497. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  498. return
  499. }
  500. ch := make(chan any)
  501. go func() {
  502. defer close(ch)
  503. fn := func(r api.ProgressResponse) {
  504. ch <- r
  505. }
  506. regOpts := &registryOptions{
  507. Insecure: req.Insecure,
  508. }
  509. ctx, cancel := context.WithCancel(c.Request.Context())
  510. defer cancel()
  511. if err := PullModel(ctx, name.DisplayShortest(), regOpts, fn); err != nil {
  512. ch <- gin.H{"error": err.Error()}
  513. }
  514. }()
  515. if req.Stream != nil && !*req.Stream {
  516. waitForStream(c, ch)
  517. return
  518. }
  519. streamResponse(c, ch)
  520. }
  521. func (s *Server) PushHandler(c *gin.Context) {
  522. var req api.PushRequest
  523. err := c.ShouldBindJSON(&req)
  524. switch {
  525. case errors.Is(err, io.EOF):
  526. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  527. return
  528. case err != nil:
  529. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  530. return
  531. }
  532. var mname string
  533. if req.Model != "" {
  534. mname = req.Model
  535. } else if req.Name != "" {
  536. mname = req.Name
  537. } else {
  538. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  539. return
  540. }
  541. ch := make(chan any)
  542. go func() {
  543. defer close(ch)
  544. fn := func(r api.ProgressResponse) {
  545. ch <- r
  546. }
  547. regOpts := &registryOptions{
  548. Insecure: req.Insecure,
  549. }
  550. ctx, cancel := context.WithCancel(c.Request.Context())
  551. defer cancel()
  552. name, err := getExistingName(model.ParseName(mname))
  553. if err != nil {
  554. ch <- gin.H{"error": err.Error()}
  555. return
  556. }
  557. if err := PushModel(ctx, name.DisplayShortest(), regOpts, fn); err != nil {
  558. ch <- gin.H{"error": err.Error()}
  559. }
  560. }()
  561. if req.Stream != nil && !*req.Stream {
  562. waitForStream(c, ch)
  563. return
  564. }
  565. streamResponse(c, ch)
  566. }
  567. // getExistingName searches the models directory for the longest prefix match of
  568. // the input name and returns the input name with all existing parts replaced
  569. // with each part found. If no parts are found, the input name is returned as
  570. // is.
  571. func getExistingName(n model.Name) (model.Name, error) {
  572. var zero model.Name
  573. existing, err := Manifests(true)
  574. if err != nil {
  575. return zero, err
  576. }
  577. var set model.Name // tracks parts already canonicalized
  578. for e := range existing {
  579. if set.Host == "" && strings.EqualFold(e.Host, n.Host) {
  580. n.Host = e.Host
  581. }
  582. if set.Namespace == "" && strings.EqualFold(e.Namespace, n.Namespace) {
  583. n.Namespace = e.Namespace
  584. }
  585. if set.Model == "" && strings.EqualFold(e.Model, n.Model) {
  586. n.Model = e.Model
  587. }
  588. if set.Tag == "" && strings.EqualFold(e.Tag, n.Tag) {
  589. n.Tag = e.Tag
  590. }
  591. }
  592. return n, nil
  593. }
  594. func (s *Server) CreateHandler(c *gin.Context) {
  595. var r api.CreateRequest
  596. if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
  597. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  598. return
  599. } else if err != nil {
  600. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  601. return
  602. }
  603. name := model.ParseName(cmp.Or(r.Model, r.Name))
  604. if !name.IsValid() {
  605. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": errtypes.InvalidModelNameErrMsg})
  606. return
  607. }
  608. name, err := getExistingName(name)
  609. if err != nil {
  610. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  611. return
  612. }
  613. if r.Path == "" && r.Modelfile == "" {
  614. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "path or Modelfile are required"})
  615. return
  616. }
  617. var sr io.Reader = strings.NewReader(r.Modelfile)
  618. if r.Path != "" && r.Modelfile == "" {
  619. f, err := os.Open(r.Path)
  620. if err != nil {
  621. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("error reading modelfile: %s", err)})
  622. return
  623. }
  624. defer f.Close()
  625. sr = f
  626. }
  627. f, err := parser.ParseFile(sr)
  628. if err != nil {
  629. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  630. return
  631. }
  632. ch := make(chan any)
  633. go func() {
  634. defer close(ch)
  635. fn := func(resp api.ProgressResponse) {
  636. ch <- resp
  637. }
  638. ctx, cancel := context.WithCancel(c.Request.Context())
  639. defer cancel()
  640. quantization := cmp.Or(r.Quantize, r.Quantization)
  641. if err := CreateModel(ctx, name, filepath.Dir(r.Path), strings.ToUpper(quantization), f, fn); errors.Is(err, errBadTemplate) {
  642. ch <- gin.H{"error": err.Error(), "status": http.StatusBadRequest}
  643. } else if err != nil {
  644. ch <- gin.H{"error": err.Error()}
  645. }
  646. }()
  647. if r.Stream != nil && !*r.Stream {
  648. waitForStream(c, ch)
  649. return
  650. }
  651. streamResponse(c, ch)
  652. }
  653. func (s *Server) DeleteHandler(c *gin.Context) {
  654. var r api.DeleteRequest
  655. if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
  656. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  657. return
  658. } else if err != nil {
  659. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  660. return
  661. }
  662. n := model.ParseName(cmp.Or(r.Model, r.Name))
  663. if !n.IsValid() {
  664. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("name %q is invalid", cmp.Or(r.Model, r.Name))})
  665. return
  666. }
  667. n, err := getExistingName(n)
  668. if err != nil {
  669. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", cmp.Or(r.Model, r.Name))})
  670. return
  671. }
  672. m, err := ParseNamedManifest(n)
  673. if err != nil {
  674. switch {
  675. case os.IsNotExist(err):
  676. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", cmp.Or(r.Model, r.Name))})
  677. default:
  678. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  679. }
  680. return
  681. }
  682. if err := m.Remove(); err != nil {
  683. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  684. return
  685. }
  686. if err := m.RemoveLayers(); err != nil {
  687. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  688. return
  689. }
  690. }
  691. func (s *Server) ShowHandler(c *gin.Context) {
  692. var req api.ShowRequest
  693. err := c.ShouldBindJSON(&req)
  694. switch {
  695. case errors.Is(err, io.EOF):
  696. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  697. return
  698. case err != nil:
  699. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  700. return
  701. }
  702. if req.Model != "" {
  703. // noop
  704. } else if req.Name != "" {
  705. req.Model = req.Name
  706. } else {
  707. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  708. return
  709. }
  710. resp, err := GetModelInfo(req)
  711. if err != nil {
  712. switch {
  713. case os.IsNotExist(err):
  714. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
  715. case err.Error() == errtypes.InvalidModelNameErrMsg:
  716. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  717. default:
  718. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  719. }
  720. return
  721. }
  722. c.JSON(http.StatusOK, resp)
  723. }
  724. func GetModelInfo(req api.ShowRequest) (*api.ShowResponse, error) {
  725. name := model.ParseName(req.Model)
  726. if !name.IsValid() {
  727. return nil, errModelPathInvalid
  728. }
  729. name, err := getExistingName(name)
  730. if err != nil {
  731. return nil, err
  732. }
  733. m, err := GetModel(name.String())
  734. if err != nil {
  735. return nil, err
  736. }
  737. modelDetails := api.ModelDetails{
  738. ParentModel: m.ParentModel,
  739. Format: m.Config.ModelFormat,
  740. Family: m.Config.ModelFamily,
  741. Families: m.Config.ModelFamilies,
  742. ParameterSize: m.Config.ModelType,
  743. QuantizationLevel: m.Config.FileType,
  744. }
  745. if req.System != "" {
  746. m.System = req.System
  747. }
  748. msgs := make([]api.Message, len(m.Messages))
  749. for i, msg := range m.Messages {
  750. msgs[i] = api.Message{Role: msg.Role, Content: msg.Content}
  751. }
  752. manifest, err := ParseNamedManifest(name)
  753. if err != nil {
  754. return nil, err
  755. }
  756. resp := &api.ShowResponse{
  757. License: strings.Join(m.License, "\n"),
  758. System: m.System,
  759. Template: m.Template.String(),
  760. Details: modelDetails,
  761. Messages: msgs,
  762. ModifiedAt: manifest.fi.ModTime(),
  763. }
  764. var params []string
  765. cs := 30
  766. for k, v := range m.Options {
  767. switch val := v.(type) {
  768. case []interface{}:
  769. for _, nv := range val {
  770. params = append(params, fmt.Sprintf("%-*s %#v", cs, k, nv))
  771. }
  772. default:
  773. params = append(params, fmt.Sprintf("%-*s %#v", cs, k, v))
  774. }
  775. }
  776. resp.Parameters = strings.Join(params, "\n")
  777. for k, v := range req.Options {
  778. if _, ok := req.Options[k]; ok {
  779. m.Options[k] = v
  780. }
  781. }
  782. var sb strings.Builder
  783. fmt.Fprintln(&sb, "# Modelfile generated by \"ollama show\"")
  784. fmt.Fprintln(&sb, "# To build a new Modelfile based on this, replace FROM with:")
  785. fmt.Fprintf(&sb, "# FROM %s\n\n", m.ShortName)
  786. fmt.Fprint(&sb, m.String())
  787. resp.Modelfile = sb.String()
  788. kvData, err := getKVData(m.ModelPath, req.Verbose)
  789. if err != nil {
  790. return nil, err
  791. }
  792. delete(kvData, "general.name")
  793. delete(kvData, "tokenizer.chat_template")
  794. resp.ModelInfo = kvData
  795. if len(m.ProjectorPaths) > 0 {
  796. projectorData, err := getKVData(m.ProjectorPaths[0], req.Verbose)
  797. if err != nil {
  798. return nil, err
  799. }
  800. resp.ProjectorInfo = projectorData
  801. }
  802. return resp, nil
  803. }
  804. func getKVData(digest string, verbose bool) (llm.KV, error) {
  805. maxArraySize := 0
  806. if verbose {
  807. maxArraySize = -1
  808. }
  809. kvData, err := llm.LoadModel(digest, maxArraySize)
  810. if err != nil {
  811. return nil, err
  812. }
  813. kv := kvData.KV()
  814. if !verbose {
  815. for k := range kv {
  816. if t, ok := kv[k].([]any); len(t) > 5 && ok {
  817. kv[k] = []any{}
  818. }
  819. }
  820. }
  821. return kv, nil
  822. }
  823. func (s *Server) ListHandler(c *gin.Context) {
  824. ms, err := Manifests(true)
  825. if err != nil {
  826. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  827. return
  828. }
  829. models := []api.ListModelResponse{}
  830. for n, m := range ms {
  831. var cf ConfigV2
  832. if m.Config.Digest != "" {
  833. f, err := m.Config.Open()
  834. if err != nil {
  835. slog.Warn("bad manifest filepath", "name", n, "error", err)
  836. continue
  837. }
  838. defer f.Close()
  839. if err := json.NewDecoder(f).Decode(&cf); err != nil {
  840. slog.Warn("bad manifest config", "name", n, "error", err)
  841. continue
  842. }
  843. }
  844. // tag should never be masked
  845. models = append(models, api.ListModelResponse{
  846. Model: n.DisplayShortest(),
  847. Name: n.DisplayShortest(),
  848. Size: m.Size(),
  849. Digest: m.digest,
  850. ModifiedAt: m.fi.ModTime(),
  851. Details: api.ModelDetails{
  852. Format: cf.ModelFormat,
  853. Family: cf.ModelFamily,
  854. Families: cf.ModelFamilies,
  855. ParameterSize: cf.ModelType,
  856. QuantizationLevel: cf.FileType,
  857. },
  858. })
  859. }
  860. slices.SortStableFunc(models, func(i, j api.ListModelResponse) int {
  861. // most recently modified first
  862. return cmp.Compare(j.ModifiedAt.Unix(), i.ModifiedAt.Unix())
  863. })
  864. c.JSON(http.StatusOK, api.ListResponse{Models: models})
  865. }
  866. func (s *Server) CopyHandler(c *gin.Context) {
  867. var r api.CopyRequest
  868. if err := c.ShouldBindJSON(&r); errors.Is(err, io.EOF) {
  869. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  870. return
  871. } else if err != nil {
  872. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  873. return
  874. }
  875. src := model.ParseName(r.Source)
  876. if !src.IsValid() {
  877. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("source %q is invalid", r.Source)})
  878. return
  879. }
  880. src, err := getExistingName(src)
  881. if err != nil {
  882. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  883. return
  884. }
  885. dst := model.ParseName(r.Destination)
  886. if !dst.IsValid() {
  887. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("destination %q is invalid", r.Destination)})
  888. return
  889. }
  890. dst, err = getExistingName(dst)
  891. if err != nil {
  892. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  893. return
  894. }
  895. if err := CopyModel(src, dst); errors.Is(err, os.ErrNotExist) {
  896. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model %q not found", r.Source)})
  897. } else if err != nil {
  898. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  899. }
  900. }
  901. func (s *Server) HeadBlobHandler(c *gin.Context) {
  902. path, err := GetBlobsPath(c.Param("digest"))
  903. if err != nil {
  904. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  905. return
  906. }
  907. if _, err := os.Stat(path); err != nil {
  908. c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("blob %q not found", c.Param("digest"))})
  909. return
  910. }
  911. c.Status(http.StatusOK)
  912. }
  913. func (s *Server) CreateBlobHandler(c *gin.Context) {
  914. if ib, ok := intermediateBlobs[c.Param("digest")]; ok {
  915. p, err := GetBlobsPath(ib)
  916. if err != nil {
  917. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  918. return
  919. }
  920. if _, err := os.Stat(p); errors.Is(err, os.ErrNotExist) {
  921. slog.Info("evicting intermediate blob which no longer exists", "digest", ib)
  922. delete(intermediateBlobs, c.Param("digest"))
  923. } else if err != nil {
  924. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  925. return
  926. } else {
  927. c.Status(http.StatusOK)
  928. return
  929. }
  930. }
  931. path, err := GetBlobsPath(c.Param("digest"))
  932. if err != nil {
  933. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  934. return
  935. }
  936. _, err = os.Stat(path)
  937. switch {
  938. case errors.Is(err, os.ErrNotExist):
  939. // noop
  940. case err != nil:
  941. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  942. return
  943. default:
  944. c.Status(http.StatusOK)
  945. return
  946. }
  947. layer, err := NewLayer(c.Request.Body, "")
  948. if err != nil {
  949. c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  950. return
  951. }
  952. if layer.Digest != c.Param("digest") {
  953. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("digest mismatch, expected %q, got %q", c.Param("digest"), layer.Digest)})
  954. return
  955. }
  956. c.Status(http.StatusCreated)
  957. }
  958. func isLocalIP(ip netip.Addr) bool {
  959. if interfaces, err := net.Interfaces(); err == nil {
  960. for _, iface := range interfaces {
  961. addrs, err := iface.Addrs()
  962. if err != nil {
  963. continue
  964. }
  965. for _, a := range addrs {
  966. if parsed, _, err := net.ParseCIDR(a.String()); err == nil {
  967. if parsed.String() == ip.String() {
  968. return true
  969. }
  970. }
  971. }
  972. }
  973. }
  974. return false
  975. }
  976. func allowedHost(host string) bool {
  977. host = strings.ToLower(host)
  978. if host == "" || host == "localhost" {
  979. return true
  980. }
  981. if hostname, err := os.Hostname(); err == nil && host == strings.ToLower(hostname) {
  982. return true
  983. }
  984. tlds := []string{
  985. "localhost",
  986. "local",
  987. "internal",
  988. }
  989. // check if the host is a local TLD
  990. for _, tld := range tlds {
  991. if strings.HasSuffix(host, "."+tld) {
  992. return true
  993. }
  994. }
  995. return false
  996. }
  997. func allowedHostsMiddleware(addr net.Addr) gin.HandlerFunc {
  998. return func(c *gin.Context) {
  999. if addr == nil {
  1000. c.Next()
  1001. return
  1002. }
  1003. if addr, err := netip.ParseAddrPort(addr.String()); err == nil && !addr.Addr().IsLoopback() {
  1004. c.Next()
  1005. return
  1006. }
  1007. host, _, err := net.SplitHostPort(c.Request.Host)
  1008. if err != nil {
  1009. host = c.Request.Host
  1010. }
  1011. if addr, err := netip.ParseAddr(host); err == nil {
  1012. if addr.IsLoopback() || addr.IsPrivate() || addr.IsUnspecified() || isLocalIP(addr) {
  1013. c.Next()
  1014. return
  1015. }
  1016. }
  1017. if allowedHost(host) {
  1018. if c.Request.Method == http.MethodOptions {
  1019. c.AbortWithStatus(http.StatusNoContent)
  1020. return
  1021. }
  1022. c.Next()
  1023. return
  1024. }
  1025. c.AbortWithStatus(http.StatusForbidden)
  1026. }
  1027. }
  1028. func (s *Server) GenerateRoutes() http.Handler {
  1029. config := cors.DefaultConfig()
  1030. config.AllowWildcard = true
  1031. config.AllowBrowserExtensions = true
  1032. config.AllowHeaders = []string{"Authorization", "Content-Type", "User-Agent", "Accept", "X-Requested-With"}
  1033. openAIProperties := []string{"lang", "package-version", "os", "arch", "retry-count", "runtime", "runtime-version", "async"}
  1034. for _, prop := range openAIProperties {
  1035. config.AllowHeaders = append(config.AllowHeaders, "x-stainless-"+prop)
  1036. }
  1037. config.AllowOrigins = envconfig.Origins()
  1038. r := gin.Default()
  1039. r.Use(
  1040. cors.New(config),
  1041. allowedHostsMiddleware(s.addr),
  1042. )
  1043. r.POST("/api/pull", s.PullHandler)
  1044. r.POST("/api/generate", s.GenerateHandler)
  1045. r.POST("/api/chat", s.ChatHandler)
  1046. r.POST("/api/embed", s.EmbedHandler)
  1047. r.POST("/api/embeddings", s.EmbeddingsHandler)
  1048. r.POST("/api/create", s.CreateHandler)
  1049. r.POST("/api/push", s.PushHandler)
  1050. r.POST("/api/copy", s.CopyHandler)
  1051. r.DELETE("/api/delete", s.DeleteHandler)
  1052. r.POST("/api/show", s.ShowHandler)
  1053. r.POST("/api/blobs/:digest", s.CreateBlobHandler)
  1054. r.HEAD("/api/blobs/:digest", s.HeadBlobHandler)
  1055. r.GET("/api/ps", s.PsHandler)
  1056. // Compatibility endpoints
  1057. r.POST("/v1/chat/completions", openai.ChatMiddleware(), s.ChatHandler)
  1058. r.POST("/v1/completions", openai.CompletionsMiddleware(), s.GenerateHandler)
  1059. r.POST("/v1/embeddings", openai.EmbeddingsMiddleware(), s.EmbedHandler)
  1060. r.GET("/v1/models", openai.ListMiddleware(), s.ListHandler)
  1061. r.GET("/v1/models/:model", openai.RetrieveMiddleware(), s.ShowHandler)
  1062. for _, method := range []string{http.MethodGet, http.MethodHead} {
  1063. r.Handle(method, "/", func(c *gin.Context) {
  1064. c.String(http.StatusOK, "Ollama is running")
  1065. })
  1066. r.Handle(method, "/api/tags", s.ListHandler)
  1067. r.Handle(method, "/api/version", func(c *gin.Context) {
  1068. c.JSON(http.StatusOK, gin.H{"version": version.Version})
  1069. })
  1070. }
  1071. return r
  1072. }
  1073. func Serve(ln net.Listener) error {
  1074. level := slog.LevelInfo
  1075. if envconfig.Debug() {
  1076. level = slog.LevelDebug
  1077. }
  1078. slog.Info("server config", "env", envconfig.Values())
  1079. handler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
  1080. Level: level,
  1081. AddSource: true,
  1082. ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
  1083. if attr.Key == slog.SourceKey {
  1084. source := attr.Value.Any().(*slog.Source)
  1085. source.File = filepath.Base(source.File)
  1086. }
  1087. return attr
  1088. },
  1089. })
  1090. slog.SetDefault(slog.New(handler))
  1091. blobsDir, err := GetBlobsPath("")
  1092. if err != nil {
  1093. return err
  1094. }
  1095. if err := fixBlobs(blobsDir); err != nil {
  1096. return err
  1097. }
  1098. if !envconfig.NoPrune() {
  1099. if _, err := Manifests(false); err != nil {
  1100. slog.Warn("corrupt manifests detected, skipping prune operation. Re-pull or delete to clear", "error", err)
  1101. } else {
  1102. // clean up unused layers and manifests
  1103. if err := PruneLayers(); err != nil {
  1104. return err
  1105. }
  1106. manifestsPath, err := GetManifestPath()
  1107. if err != nil {
  1108. return err
  1109. }
  1110. if err := PruneDirectory(manifestsPath); err != nil {
  1111. return err
  1112. }
  1113. }
  1114. }
  1115. ctx, done := context.WithCancel(context.Background())
  1116. schedCtx, schedDone := context.WithCancel(ctx)
  1117. sched := InitScheduler(schedCtx)
  1118. s := &Server{addr: ln.Addr(), sched: sched}
  1119. http.Handle("/", s.GenerateRoutes())
  1120. slog.Info(fmt.Sprintf("Listening on %s (version %s)", ln.Addr(), version.Version))
  1121. srvr := &http.Server{
  1122. // Use http.DefaultServeMux so we get net/http/pprof for
  1123. // free.
  1124. //
  1125. // TODO(bmizerany): Decide if we want to make this
  1126. // configurable so it is not exposed by default, or allow
  1127. // users to bind it to a different port. This was a quick
  1128. // and easy way to get pprof, but it may not be the best
  1129. // way.
  1130. Handler: nil,
  1131. }
  1132. // listen for a ctrl+c and stop any loaded llm
  1133. signals := make(chan os.Signal, 1)
  1134. signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
  1135. go func() {
  1136. <-signals
  1137. srvr.Close()
  1138. schedDone()
  1139. sched.unloadAllRunners()
  1140. done()
  1141. }()
  1142. // Locate and log what runners are present at startup
  1143. var runnerNames []string
  1144. for v := range runners.GetAvailableServers() {
  1145. runnerNames = append(runnerNames, v)
  1146. }
  1147. slog.Info("Dynamic LLM libraries", "runners", runnerNames)
  1148. slog.Debug("Override detection logic by setting OLLAMA_LLM_LIBRARY")
  1149. s.sched.Run(schedCtx)
  1150. // At startup we retrieve GPU information so we can get log messages before loading a model
  1151. // This will log warnings to the log in case we have problems with detected GPUs
  1152. gpus := discover.GetGPUInfo()
  1153. gpus.LogDetails()
  1154. err = srvr.Serve(ln)
  1155. // If server is closed from the signal handler, wait for the ctx to be done
  1156. // otherwise error out quickly
  1157. if !errors.Is(err, http.ErrServerClosed) {
  1158. return err
  1159. }
  1160. <-ctx.Done()
  1161. return nil
  1162. }
  1163. func waitForStream(c *gin.Context, ch chan interface{}) {
  1164. c.Header("Content-Type", "application/json")
  1165. for resp := range ch {
  1166. switch r := resp.(type) {
  1167. case api.ProgressResponse:
  1168. if r.Status == "success" {
  1169. c.JSON(http.StatusOK, r)
  1170. return
  1171. }
  1172. case gin.H:
  1173. status, ok := r["status"].(int)
  1174. if !ok {
  1175. status = http.StatusInternalServerError
  1176. }
  1177. if errorMsg, ok := r["error"].(string); ok {
  1178. c.JSON(status, gin.H{"error": errorMsg})
  1179. return
  1180. } else {
  1181. c.JSON(status, gin.H{"error": "unexpected error format in progress response"})
  1182. return
  1183. }
  1184. default:
  1185. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected progress response"})
  1186. return
  1187. }
  1188. }
  1189. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected end of progress response"})
  1190. }
  1191. func streamResponse(c *gin.Context, ch chan any) {
  1192. c.Header("Content-Type", "application/x-ndjson")
  1193. c.Stream(func(w io.Writer) bool {
  1194. val, ok := <-ch
  1195. if !ok {
  1196. return false
  1197. }
  1198. bts, err := json.Marshal(val)
  1199. if err != nil {
  1200. slog.Info(fmt.Sprintf("streamResponse: json.Marshal failed with %s", err))
  1201. return false
  1202. }
  1203. // Delineate chunks with new-line delimiter
  1204. bts = append(bts, '\n')
  1205. if _, err := w.Write(bts); err != nil {
  1206. slog.Info(fmt.Sprintf("streamResponse: w.Write failed with %s", err))
  1207. return false
  1208. }
  1209. return true
  1210. })
  1211. }
  1212. func (s *Server) PsHandler(c *gin.Context) {
  1213. models := []api.ProcessModelResponse{}
  1214. for _, v := range s.sched.loaded {
  1215. model := v.model
  1216. modelDetails := api.ModelDetails{
  1217. Format: model.Config.ModelFormat,
  1218. Family: model.Config.ModelFamily,
  1219. Families: model.Config.ModelFamilies,
  1220. ParameterSize: model.Config.ModelType,
  1221. QuantizationLevel: model.Config.FileType,
  1222. }
  1223. mr := api.ProcessModelResponse{
  1224. Model: model.ShortName,
  1225. Name: model.ShortName,
  1226. Size: int64(v.estimatedTotal),
  1227. SizeVRAM: int64(v.estimatedVRAM),
  1228. Digest: model.Digest,
  1229. Details: modelDetails,
  1230. ExpiresAt: v.expiresAt,
  1231. }
  1232. // The scheduler waits to set expiresAt, so if a model is loading it's
  1233. // possible that it will be set to the unix epoch. For those cases, just
  1234. // calculate the time w/ the sessionDuration instead.
  1235. var epoch time.Time
  1236. if v.expiresAt == epoch {
  1237. mr.ExpiresAt = time.Now().Add(v.sessionDuration)
  1238. }
  1239. models = append(models, mr)
  1240. }
  1241. slices.SortStableFunc(models, func(i, j api.ProcessModelResponse) int {
  1242. // longest duration remaining listed first
  1243. return cmp.Compare(j.ExpiresAt.Unix(), i.ExpiresAt.Unix())
  1244. })
  1245. c.JSON(http.StatusOK, api.ProcessResponse{Models: models})
  1246. }
  1247. func (s *Server) ChatHandler(c *gin.Context) {
  1248. checkpointStart := time.Now()
  1249. var req api.ChatRequest
  1250. if err := c.ShouldBindJSON(&req); errors.Is(err, io.EOF) {
  1251. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing request body"})
  1252. return
  1253. } else if err != nil {
  1254. c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  1255. return
  1256. }
  1257. // expire the runner
  1258. if len(req.Messages) == 0 && req.KeepAlive != nil && int(req.KeepAlive.Seconds()) == 0 {
  1259. model, err := GetModel(req.Model)
  1260. if err != nil {
  1261. switch {
  1262. case os.IsNotExist(err):
  1263. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Model)})
  1264. case err.Error() == errtypes.InvalidModelNameErrMsg:
  1265. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  1266. default:
  1267. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  1268. }
  1269. return
  1270. }
  1271. s.sched.expireRunner(model)
  1272. c.JSON(http.StatusOK, api.ChatResponse{
  1273. Model: req.Model,
  1274. CreatedAt: time.Now().UTC(),
  1275. Message: api.Message{Role: "assistant"},
  1276. Done: true,
  1277. DoneReason: "unload",
  1278. })
  1279. return
  1280. }
  1281. caps := []Capability{CapabilityCompletion}
  1282. if len(req.Tools) > 0 {
  1283. caps = append(caps, CapabilityTools)
  1284. }
  1285. name := model.ParseName(req.Model)
  1286. if !name.IsValid() {
  1287. c.JSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  1288. return
  1289. }
  1290. name, err := getExistingName(name)
  1291. if err != nil {
  1292. c.JSON(http.StatusBadRequest, gin.H{"error": "model is required"})
  1293. return
  1294. }
  1295. r, m, opts, err := s.scheduleRunner(c.Request.Context(), name.String(), caps, req.Options, req.KeepAlive)
  1296. if errors.Is(err, errCapabilityCompletion) {
  1297. c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("%q does not support chat", req.Model)})
  1298. return
  1299. } else if err != nil {
  1300. handleScheduleError(c, req.Model, err)
  1301. return
  1302. }
  1303. checkpointLoaded := time.Now()
  1304. if len(req.Messages) == 0 {
  1305. c.JSON(http.StatusOK, api.ChatResponse{
  1306. Model: req.Model,
  1307. CreatedAt: time.Now().UTC(),
  1308. Message: api.Message{Role: "assistant"},
  1309. Done: true,
  1310. DoneReason: "load",
  1311. })
  1312. return
  1313. }
  1314. msgs := append(m.Messages, req.Messages...)
  1315. if req.Messages[0].Role != "system" && m.System != "" {
  1316. msgs = append([]api.Message{{Role: "system", Content: m.System}}, msgs...)
  1317. }
  1318. prompt, images, err := chatPrompt(c.Request.Context(), m, r.Tokenize, opts, msgs, req.Tools)
  1319. if err != nil {
  1320. slog.Error("chat prompt error", "error", err)
  1321. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  1322. return
  1323. }
  1324. slog.Debug("chat request", "images", len(images), "prompt", prompt)
  1325. ch := make(chan any)
  1326. go func() {
  1327. defer close(ch)
  1328. var sb strings.Builder
  1329. var toolCallIndex int = 0
  1330. if err := r.Completion(c.Request.Context(), llm.CompletionRequest{
  1331. Prompt: prompt,
  1332. Images: images,
  1333. Format: req.Format,
  1334. Options: opts,
  1335. ReturnLogits: true,
  1336. }, func(r llm.CompletionResponse) {
  1337. res := api.ChatResponse{
  1338. Model: req.Model,
  1339. CreatedAt: time.Now().UTC(),
  1340. Message: api.Message{Role: "assistant", Content: r.Content},
  1341. Done: r.Done,
  1342. DoneReason: r.DoneReason,
  1343. Logits: r.Logits,
  1344. Metrics: api.Metrics{
  1345. PromptEvalCount: r.PromptEvalCount,
  1346. PromptEvalDuration: r.PromptEvalDuration,
  1347. EvalCount: r.EvalCount,
  1348. EvalDuration: r.EvalDuration,
  1349. },
  1350. }
  1351. if r.Done {
  1352. res.TotalDuration = time.Since(checkpointStart)
  1353. res.LoadDuration = checkpointLoaded.Sub(checkpointStart)
  1354. }
  1355. // TODO: tool call checking and filtering should be moved outside of this callback once streaming
  1356. // however this was a simple change for now without reworking streaming logic of this (and other)
  1357. // handlers
  1358. if req.Stream != nil && !*req.Stream || len(req.Tools) == 0 {
  1359. ch <- res
  1360. return
  1361. }
  1362. // Streaming tool calls:
  1363. // If tools are recognized, use a flag to track the sending of a tool downstream
  1364. // This ensures that content is cleared from the message on the last chunk sent
  1365. sb.WriteString(r.Content)
  1366. if toolCalls, ok := m.parseToolCalls(sb.String()); ok {
  1367. res.Message.ToolCalls = toolCalls
  1368. for i := range toolCalls {
  1369. toolCalls[i].Function.Index = toolCallIndex
  1370. toolCallIndex++
  1371. }
  1372. res.Message.Content = ""
  1373. sb.Reset()
  1374. ch <- res
  1375. return
  1376. }
  1377. if r.Done {
  1378. // Send any remaining content if no tool calls were detected
  1379. if toolCallIndex == 0 {
  1380. res.Message.Content = sb.String()
  1381. }
  1382. ch <- res
  1383. }
  1384. }); err != nil {
  1385. ch <- gin.H{"error": err.Error()}
  1386. }
  1387. }()
  1388. if req.Stream != nil && !*req.Stream {
  1389. var resp api.ChatResponse
  1390. var sb strings.Builder
  1391. for rr := range ch {
  1392. switch t := rr.(type) {
  1393. case api.ChatResponse:
  1394. sb.WriteString(t.Message.Content)
  1395. resp = t
  1396. case gin.H:
  1397. msg, ok := t["error"].(string)
  1398. if !ok {
  1399. msg = "unexpected error format in response"
  1400. }
  1401. c.JSON(http.StatusInternalServerError, gin.H{"error": msg})
  1402. return
  1403. default:
  1404. c.JSON(http.StatusInternalServerError, gin.H{"error": "unexpected response"})
  1405. return
  1406. }
  1407. }
  1408. resp.Message.Content = sb.String()
  1409. if len(req.Tools) > 0 {
  1410. if toolCalls, ok := m.parseToolCalls(sb.String()); ok {
  1411. resp.Message.ToolCalls = toolCalls
  1412. resp.Message.Content = ""
  1413. }
  1414. }
  1415. c.JSON(http.StatusOK, resp)
  1416. return
  1417. }
  1418. streamResponse(c, ch)
  1419. }
  1420. func handleScheduleError(c *gin.Context, name string, err error) {
  1421. switch {
  1422. case errors.Is(err, errCapabilities), errors.Is(err, errRequired):
  1423. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  1424. case errors.Is(err, context.Canceled):
  1425. c.JSON(499, gin.H{"error": "request canceled"})
  1426. case errors.Is(err, ErrMaxQueue):
  1427. c.JSON(http.StatusServiceUnavailable, gin.H{"error": err.Error()})
  1428. case errors.Is(err, os.ErrNotExist):
  1429. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model %q not found, try pulling it first", name)})
  1430. default:
  1431. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  1432. }
  1433. }