server.go 26 KB

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