routes.go 40 KB

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