routes.go 34 KB

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