server.go 27 KB

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