server.go 27 KB

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