routes.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. package server
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "log"
  8. "net"
  9. "net/http"
  10. "os"
  11. "os/signal"
  12. "path/filepath"
  13. "reflect"
  14. "strings"
  15. "sync"
  16. "syscall"
  17. "time"
  18. "github.com/gin-contrib/cors"
  19. "github.com/gin-gonic/gin"
  20. "gonum.org/v1/gonum/mat"
  21. "github.com/jmorganca/ollama/api"
  22. "github.com/jmorganca/ollama/llm"
  23. "github.com/jmorganca/ollama/vector"
  24. )
  25. var mode string = gin.DebugMode
  26. func init() {
  27. switch mode {
  28. case gin.DebugMode:
  29. case gin.ReleaseMode:
  30. case gin.TestMode:
  31. default:
  32. mode = gin.DebugMode
  33. }
  34. gin.SetMode(mode)
  35. }
  36. var loaded struct {
  37. mu sync.Mutex
  38. llm llm.LLM
  39. Embeddings []vector.Embedding
  40. expireAt time.Time
  41. expireTimer *time.Timer
  42. digest string
  43. options api.Options
  44. }
  45. var defaultSessionDuration = 5 * time.Minute
  46. // load a model into memory if it is not already loaded, it is up to the caller to lock loaded.mu before calling this function
  47. func load(ctx context.Context, model *Model, reqOpts map[string]interface{}, sessionDuration time.Duration) error {
  48. opts := api.DefaultOptions()
  49. if err := opts.FromMap(model.Options); err != nil {
  50. log.Printf("could not load model options: %v", err)
  51. return err
  52. }
  53. if err := opts.FromMap(reqOpts); err != nil {
  54. log.Printf("could not merge model options: %v", err)
  55. return err
  56. }
  57. // check if the loaded model is still running in a subprocess, in case something unexpected happened
  58. if loaded.llm != nil {
  59. if err := loaded.llm.Ping(ctx); err != nil {
  60. log.Print("loaded llm process not responding, closing now")
  61. // the subprocess is no longer running, so close it
  62. loaded.llm.Close()
  63. loaded.llm = nil
  64. loaded.digest = ""
  65. }
  66. }
  67. if model.Digest != loaded.digest || !reflect.DeepEqual(loaded.options, opts) {
  68. if loaded.llm != nil {
  69. log.Println("changing loaded model")
  70. loaded.llm.Close()
  71. loaded.llm = nil
  72. loaded.digest = ""
  73. }
  74. if model.Embeddings != nil && len(model.Embeddings) > 0 {
  75. opts.EmbeddingOnly = true // this is requried to generate embeddings, completions will still work
  76. loaded.Embeddings = model.Embeddings
  77. }
  78. llmModel, err := llm.New(model.ModelPath, model.AdapterPaths, opts)
  79. if err != nil {
  80. return err
  81. }
  82. // set cache values before modifying opts
  83. loaded.llm = llmModel
  84. loaded.digest = model.Digest
  85. loaded.options = opts
  86. if opts.NumKeep < 0 {
  87. promptWithSystem, err := model.Prompt(api.GenerateRequest{}, "")
  88. if err != nil {
  89. return err
  90. }
  91. promptNoSystem, err := model.Prompt(api.GenerateRequest{Context: []int{0}}, "")
  92. if err != nil {
  93. return err
  94. }
  95. tokensWithSystem, err := llmModel.Encode(ctx, promptWithSystem)
  96. if err != nil {
  97. return err
  98. }
  99. tokensNoSystem, err := llmModel.Encode(ctx, promptNoSystem)
  100. if err != nil {
  101. return err
  102. }
  103. opts.NumKeep = len(tokensWithSystem) - len(tokensNoSystem) + 1
  104. llmModel.SetOptions(opts)
  105. }
  106. }
  107. loaded.expireAt = time.Now().Add(sessionDuration)
  108. if loaded.expireTimer == nil {
  109. loaded.expireTimer = time.AfterFunc(sessionDuration, func() {
  110. loaded.mu.Lock()
  111. defer loaded.mu.Unlock()
  112. if time.Now().Before(loaded.expireAt) {
  113. return
  114. }
  115. if loaded.llm == nil {
  116. return
  117. }
  118. loaded.llm.Close()
  119. loaded.llm = nil
  120. loaded.digest = ""
  121. })
  122. }
  123. loaded.expireTimer.Reset(sessionDuration)
  124. return nil
  125. }
  126. func GenerateHandler(c *gin.Context) {
  127. loaded.mu.Lock()
  128. defer loaded.mu.Unlock()
  129. checkpointStart := time.Now()
  130. var req api.GenerateRequest
  131. if err := c.ShouldBindJSON(&req); err != nil {
  132. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  133. return
  134. }
  135. model, err := GetModel(req.Model)
  136. if err != nil {
  137. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  138. return
  139. }
  140. sessionDuration := defaultSessionDuration // TODO: set this duration from the request if specified
  141. if err := load(c.Request.Context(), model, req.Options, sessionDuration); err != nil {
  142. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  143. return
  144. }
  145. checkpointLoaded := time.Now()
  146. embedding := ""
  147. if model.Embeddings != nil && len(model.Embeddings) > 0 {
  148. promptEmbed, err := loaded.llm.Embedding(c.Request.Context(), req.Prompt)
  149. if err != nil {
  150. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  151. return
  152. }
  153. // TODO: set embed_top from specified parameters in modelfile
  154. embed_top := 3
  155. topK := vector.TopK(embed_top, mat.NewVecDense(len(promptEmbed), promptEmbed), loaded.Embeddings)
  156. for _, e := range topK {
  157. embedding = fmt.Sprintf("%s %s", embedding, e.Embedding.Data)
  158. }
  159. }
  160. prompt, err := model.Prompt(req, embedding)
  161. if err != nil {
  162. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  163. return
  164. }
  165. ch := make(chan any)
  166. go func() {
  167. defer close(ch)
  168. fn := func(r api.GenerateResponse) {
  169. loaded.expireAt = time.Now().Add(sessionDuration)
  170. loaded.expireTimer.Reset(sessionDuration)
  171. r.Model = req.Model
  172. r.CreatedAt = time.Now().UTC()
  173. if r.Done {
  174. r.TotalDuration = time.Since(checkpointStart)
  175. r.LoadDuration = checkpointLoaded.Sub(checkpointStart)
  176. }
  177. ch <- r
  178. }
  179. if err := loaded.llm.Predict(c.Request.Context(), req.Context, prompt, fn); err != nil {
  180. ch <- gin.H{"error": err.Error()}
  181. }
  182. }()
  183. streamResponse(c, ch)
  184. }
  185. func EmbeddingHandler(c *gin.Context) {
  186. loaded.mu.Lock()
  187. defer loaded.mu.Unlock()
  188. var req api.EmbeddingRequest
  189. if err := c.ShouldBindJSON(&req); err != nil {
  190. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  191. return
  192. }
  193. model, err := GetModel(req.Model)
  194. if err != nil {
  195. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  196. return
  197. }
  198. if err := load(c.Request.Context(), model, req.Options, 5*time.Minute); err != nil {
  199. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  200. return
  201. }
  202. if !loaded.options.EmbeddingOnly {
  203. c.JSON(http.StatusBadRequest, gin.H{"error": "embedding option must be set to true"})
  204. return
  205. }
  206. embedding, err := loaded.llm.Embedding(c.Request.Context(), req.Prompt)
  207. if err != nil {
  208. log.Printf("embedding generation failed: %v", err)
  209. c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate embedding"})
  210. return
  211. }
  212. resp := api.EmbeddingResponse{
  213. Embedding: embedding,
  214. }
  215. c.JSON(http.StatusOK, resp)
  216. }
  217. func PullModelHandler(c *gin.Context) {
  218. var req api.PullRequest
  219. if err := c.ShouldBindJSON(&req); err != nil {
  220. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  221. return
  222. }
  223. ch := make(chan any)
  224. go func() {
  225. defer close(ch)
  226. fn := func(r api.ProgressResponse) {
  227. ch <- r
  228. }
  229. regOpts := &RegistryOptions{
  230. Insecure: req.Insecure,
  231. Username: req.Username,
  232. Password: req.Password,
  233. }
  234. ctx, cancel := context.WithCancel(c.Request.Context())
  235. defer cancel()
  236. if err := PullModel(ctx, req.Name, regOpts, fn); err != nil {
  237. ch <- gin.H{"error": err.Error()}
  238. }
  239. }()
  240. streamResponse(c, ch)
  241. }
  242. func PushModelHandler(c *gin.Context) {
  243. var req api.PushRequest
  244. if err := c.ShouldBindJSON(&req); err != nil {
  245. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  246. return
  247. }
  248. ch := make(chan any)
  249. go func() {
  250. defer close(ch)
  251. fn := func(r api.ProgressResponse) {
  252. ch <- r
  253. }
  254. regOpts := &RegistryOptions{
  255. Insecure: req.Insecure,
  256. Username: req.Username,
  257. Password: req.Password,
  258. }
  259. ctx := context.Background()
  260. if err := PushModel(ctx, req.Name, regOpts, fn); err != nil {
  261. ch <- gin.H{"error": err.Error()}
  262. }
  263. }()
  264. streamResponse(c, ch)
  265. }
  266. func CreateModelHandler(c *gin.Context) {
  267. var req api.CreateRequest
  268. if err := c.ShouldBindJSON(&req); err != nil {
  269. c.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
  270. return
  271. }
  272. ch := make(chan any)
  273. go func() {
  274. defer close(ch)
  275. fn := func(resp api.ProgressResponse) {
  276. ch <- resp
  277. }
  278. ctx, cancel := context.WithCancel(c.Request.Context())
  279. defer cancel()
  280. if err := CreateModel(ctx, req.Name, req.Path, fn); err != nil {
  281. ch <- gin.H{"error": err.Error()}
  282. }
  283. }()
  284. streamResponse(c, ch)
  285. }
  286. func DeleteModelHandler(c *gin.Context) {
  287. var req api.DeleteRequest
  288. if err := c.ShouldBindJSON(&req); err != nil {
  289. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  290. return
  291. }
  292. if err := DeleteModel(req.Name); err != nil {
  293. if os.IsNotExist(err) {
  294. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Name)})
  295. } else {
  296. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  297. }
  298. return
  299. }
  300. }
  301. func ListModelsHandler(c *gin.Context) {
  302. var models []api.ModelResponse
  303. fp, err := GetManifestPath()
  304. if err != nil {
  305. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  306. return
  307. }
  308. walkFunc := func(path string, info os.FileInfo, _ error) error {
  309. if !info.IsDir() {
  310. dir, file := filepath.Split(path)
  311. dir = strings.Trim(strings.TrimPrefix(dir, fp), string(os.PathSeparator))
  312. tag := strings.Join([]string{dir, file}, ":")
  313. mp := ParseModelPath(tag)
  314. manifest, digest, err := GetManifest(mp)
  315. if err != nil {
  316. log.Printf("skipping file: %s", fp)
  317. return nil
  318. }
  319. models = append(models, api.ModelResponse{
  320. Name: mp.GetShortTagname(),
  321. Size: manifest.GetTotalSize(),
  322. Digest: digest,
  323. ModifiedAt: info.ModTime(),
  324. })
  325. }
  326. return nil
  327. }
  328. if err := filepath.Walk(fp, walkFunc); err != nil {
  329. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  330. return
  331. }
  332. c.JSON(http.StatusOK, api.ListResponse{Models: models})
  333. }
  334. func CopyModelHandler(c *gin.Context) {
  335. var req api.CopyRequest
  336. if err := c.ShouldBindJSON(&req); err != nil {
  337. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  338. return
  339. }
  340. if err := CopyModel(req.Source, req.Destination); err != nil {
  341. if os.IsNotExist(err) {
  342. c.JSON(http.StatusNotFound, gin.H{"error": fmt.Sprintf("model '%s' not found", req.Source)})
  343. } else {
  344. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  345. }
  346. return
  347. }
  348. }
  349. func Serve(ln net.Listener, origins []string) error {
  350. config := cors.DefaultConfig()
  351. config.AllowWildcard = true
  352. config.AllowOrigins = append(origins, []string{
  353. "http://localhost",
  354. "http://localhost:*",
  355. "https://localhost",
  356. "https://localhost:*",
  357. "http://127.0.0.1",
  358. "http://127.0.0.1:*",
  359. "https://127.0.0.1",
  360. "https://127.0.0.1:*",
  361. "http://0.0.0.0",
  362. "http://0.0.0.0:*",
  363. "https://0.0.0.0",
  364. "https://0.0.0.0:*",
  365. }...)
  366. r := gin.Default()
  367. r.Use(cors.New(config))
  368. r.GET("/", func(c *gin.Context) {
  369. c.String(http.StatusOK, "Ollama is running")
  370. })
  371. r.HEAD("/", func(c *gin.Context) {
  372. c.Status(http.StatusOK)
  373. })
  374. r.POST("/api/pull", PullModelHandler)
  375. r.POST("/api/generate", GenerateHandler)
  376. r.POST("/api/embeddings", EmbeddingHandler)
  377. r.POST("/api/create", CreateModelHandler)
  378. r.POST("/api/push", PushModelHandler)
  379. r.POST("/api/copy", CopyModelHandler)
  380. r.GET("/api/tags", ListModelsHandler)
  381. r.DELETE("/api/delete", DeleteModelHandler)
  382. log.Printf("Listening on %s", ln.Addr())
  383. s := &http.Server{
  384. Handler: r,
  385. }
  386. // listen for a ctrl+c and stop any loaded llm
  387. signals := make(chan os.Signal, 1)
  388. signal.Notify(signals, syscall.SIGINT)
  389. go func() {
  390. <-signals
  391. if loaded.llm != nil {
  392. loaded.llm.Close()
  393. }
  394. os.Exit(0)
  395. }()
  396. return s.Serve(ln)
  397. }
  398. func streamResponse(c *gin.Context, ch chan any) {
  399. c.Header("Content-Type", "application/x-ndjson")
  400. c.Stream(func(w io.Writer) bool {
  401. val, ok := <-ch
  402. if !ok {
  403. return false
  404. }
  405. bts, err := json.Marshal(val)
  406. if err != nil {
  407. log.Printf("streamResponse: json.Marshal failed with %s", err)
  408. return false
  409. }
  410. bts = append(bts, '\n')
  411. if _, err := w.Write(bts); err != nil {
  412. log.Printf("streamResponse: w.Write failed with %s", err)
  413. return false
  414. }
  415. return true
  416. })
  417. }