server.go 26 KB

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