routes.go 34 KB

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