routes.go 43 KB

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