server.go 27 KB

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