routes.go 37 KB

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