server.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  1. package llm
  2. import (
  3. "bufio"
  4. "bytes"
  5. "context"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "log"
  11. "log/slog"
  12. "math/rand"
  13. "net"
  14. "net/http"
  15. "os"
  16. "os/exec"
  17. "path/filepath"
  18. "runtime"
  19. "strconv"
  20. "strings"
  21. "time"
  22. "golang.org/x/sync/semaphore"
  23. "github.com/ollama/ollama/api"
  24. "github.com/ollama/ollama/format"
  25. "github.com/ollama/ollama/gpu"
  26. )
  27. type LlamaServer interface {
  28. Ping(ctx context.Context) error
  29. WaitUntilRunning(ctx context.Context) error
  30. Completion(ctx context.Context, req CompletionRequest, fn func(CompletionResponse)) error
  31. Embeddings(ctx context.Context, prompt []string) ([][]float64, error)
  32. Tokenize(ctx context.Context, content string) ([]int, error)
  33. Detokenize(ctx context.Context, tokens []int) (string, error)
  34. Close() error
  35. EstimatedVRAM() uint64
  36. }
  37. // llmServer is an instance of the llama.cpp server
  38. type llmServer struct {
  39. port int
  40. cmd *exec.Cmd
  41. done chan error // Channel to signal when the process exits
  42. status *StatusWriter
  43. options api.Options
  44. // TODO - this should be broken down by GPU
  45. estimatedVRAM uint64 // Estimated usage of VRAM by the loaded model
  46. sem *semaphore.Weighted
  47. }
  48. func LoadModel(model string) (*GGML, error) {
  49. if _, err := os.Stat(model); err != nil {
  50. return nil, err
  51. }
  52. f, err := os.Open(model)
  53. if err != nil {
  54. return nil, err
  55. }
  56. defer f.Close()
  57. ggml, _, err := DecodeGGML(f)
  58. return ggml, err
  59. }
  60. // NewLlamaServer will run a server for the given GPUs
  61. // The gpu list must be a single family.
  62. func NewLlamaServer(gpus gpu.GpuInfoList, model string, ggml *GGML, adapters, projectors []string, opts api.Options) (LlamaServer, error) {
  63. var err error
  64. if opts.NumCtx > int(ggml.KV().ContextLength()) {
  65. slog.Warn("requested context length is greater than model max context length", "requested", opts.NumCtx, "model", ggml.KV().ContextLength())
  66. opts.NumCtx = int(ggml.KV().ContextLength())
  67. }
  68. if opts.NumCtx < 4 {
  69. opts.NumCtx = 4
  70. }
  71. cpuRunner := ""
  72. var estimatedVRAM uint64
  73. var systemMemory uint64
  74. if (len(gpus) == 1 && gpus[0].Library == "cpu") || opts.NumGPU == 0 {
  75. // TODO evaluate system memory to see if we should block the load, or force an unload of another CPU runner
  76. cpuRunner = serverForCpu()
  77. } else {
  78. if gpus[0].Library == "metal" {
  79. memInfo, err := gpu.GetCPUMem()
  80. if err != nil {
  81. slog.Error("failed to lookup system memory", "error", err)
  82. } else {
  83. systemMemory = memInfo.TotalMemory
  84. slog.Debug("system memory", "total", format.HumanBytes2(systemMemory))
  85. }
  86. }
  87. var layers int
  88. layers, estimatedVRAM = EstimateGPULayers(gpus, ggml, projectors, opts)
  89. if gpus[0].Library == "metal" && estimatedVRAM > systemMemory {
  90. // disable partial offloading when model is greater than total system memory as this
  91. // can lead to locking up the system
  92. opts.NumGPU = 0
  93. } else if opts.NumGPU < 0 && layers > 0 && gpus[0].Library != "cpu" {
  94. opts.NumGPU = layers
  95. }
  96. }
  97. // Loop through potential servers
  98. finalErr := fmt.Errorf("no suitable llama servers found")
  99. if len(adapters) > 1 {
  100. return nil, errors.New("ollama supports only one lora adapter, but multiple were provided")
  101. }
  102. availableServers := availableServers()
  103. var servers []string
  104. if cpuRunner != "" {
  105. servers = []string{cpuRunner}
  106. } else {
  107. servers = serversForGpu(gpus[0]) // All GPUs in the list are matching Library and Variant
  108. }
  109. demandLib := strings.Trim(os.Getenv("OLLAMA_LLM_LIBRARY"), "\"' ")
  110. if demandLib != "" {
  111. serverPath := availableServers[demandLib]
  112. if serverPath == "" {
  113. slog.Info(fmt.Sprintf("Invalid OLLAMA_LLM_LIBRARY %s - not found", demandLib))
  114. } else {
  115. slog.Info("user override", "OLLAMA_LLM_LIBRARY", demandLib, "path", serverPath)
  116. servers = []string{demandLib}
  117. }
  118. }
  119. if len(servers) == 0 {
  120. return nil, fmt.Errorf("no servers found for %v", gpus)
  121. }
  122. params := []string{
  123. "--model", model,
  124. "--ctx-size", fmt.Sprintf("%d", opts.NumCtx),
  125. "--batch-size", fmt.Sprintf("%d", opts.NumBatch),
  126. "--embedding",
  127. }
  128. if debug := os.Getenv("OLLAMA_DEBUG"); debug != "" {
  129. params = append(params, "--log-format", "json")
  130. } else {
  131. params = append(params, "--log-disable")
  132. }
  133. if opts.NumGPU >= 0 {
  134. params = append(params, "--n-gpu-layers", fmt.Sprintf("%d", opts.NumGPU))
  135. }
  136. if debug := os.Getenv("OLLAMA_DEBUG"); debug != "" {
  137. params = append(params, "--verbose")
  138. }
  139. if opts.MainGPU > 0 {
  140. params = append(params, "--main-gpu", fmt.Sprintf("%d", opts.MainGPU))
  141. }
  142. if len(adapters) > 0 {
  143. // TODO: applying multiple adapters is not supported by the llama.cpp server yet
  144. params = append(params, "--lora", adapters[0])
  145. }
  146. if len(projectors) > 0 {
  147. // TODO: applying multiple projectors is not supported by the llama.cpp server yet
  148. params = append(params, "--mmproj", projectors[0])
  149. }
  150. if opts.NumThread > 0 {
  151. params = append(params, "--threads", fmt.Sprintf("%d", opts.NumThread))
  152. }
  153. if !opts.F16KV {
  154. params = append(params, "--memory-f32")
  155. }
  156. if opts.UseMLock {
  157. params = append(params, "--mlock")
  158. }
  159. if !opts.UseMMap {
  160. params = append(params, "--no-mmap")
  161. }
  162. if opts.UseNUMA {
  163. params = append(params, "--numa")
  164. }
  165. // "--cont-batching", // TODO - doesn't seem to have any noticeable perf change for multiple requests
  166. numParallel := 1
  167. if onp := os.Getenv("OLLAMA_NUM_PARALLEL"); onp != "" {
  168. numParallel, err = strconv.Atoi(onp)
  169. if err != nil || numParallel <= 0 {
  170. err = fmt.Errorf("invalid OLLAMA_NUM_PARALLEL=%s must be greater than zero - %w", onp, err)
  171. slog.Error("misconfiguration", "error", err)
  172. return nil, err
  173. }
  174. }
  175. params = append(params, "--parallel", fmt.Sprintf("%d", numParallel))
  176. for i := 0; i < len(servers); i++ {
  177. dir := availableServers[servers[i]]
  178. if dir == "" {
  179. // Shouldn't happen
  180. finalErr = fmt.Errorf("[%d] server %s not listed in available servers %v", i, servers[i], availableServers)
  181. slog.Error("sever list inconsistent", "error", finalErr)
  182. continue
  183. }
  184. // Find an availableServers port, retry on each iterration in case the failure was a port conflict race
  185. port := 0
  186. if a, err := net.ResolveTCPAddr("tcp", "localhost:0"); err == nil {
  187. var l *net.TCPListener
  188. if l, err = net.ListenTCP("tcp", a); err == nil {
  189. port = l.Addr().(*net.TCPAddr).Port
  190. l.Close()
  191. }
  192. }
  193. if port == 0 {
  194. slog.Debug("ResolveTCPAddr failed ", "error", err)
  195. port = rand.Intn(65535-49152) + 49152 // get a random port in the ephemeral range
  196. }
  197. finalParams := append(params, "--port", strconv.Itoa(port))
  198. pathEnv := "LD_LIBRARY_PATH"
  199. if runtime.GOOS == "windows" {
  200. pathEnv = "PATH"
  201. }
  202. // append the server directory to LD_LIBRARY_PATH/PATH
  203. libraryPaths := []string{dir}
  204. if libraryPath, ok := os.LookupEnv(pathEnv); ok {
  205. // Append our runner directory to the path
  206. // This will favor system libraries over our bundled library dependencies
  207. libraryPaths = append(filepath.SplitList(libraryPath), libraryPaths...)
  208. }
  209. // Note: we always put the dependency path first
  210. // since this was the exact version we verified for AMD GPUs
  211. // and we favor what the user had in their path
  212. if gpus[0].DependencyPath != "" {
  213. // TODO refine for multi-gpu support
  214. libraryPaths = append([]string{gpus[0].DependencyPath}, libraryPaths...)
  215. }
  216. server := filepath.Join(dir, "ollama_llama_server")
  217. if runtime.GOOS == "windows" {
  218. server = server + ".exe"
  219. }
  220. // Detect tmp cleaners wiping out the file
  221. _, err := os.Stat(server)
  222. if errors.Is(err, os.ErrNotExist) {
  223. slog.Warn("llama server disappeared, reinitializing payloads", "path", server, "error", err)
  224. err = Init()
  225. if err != nil {
  226. slog.Warn("failed to reinitialize payloads", "error", err)
  227. return nil, err
  228. }
  229. }
  230. s := &llmServer{
  231. port: port,
  232. cmd: exec.Command(server, finalParams...),
  233. status: NewStatusWriter(os.Stderr),
  234. options: opts,
  235. estimatedVRAM: estimatedVRAM,
  236. sem: semaphore.NewWeighted(int64(numParallel)),
  237. }
  238. libEnv := fmt.Sprintf("%s=%s", pathEnv, strings.Join(libraryPaths, string(filepath.ListSeparator)))
  239. s.cmd.Env = append(os.Environ(), libEnv)
  240. s.cmd.Stdout = os.Stdout
  241. s.cmd.Stderr = s.status
  242. // TODO - multiple GPU selection logic...
  243. key, val := gpu.GpuInfoList(gpus).GetVisibleDevicesEnv()
  244. if key != "" {
  245. s.cmd.Env = append(s.cmd.Env, key+"="+val)
  246. }
  247. slog.Info("starting llama server", "cmd", s.cmd.String())
  248. // Log at debug as the environment is inherited and might contain sensitive information
  249. slog.Debug("subprocess", "environment", s.cmd.Env)
  250. if err = s.cmd.Start(); err != nil {
  251. msg := ""
  252. if s.status != nil && s.status.LastErrMsg != "" {
  253. msg = s.status.LastErrMsg
  254. }
  255. err = fmt.Errorf("error starting the external llama server: %v %s", err, msg)
  256. finalErr = err
  257. continue
  258. }
  259. // reap subprocess when it exits
  260. go func() {
  261. // Exit status managed via getServerStatus
  262. _ = s.cmd.Wait()
  263. }()
  264. // TODO - make sure this is all wired up correctly
  265. // if err = s.WaitUntilRunning(); err != nil {
  266. // slog.Error("error starting llama server", "server", servers[i], "error", err)
  267. // s.Close()
  268. // finalErr = err
  269. // continue
  270. // }
  271. return s, nil
  272. }
  273. slog.Error("unable to load any llama server", "error", finalErr)
  274. return nil, finalErr
  275. }
  276. func projectorMemoryRequirements(filename string) uint64 {
  277. file, err := os.Open(filename)
  278. if err != nil {
  279. return 0
  280. }
  281. defer file.Close()
  282. ggml, _, err := DecodeGGML(file)
  283. if err != nil {
  284. return 0
  285. }
  286. var mem uint64
  287. for _, layer := range ggml.Tensors().Layers() {
  288. mem += layer.size()
  289. }
  290. return mem
  291. }
  292. type ServerStatus int
  293. const ( // iota is reset to 0
  294. ServerStatusReady ServerStatus = iota
  295. ServerStatusNoSlotsAvaialble
  296. ServerStatusLoadingModel
  297. ServerStatusNotResponding
  298. ServerStatusError
  299. )
  300. func (s ServerStatus) ToString() string {
  301. switch s {
  302. case ServerStatusReady:
  303. return "llm server ready"
  304. case ServerStatusNoSlotsAvaialble:
  305. return "llm busy - no slots available"
  306. case ServerStatusLoadingModel:
  307. return "llm server loading model"
  308. case ServerStatusNotResponding:
  309. return "llm server not responding"
  310. default:
  311. return "llm server error"
  312. }
  313. }
  314. type ServerStatusResp struct {
  315. Status string `json:"status"`
  316. SlotsIdle int `json:"slots_idle"`
  317. SlotsProcessing int `json:"slots_processing"`
  318. Error string `json:"error"`
  319. }
  320. func (s *llmServer) getServerStatus(ctx context.Context) (ServerStatus, error) {
  321. // Fail fast if its exited
  322. if s.cmd.ProcessState != nil {
  323. msg := ""
  324. if s.status != nil && s.status.LastErrMsg != "" {
  325. msg = s.status.LastErrMsg
  326. }
  327. return ServerStatusError, fmt.Errorf("llama runner process no longer running: %d %s", s.cmd.ProcessState.ExitCode(), msg)
  328. }
  329. req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://127.0.0.1:%d/health", s.port), nil)
  330. if err != nil {
  331. return ServerStatusError, fmt.Errorf("error creating GET request: %v", err)
  332. }
  333. req.Header.Set("Content-Type", "application/json")
  334. resp, err := http.DefaultClient.Do(req)
  335. if err != nil {
  336. if errors.Is(err, context.DeadlineExceeded) {
  337. return ServerStatusNotResponding, fmt.Errorf("server not responding")
  338. }
  339. return ServerStatusError, fmt.Errorf("health resp: %w", err)
  340. }
  341. defer resp.Body.Close()
  342. body, err := io.ReadAll(resp.Body)
  343. if err != nil {
  344. return ServerStatusError, fmt.Errorf("read health request: %w", err)
  345. }
  346. var status ServerStatusResp
  347. if err := json.Unmarshal(body, &status); err != nil {
  348. return ServerStatusError, fmt.Errorf("health unmarshal encode response: %w", err)
  349. }
  350. switch status.Status {
  351. case "ok":
  352. return ServerStatusReady, nil
  353. case "no slot available":
  354. return ServerStatusNoSlotsAvaialble, nil
  355. case "loading model":
  356. return ServerStatusLoadingModel, nil
  357. default:
  358. return ServerStatusError, fmt.Errorf("server error: %+v", status)
  359. }
  360. }
  361. func (s *llmServer) Ping(ctx context.Context) error {
  362. _, err := s.getServerStatus(ctx)
  363. if err != nil {
  364. slog.Debug("server unhealthy", "error", err)
  365. return err
  366. }
  367. return nil
  368. }
  369. func (s *llmServer) WaitUntilRunning(ctx context.Context) error {
  370. start := time.Now()
  371. // TODO we need to wire up a better way to detect hangs during model load and startup of the server
  372. expiresAt := time.Now().Add(10 * time.Minute) // be generous with timeout, large models can take a while to load
  373. ticker := time.NewTicker(50 * time.Millisecond)
  374. defer ticker.Stop()
  375. slog.Info("waiting for llama runner to start responding")
  376. var lastStatus ServerStatus = -1
  377. for {
  378. select {
  379. case <-ctx.Done():
  380. slog.Info("context expired before server started")
  381. return fmt.Errorf("timed out waiting for llama runner to start: %w", ctx.Err())
  382. case err := <-s.done:
  383. msg := ""
  384. if s.status != nil && s.status.LastErrMsg != "" {
  385. msg = s.status.LastErrMsg
  386. }
  387. return fmt.Errorf("llama runner process has terminated: %v %s", err, msg)
  388. case <-ticker.C:
  389. if time.Now().After(expiresAt) {
  390. // timeout
  391. msg := ""
  392. if s.status != nil && s.status.LastErrMsg != "" {
  393. msg = s.status.LastErrMsg
  394. }
  395. return fmt.Errorf("timed out waiting for llama runner to start: %s", msg)
  396. }
  397. if s.cmd.ProcessState != nil {
  398. msg := ""
  399. if s.status != nil && s.status.LastErrMsg != "" {
  400. msg = s.status.LastErrMsg
  401. }
  402. return fmt.Errorf("llama runner process no longer running: %d %s", s.cmd.ProcessState.ExitCode(), msg)
  403. }
  404. c, cancel := context.WithTimeout(ctx, 200*time.Millisecond)
  405. defer cancel()
  406. status, err := s.getServerStatus(c)
  407. if err != nil && lastStatus != status {
  408. slog.Debug("server not yet available", "error", err)
  409. lastStatus = status
  410. continue
  411. }
  412. switch status {
  413. case ServerStatusLoadingModel:
  414. // TODO - this state never seems to happen with the current server.cpp code (bug?)
  415. // it doesn't respond to the health endpoint until after the model is loaded
  416. slog.Debug("loading model")
  417. case ServerStatusReady:
  418. slog.Debug(fmt.Sprintf("llama runner started in %f seconds", time.Since(start).Seconds()))
  419. return nil
  420. }
  421. }
  422. }
  423. }
  424. const jsonGrammar = `
  425. root ::= object
  426. value ::= object | array | string | number | ("true" | "false" | "null") ws
  427. object ::=
  428. "{" ws (
  429. string ":" ws value
  430. ("," ws string ":" ws value)*
  431. )? "}" ws
  432. array ::=
  433. "[" ws (
  434. value
  435. ("," ws value)*
  436. )? "]" ws
  437. string ::=
  438. "\"" (
  439. [^"\\] |
  440. "\\" (["\\/bfnrt] | "u" [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F]) # escapes
  441. )* "\"" ws
  442. number ::= ("-"? ([0-9] | [1-9] [0-9]*)) ("." [0-9]+)? ([eE] [-+]? [0-9]+)? ws
  443. # Optional space: by convention, applied in this grammar after literal chars when allowed
  444. ws ::= ([ \t\n] ws)?
  445. `
  446. const maxBufferSize = 512 * format.KiloByte
  447. const maxRetries = 3
  448. type ImageData struct {
  449. Data []byte `json:"data"`
  450. ID int `json:"id"`
  451. }
  452. type completion struct {
  453. Content string `json:"content"`
  454. Model string `json:"model"`
  455. Prompt string `json:"prompt"`
  456. Stop bool `json:"stop"`
  457. Timings struct {
  458. PredictedN int `json:"predicted_n"`
  459. PredictedMS float64 `json:"predicted_ms"`
  460. PromptN int `json:"prompt_n"`
  461. PromptMS float64 `json:"prompt_ms"`
  462. }
  463. }
  464. type CompletionRequest struct {
  465. Prompt string
  466. Format string
  467. Images []ImageData
  468. Options api.Options
  469. }
  470. type CompletionResponse struct {
  471. Content string
  472. Done bool
  473. PromptEvalCount int
  474. PromptEvalDuration time.Duration
  475. EvalCount int
  476. EvalDuration time.Duration
  477. }
  478. func (s *llmServer) Completion(ctx context.Context, req CompletionRequest, fn func(CompletionResponse)) error {
  479. if err := s.sem.Acquire(ctx, 1); err != nil {
  480. slog.Error("Failed to acquire semaphore", "error", err)
  481. return err
  482. }
  483. defer s.sem.Release(1)
  484. // only allow maximum 10 "context shifts" to avoid infinite generation
  485. if req.Options.NumPredict < 0 || req.Options.NumPredict > 10*s.options.NumCtx {
  486. req.Options.NumPredict = 10 * s.options.NumCtx
  487. slog.Debug("setting token limit to 10x num_ctx", "num_ctx", s.options.NumCtx, "num_predict", req.Options.NumPredict)
  488. }
  489. request := map[string]any{
  490. "prompt": req.Prompt,
  491. "stream": true,
  492. "n_predict": req.Options.NumPredict,
  493. "n_keep": req.Options.NumKeep,
  494. "main_gpu": req.Options.MainGPU,
  495. "temperature": req.Options.Temperature,
  496. "top_k": req.Options.TopK,
  497. "top_p": req.Options.TopP,
  498. "tfs_z": req.Options.TFSZ,
  499. "typical_p": req.Options.TypicalP,
  500. "repeat_last_n": req.Options.RepeatLastN,
  501. "repeat_penalty": req.Options.RepeatPenalty,
  502. "presence_penalty": req.Options.PresencePenalty,
  503. "frequency_penalty": req.Options.FrequencyPenalty,
  504. "mirostat": req.Options.Mirostat,
  505. "mirostat_tau": req.Options.MirostatTau,
  506. "mirostat_eta": req.Options.MirostatEta,
  507. "penalize_nl": req.Options.PenalizeNewline,
  508. "seed": req.Options.Seed,
  509. "stop": req.Options.Stop,
  510. "image_data": req.Images,
  511. "cache_prompt": true,
  512. }
  513. // Make sure the server is ready
  514. status, err := s.getServerStatus(ctx)
  515. if err != nil {
  516. return err
  517. } else if status != ServerStatusReady {
  518. return fmt.Errorf("unexpected server status: %s", status.ToString())
  519. }
  520. if req.Format == "json" {
  521. request["grammar"] = jsonGrammar
  522. if !strings.Contains(strings.ToLower(req.Prompt), "json") {
  523. slog.Warn("Prompt does not specify that the LLM should response in JSON, but JSON format is expected. For best results specify that JSON is expected in the system prompt.")
  524. }
  525. }
  526. retryDelay := 100 * time.Microsecond
  527. for retries := 0; retries < maxRetries; retries++ {
  528. if retries > 0 {
  529. time.Sleep(retryDelay) // wait before retrying
  530. retryDelay *= 2 // exponential backoff
  531. }
  532. // Handling JSON marshaling with special characters unescaped.
  533. buffer := &bytes.Buffer{}
  534. enc := json.NewEncoder(buffer)
  535. enc.SetEscapeHTML(false)
  536. if err := enc.Encode(request); err != nil {
  537. return fmt.Errorf("failed to marshal data: %v", err)
  538. }
  539. endpoint := fmt.Sprintf("http://127.0.0.1:%d/completion", s.port)
  540. req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, buffer)
  541. if err != nil {
  542. return fmt.Errorf("error creating POST request: %v", err)
  543. }
  544. req.Header.Set("Content-Type", "application/json")
  545. resp, err := http.DefaultClient.Do(req)
  546. if err != nil {
  547. return fmt.Errorf("POST predict: %v", err)
  548. }
  549. defer resp.Body.Close()
  550. if resp.StatusCode >= 400 {
  551. bodyBytes, err := io.ReadAll(resp.Body)
  552. if err != nil {
  553. return fmt.Errorf("failed reading llm error response: %w", err)
  554. }
  555. log.Printf("llm predict error: %s", bodyBytes)
  556. return fmt.Errorf("%s", bodyBytes)
  557. }
  558. scanner := bufio.NewScanner(resp.Body)
  559. buf := make([]byte, 0, maxBufferSize)
  560. scanner.Buffer(buf, maxBufferSize)
  561. retryNeeded := false
  562. // keep track of the last token generated, this is used to abort if the model starts looping
  563. var lastToken string
  564. var tokenRepeat int
  565. for scanner.Scan() {
  566. select {
  567. case <-ctx.Done():
  568. // This handles the request cancellation
  569. return ctx.Err()
  570. default:
  571. line := scanner.Bytes()
  572. if len(line) == 0 {
  573. continue
  574. }
  575. // try again on slot unavailable
  576. if bytes.Contains(line, []byte("slot unavailable")) {
  577. retryNeeded = true
  578. break
  579. }
  580. evt, ok := bytes.CutPrefix(line, []byte("data: "))
  581. if !ok {
  582. return fmt.Errorf("error parsing llm response stream: %s", line)
  583. }
  584. var c completion
  585. if err := json.Unmarshal(evt, &c); err != nil {
  586. return fmt.Errorf("error unmarshaling llm prediction response: %v", err)
  587. }
  588. switch {
  589. case strings.TrimSpace(c.Content) == lastToken:
  590. tokenRepeat++
  591. default:
  592. lastToken = strings.TrimSpace(c.Content)
  593. tokenRepeat = 0
  594. }
  595. // 30 picked as an arbitrary max token repeat limit, modify as needed
  596. if tokenRepeat > 30 {
  597. slog.Debug("prediction aborted, token repeat limit reached")
  598. return ctx.Err()
  599. }
  600. if c.Content != "" {
  601. fn(CompletionResponse{
  602. Content: c.Content,
  603. })
  604. }
  605. if c.Stop {
  606. fn(CompletionResponse{
  607. Done: true,
  608. PromptEvalCount: c.Timings.PromptN,
  609. PromptEvalDuration: parseDurationMs(c.Timings.PromptMS),
  610. EvalCount: c.Timings.PredictedN,
  611. EvalDuration: parseDurationMs(c.Timings.PredictedMS),
  612. })
  613. return nil
  614. }
  615. }
  616. }
  617. if err := scanner.Err(); err != nil {
  618. if strings.Contains(err.Error(), "unexpected EOF") {
  619. s.Close()
  620. msg := ""
  621. if s.status != nil && s.status.LastErrMsg != "" {
  622. msg = s.status.LastErrMsg
  623. }
  624. return fmt.Errorf("an unknown error was encountered while running the model %s", msg)
  625. }
  626. return fmt.Errorf("error reading llm response: %v", err)
  627. }
  628. if !retryNeeded {
  629. return nil // success
  630. }
  631. }
  632. // should never reach here ideally
  633. return fmt.Errorf("max retries exceeded")
  634. }
  635. type EmbeddingsRequest struct {
  636. Contents []string `json:"contents"`
  637. }
  638. type EmbeddingsResponse struct {
  639. Embeddings [][]float64 `json:"embeddings"`
  640. }
  641. func (s *llmServer) Embeddings(ctx context.Context, prompts []string) ([][]float64, error) {
  642. if err := s.sem.Acquire(ctx, 1); err != nil {
  643. slog.Error("Failed to acquire semaphore", "error", err)
  644. return nil, err
  645. }
  646. defer s.sem.Release(1)
  647. // Make sure the server is ready
  648. status, err := s.getServerStatus(ctx)
  649. if err != nil {
  650. return nil, err
  651. } else if status != ServerStatusReady {
  652. return nil, fmt.Errorf("unexpected server status: %s", status.ToString())
  653. }
  654. data, err := json.Marshal(EmbeddingsRequest{Contents: prompts})
  655. if err != nil {
  656. return nil, fmt.Errorf("error marshaling embed data: %w", err)
  657. }
  658. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/embeddings", s.port), bytes.NewBuffer(data))
  659. if err != nil {
  660. return nil, fmt.Errorf("error creating embed request: %w", err)
  661. }
  662. req.Header.Set("Content-Type", "application/json")
  663. resp, err := http.DefaultClient.Do(req)
  664. if err != nil {
  665. return nil, fmt.Errorf("do embedding request: %w", err)
  666. }
  667. defer resp.Body.Close()
  668. body, err := io.ReadAll(resp.Body)
  669. if err != nil {
  670. return nil, fmt.Errorf("error reading embed response: %w", err)
  671. }
  672. fmt.Println("embeddings response", string(body))
  673. if resp.StatusCode >= 400 {
  674. log.Printf("llm encode error: %s", body)
  675. return nil, fmt.Errorf("%s", body)
  676. }
  677. var embedding EmbeddingsResponse
  678. if err := json.Unmarshal(body, &embedding); err != nil {
  679. return nil, fmt.Errorf("unmarshal tokenize response: %w", err)
  680. }
  681. return embedding.Embeddings, nil
  682. }
  683. type TokenizeRequest struct {
  684. Content string `json:"content"`
  685. }
  686. type TokenizeResponse struct {
  687. Tokens []int `json:"tokens"`
  688. }
  689. func (s *llmServer) Tokenize(ctx context.Context, content string) ([]int, error) {
  690. // Make sure the server is ready
  691. status, err := s.getServerStatus(ctx)
  692. if err != nil {
  693. return nil, err
  694. } else if status != ServerStatusReady && status != ServerStatusNoSlotsAvaialble {
  695. return nil, fmt.Errorf("unexpected server status: %s", status.ToString())
  696. }
  697. data, err := json.Marshal(TokenizeRequest{Content: content})
  698. if err != nil {
  699. return nil, fmt.Errorf("marshaling encode data: %w", err)
  700. }
  701. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/tokenize", s.port), bytes.NewBuffer(data))
  702. if err != nil {
  703. return nil, fmt.Errorf("encode request: %w", err)
  704. }
  705. req.Header.Set("Content-Type", "application/json")
  706. resp, err := http.DefaultClient.Do(req)
  707. if err != nil {
  708. return nil, fmt.Errorf("do encode request: %w", err)
  709. }
  710. defer resp.Body.Close()
  711. body, err := io.ReadAll(resp.Body)
  712. if err != nil {
  713. return nil, fmt.Errorf("read encode request: %w", err)
  714. }
  715. if resp.StatusCode >= 400 {
  716. log.Printf("llm encode error: %s", body)
  717. return nil, fmt.Errorf("%s", body)
  718. }
  719. var encoded TokenizeResponse
  720. if err := json.Unmarshal(body, &encoded); err != nil {
  721. return nil, fmt.Errorf("unmarshal encode response: %w", err)
  722. }
  723. return encoded.Tokens, nil
  724. }
  725. type DetokenizeRequest struct {
  726. Tokens []int `json:"tokens"`
  727. }
  728. type DetokenizeResponse struct {
  729. Content string `json:"content"`
  730. }
  731. func (s *llmServer) Detokenize(ctx context.Context, tokens []int) (string, error) {
  732. // Make sure the server is ready
  733. status, err := s.getServerStatus(ctx)
  734. if err != nil {
  735. return "", err
  736. } else if status != ServerStatusReady && status != ServerStatusNoSlotsAvaialble {
  737. return "", fmt.Errorf("unexpected server status: %s", status.ToString())
  738. }
  739. data, err := json.Marshal(DetokenizeRequest{Tokens: tokens})
  740. if err != nil {
  741. return "", fmt.Errorf("marshaling decode data: %w", err)
  742. }
  743. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/detokenize", s.port), bytes.NewBuffer(data))
  744. if err != nil {
  745. return "", fmt.Errorf("decode request: %w", err)
  746. }
  747. req.Header.Set("Content-Type", "application/json")
  748. resp, err := http.DefaultClient.Do(req)
  749. if err != nil {
  750. return "", fmt.Errorf("do decode request: %w", err)
  751. }
  752. defer resp.Body.Close()
  753. body, err := io.ReadAll(resp.Body)
  754. if err != nil {
  755. return "", fmt.Errorf("read decode request: %w", err)
  756. }
  757. if resp.StatusCode >= 400 {
  758. log.Printf("llm decode error: %s", body)
  759. return "", fmt.Errorf("%s", body)
  760. }
  761. var decoded DetokenizeResponse
  762. if err := json.Unmarshal(body, &decoded); err != nil {
  763. return "", fmt.Errorf("unmarshal encode response: %w", err)
  764. }
  765. return decoded.Content, nil
  766. }
  767. func (s *llmServer) Close() error {
  768. if s.cmd != nil {
  769. slog.Debug("stopping llama server")
  770. return s.cmd.Process.Kill()
  771. }
  772. return nil
  773. }
  774. func (s *llmServer) EstimatedVRAM() uint64 {
  775. return s.estimatedVRAM
  776. }
  777. func parseDurationMs(ms float64) time.Duration {
  778. dur, err := time.ParseDuration(fmt.Sprintf("%fms", ms))
  779. if err != nil {
  780. panic(err)
  781. }
  782. return dur
  783. }