routes.go 45 KB

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