server.go 25 KB

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