server.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963
  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("server 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.Stdout = os.Stdout
  251. s.cmd.Stderr = s.status
  252. if v := strings.Join(libraryPaths, string(filepath.ListSeparator)); v != "" {
  253. s.cmd.Env = append(s.cmd.Env, pathEnv+"="+v)
  254. }
  255. if k, v := gpu.GpuInfoList(gpus).GetVisibleDevicesEnv(); k != "" {
  256. s.cmd.Env = append(s.cmd.Env, k+"="+v)
  257. }
  258. for _, ev := range os.Environ() {
  259. if strings.HasPrefix(ev, "CUDA_") ||
  260. strings.HasPrefix(ev, "ROCM_") ||
  261. strings.HasPrefix(ev, "HIP_") ||
  262. strings.HasPrefix(ev, "HSA_") ||
  263. strings.HasPrefix(ev, "GGML_") {
  264. s.cmd.Env = append(s.cmd.Env, ev)
  265. }
  266. }
  267. slog.Info("starting llama server", "cmd", s.cmd.String())
  268. // Log at debug as the environment is inherited and might contain sensitive information
  269. slog.Debug("subprocess", "environment", s.cmd.Env)
  270. if err = s.cmd.Start(); err != nil {
  271. // Detect permission denied and augment them essage about noexec
  272. if errors.Is(err, os.ErrPermission) {
  273. 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)
  274. continue
  275. }
  276. msg := ""
  277. if s.status != nil && s.status.LastErrMsg != "" {
  278. msg = s.status.LastErrMsg
  279. }
  280. err = fmt.Errorf("error starting the external llama server: %v %s", err, msg)
  281. finalErr = err
  282. continue
  283. }
  284. // reap subprocess when it exits
  285. go func() {
  286. s.done <- s.cmd.Wait()
  287. }()
  288. return s, nil
  289. }
  290. slog.Error("unable to load any llama server", "error", finalErr)
  291. return nil, finalErr
  292. }
  293. func projectorMemoryRequirements(filename string) uint64 {
  294. file, err := os.Open(filename)
  295. if err != nil {
  296. return 0
  297. }
  298. defer file.Close()
  299. ggml, _, err := DecodeGGML(file)
  300. if err != nil {
  301. return 0
  302. }
  303. var mem uint64
  304. for _, layer := range ggml.Tensors().Layers() {
  305. mem += layer.size()
  306. }
  307. return mem
  308. }
  309. type ServerStatus int
  310. const ( // iota is reset to 0
  311. ServerStatusReady ServerStatus = iota
  312. ServerStatusNoSlotsAvailable
  313. ServerStatusLoadingModel
  314. ServerStatusNotResponding
  315. ServerStatusError
  316. )
  317. func (s ServerStatus) ToString() string {
  318. switch s {
  319. case ServerStatusReady:
  320. return "llm server ready"
  321. case ServerStatusNoSlotsAvailable:
  322. return "llm busy - no slots available"
  323. case ServerStatusLoadingModel:
  324. return "llm server loading model"
  325. case ServerStatusNotResponding:
  326. return "llm server not responding"
  327. default:
  328. return "llm server error"
  329. }
  330. }
  331. type ServerStatusResp struct {
  332. Status string `json:"status"`
  333. SlotsIdle int `json:"slots_idle"`
  334. SlotsProcessing int `json:"slots_processing"`
  335. Error string `json:"error"`
  336. }
  337. func (s *llmServer) getServerStatus(ctx context.Context) (ServerStatus, error) {
  338. // Fail fast if its exited
  339. if s.cmd.ProcessState != nil {
  340. msg := ""
  341. if s.status != nil && s.status.LastErrMsg != "" {
  342. msg = s.status.LastErrMsg
  343. }
  344. if s.cmd.ProcessState.ExitCode() == -1 {
  345. // Most likely a signal killed it, log some more details to try to help troubleshoot
  346. slog.Warn("llama runner process no longer running", "sys", s.cmd.ProcessState.Sys(), "string", s.cmd.ProcessState.String())
  347. }
  348. return ServerStatusError, fmt.Errorf("llama runner process no longer running: %d %s", s.cmd.ProcessState.ExitCode(), msg)
  349. }
  350. req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://127.0.0.1:%d/health", s.port), nil)
  351. if err != nil {
  352. return ServerStatusError, fmt.Errorf("error creating GET request: %v", err)
  353. }
  354. req.Header.Set("Content-Type", "application/json")
  355. resp, err := http.DefaultClient.Do(req)
  356. if err != nil {
  357. if errors.Is(err, context.DeadlineExceeded) {
  358. return ServerStatusNotResponding, fmt.Errorf("server not responding")
  359. }
  360. return ServerStatusError, fmt.Errorf("health resp: %w", err)
  361. }
  362. defer resp.Body.Close()
  363. body, err := io.ReadAll(resp.Body)
  364. if err != nil {
  365. return ServerStatusError, fmt.Errorf("read health request: %w", err)
  366. }
  367. var status ServerStatusResp
  368. if err := json.Unmarshal(body, &status); err != nil {
  369. return ServerStatusError, fmt.Errorf("health unmarshal encode response: %w", err)
  370. }
  371. switch status.Status {
  372. case "ok":
  373. return ServerStatusReady, nil
  374. case "no slot available":
  375. return ServerStatusNoSlotsAvailable, nil
  376. case "loading model":
  377. return ServerStatusLoadingModel, nil
  378. default:
  379. return ServerStatusError, fmt.Errorf("server error: %+v", status)
  380. }
  381. }
  382. // getServerStatusRetry will retry if ServerStatusNoSlotsAvailable is received
  383. func (s *llmServer) getServerStatusRetry(ctx context.Context) (ServerStatus, error) {
  384. var retries int
  385. for {
  386. status, err := s.getServerStatus(ctx)
  387. if err != nil {
  388. return status, err
  389. }
  390. if status == ServerStatusNoSlotsAvailable {
  391. if retries >= 10 {
  392. return status, fmt.Errorf("no slots available after %d retries", retries)
  393. }
  394. time.Sleep(5 * time.Millisecond)
  395. retries++
  396. continue
  397. }
  398. return status, nil
  399. }
  400. }
  401. func (s *llmServer) Ping(ctx context.Context) error {
  402. _, err := s.getServerStatus(ctx)
  403. if err != nil {
  404. slog.Debug("server unhealthy", "error", err)
  405. return err
  406. }
  407. return nil
  408. }
  409. func (s *llmServer) WaitUntilRunning(ctx context.Context) error {
  410. start := time.Now()
  411. expiresAt := time.Now().Add(10 * time.Minute) // be generous with timeout, large models can take a while to load
  412. slog.Info("waiting for llama runner to start responding")
  413. var lastStatus ServerStatus = -1
  414. for {
  415. select {
  416. case <-ctx.Done():
  417. slog.Info("context expired before server started")
  418. return fmt.Errorf("timed out waiting for llama runner to start: %w", ctx.Err())
  419. case err := <-s.done:
  420. msg := ""
  421. if s.status != nil && s.status.LastErrMsg != "" {
  422. msg = s.status.LastErrMsg
  423. }
  424. return fmt.Errorf("llama runner process has terminated: %v %s", err, msg)
  425. default:
  426. }
  427. if time.Now().After(expiresAt) {
  428. // timeout
  429. msg := ""
  430. if s.status != nil && s.status.LastErrMsg != "" {
  431. msg = s.status.LastErrMsg
  432. }
  433. return fmt.Errorf("timed out waiting for llama runner to start: %s", msg)
  434. }
  435. if s.cmd.ProcessState != nil {
  436. msg := ""
  437. if s.status != nil && s.status.LastErrMsg != "" {
  438. msg = s.status.LastErrMsg
  439. }
  440. return fmt.Errorf("llama runner process no longer running: %d %s", s.cmd.ProcessState.ExitCode(), msg)
  441. }
  442. ctx, cancel := context.WithTimeout(ctx, 200*time.Millisecond)
  443. defer cancel()
  444. status, _ := s.getServerStatus(ctx)
  445. if lastStatus != status && status != ServerStatusReady {
  446. // Only log on status changes
  447. slog.Info("waiting for server to become available", "status", status.ToString())
  448. }
  449. switch status {
  450. case ServerStatusReady:
  451. s.loadDuration = time.Since(start)
  452. slog.Info(fmt.Sprintf("llama runner started in %0.2f seconds", s.loadDuration.Seconds()))
  453. return nil
  454. default:
  455. lastStatus = status
  456. time.Sleep(time.Millisecond * 250)
  457. continue
  458. }
  459. }
  460. }
  461. const jsonGrammar = `
  462. root ::= object
  463. value ::= object | array | string | number | ("true" | "false" | "null") ws
  464. object ::=
  465. "{" ws (
  466. string ":" ws value
  467. ("," ws string ":" ws value)*
  468. )? "}" ws
  469. array ::=
  470. "[" ws (
  471. value
  472. ("," ws value)*
  473. )? "]" ws
  474. string ::=
  475. "\"" (
  476. [^"\\] |
  477. "\\" (["\\/bfnrt] | "u" [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F]) # escapes
  478. )* "\"" ws
  479. number ::= ("-"? ([0-9] | [1-9] [0-9]*)) ("." [0-9]+)? ([eE] [-+]? [0-9]+)? ws
  480. # Optional space: by convention, applied in this grammar after literal chars when allowed
  481. ws ::= ([ \t\n] ws)?
  482. `
  483. const maxBufferSize = 512 * format.KiloByte
  484. type ImageData struct {
  485. Data []byte `json:"data"`
  486. ID int `json:"id"`
  487. }
  488. type completion struct {
  489. Content string `json:"content"`
  490. Model string `json:"model"`
  491. Prompt string `json:"prompt"`
  492. Stop bool `json:"stop"`
  493. StoppedLimit bool `json:"stopped_limit"`
  494. Timings struct {
  495. PredictedN int `json:"predicted_n"`
  496. PredictedMS float64 `json:"predicted_ms"`
  497. PromptN int `json:"prompt_n"`
  498. PromptMS float64 `json:"prompt_ms"`
  499. }
  500. }
  501. type CompletionRequest struct {
  502. Prompt string
  503. Format string
  504. Images []ImageData
  505. Options api.Options
  506. }
  507. type CompletionResponse struct {
  508. Content string
  509. DoneReason string
  510. Done bool
  511. PromptEvalCount int
  512. PromptEvalDuration time.Duration
  513. EvalCount int
  514. EvalDuration time.Duration
  515. }
  516. func (s *llmServer) Completion(ctx context.Context, req CompletionRequest, fn func(CompletionResponse)) error {
  517. if err := s.sem.Acquire(ctx, 1); err != nil {
  518. slog.Error("Failed to acquire semaphore", "error", err)
  519. return err
  520. }
  521. defer s.sem.Release(1)
  522. // only allow maximum 10 "context shifts" to avoid infinite generation
  523. if req.Options.NumPredict < 0 || req.Options.NumPredict > 10*s.options.NumCtx {
  524. req.Options.NumPredict = 10 * s.options.NumCtx
  525. slog.Debug("setting token limit to 10x num_ctx", "num_ctx", s.options.NumCtx, "num_predict", req.Options.NumPredict)
  526. }
  527. request := map[string]any{
  528. "prompt": req.Prompt,
  529. "stream": true,
  530. "n_predict": req.Options.NumPredict,
  531. "n_keep": req.Options.NumKeep,
  532. "main_gpu": req.Options.MainGPU,
  533. "temperature": req.Options.Temperature,
  534. "top_k": req.Options.TopK,
  535. "top_p": req.Options.TopP,
  536. "tfs_z": req.Options.TFSZ,
  537. "typical_p": req.Options.TypicalP,
  538. "repeat_last_n": req.Options.RepeatLastN,
  539. "repeat_penalty": req.Options.RepeatPenalty,
  540. "presence_penalty": req.Options.PresencePenalty,
  541. "frequency_penalty": req.Options.FrequencyPenalty,
  542. "mirostat": req.Options.Mirostat,
  543. "mirostat_tau": req.Options.MirostatTau,
  544. "mirostat_eta": req.Options.MirostatEta,
  545. "penalize_nl": req.Options.PenalizeNewline,
  546. "seed": req.Options.Seed,
  547. "stop": req.Options.Stop,
  548. "image_data": req.Images,
  549. "cache_prompt": true,
  550. }
  551. // Make sure the server is ready
  552. status, err := s.getServerStatusRetry(ctx)
  553. if err != nil {
  554. return err
  555. } else if status != ServerStatusReady {
  556. return fmt.Errorf("unexpected server status: %s", status.ToString())
  557. }
  558. if req.Format == "json" {
  559. request["grammar"] = jsonGrammar
  560. if !strings.Contains(strings.ToLower(req.Prompt), "json") {
  561. 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.")
  562. }
  563. }
  564. // Handling JSON marshaling with special characters unescaped.
  565. buffer := &bytes.Buffer{}
  566. enc := json.NewEncoder(buffer)
  567. enc.SetEscapeHTML(false)
  568. if err := enc.Encode(request); err != nil {
  569. return fmt.Errorf("failed to marshal data: %v", err)
  570. }
  571. endpoint := fmt.Sprintf("http://127.0.0.1:%d/completion", s.port)
  572. serverReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, buffer)
  573. if err != nil {
  574. return fmt.Errorf("error creating POST request: %v", err)
  575. }
  576. serverReq.Header.Set("Content-Type", "application/json")
  577. res, err := http.DefaultClient.Do(serverReq)
  578. if err != nil {
  579. return fmt.Errorf("POST predict: %v", err)
  580. }
  581. defer res.Body.Close()
  582. if res.StatusCode >= 400 {
  583. bodyBytes, err := io.ReadAll(res.Body)
  584. if err != nil {
  585. return fmt.Errorf("failed reading llm error response: %w", err)
  586. }
  587. log.Printf("llm predict error: %s", bodyBytes)
  588. return fmt.Errorf("%s", bodyBytes)
  589. }
  590. scanner := bufio.NewScanner(res.Body)
  591. buf := make([]byte, 0, maxBufferSize)
  592. scanner.Buffer(buf, maxBufferSize)
  593. // keep track of the last token generated, this is used to abort if the model starts looping
  594. var lastToken string
  595. var tokenRepeat int
  596. for scanner.Scan() {
  597. select {
  598. case <-ctx.Done():
  599. // This handles the request cancellation
  600. return ctx.Err()
  601. default:
  602. line := scanner.Bytes()
  603. if len(line) == 0 {
  604. continue
  605. }
  606. evt, ok := bytes.CutPrefix(line, []byte("data: "))
  607. if !ok {
  608. return fmt.Errorf("error parsing llm response stream: %s", line)
  609. }
  610. var c completion
  611. if err := json.Unmarshal(evt, &c); err != nil {
  612. return fmt.Errorf("error unmarshaling llm prediction response: %v", err)
  613. }
  614. switch {
  615. case strings.TrimSpace(c.Content) == lastToken:
  616. tokenRepeat++
  617. default:
  618. lastToken = strings.TrimSpace(c.Content)
  619. tokenRepeat = 0
  620. }
  621. // 30 picked as an arbitrary max token repeat limit, modify as needed
  622. if tokenRepeat > 30 {
  623. slog.Debug("prediction aborted, token repeat limit reached")
  624. return ctx.Err()
  625. }
  626. if c.Content != "" {
  627. fn(CompletionResponse{
  628. Content: c.Content,
  629. })
  630. }
  631. if c.Stop {
  632. doneReason := "stop"
  633. if c.StoppedLimit {
  634. doneReason = "length"
  635. }
  636. fn(CompletionResponse{
  637. Done: true,
  638. DoneReason: doneReason,
  639. PromptEvalCount: c.Timings.PromptN,
  640. PromptEvalDuration: parseDurationMs(c.Timings.PromptMS),
  641. EvalCount: c.Timings.PredictedN,
  642. EvalDuration: parseDurationMs(c.Timings.PredictedMS),
  643. })
  644. return nil
  645. }
  646. }
  647. }
  648. if err := scanner.Err(); err != nil {
  649. if strings.Contains(err.Error(), "unexpected EOF") {
  650. s.Close()
  651. msg := ""
  652. if s.status != nil && s.status.LastErrMsg != "" {
  653. msg = s.status.LastErrMsg
  654. }
  655. return fmt.Errorf("an unknown error was encountered while running the model %s", msg)
  656. }
  657. return fmt.Errorf("error reading llm response: %v", err)
  658. }
  659. return nil
  660. }
  661. type EmbeddingRequest struct {
  662. Content string `json:"content"`
  663. }
  664. type EmbeddingResponse struct {
  665. Embedding []float64 `json:"embedding"`
  666. }
  667. func (s *llmServer) Embedding(ctx context.Context, prompt string) ([]float64, error) {
  668. if err := s.sem.Acquire(ctx, 1); err != nil {
  669. slog.Error("Failed to acquire semaphore", "error", err)
  670. return nil, err
  671. }
  672. defer s.sem.Release(1)
  673. // Make sure the server is ready
  674. status, err := s.getServerStatusRetry(ctx)
  675. if err != nil {
  676. return nil, err
  677. } else if status != ServerStatusReady {
  678. return nil, fmt.Errorf("unexpected server status: %s", status.ToString())
  679. }
  680. data, err := json.Marshal(TokenizeRequest{Content: prompt})
  681. if err != nil {
  682. return nil, fmt.Errorf("error marshaling embed data: %w", err)
  683. }
  684. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/embedding", s.port), bytes.NewBuffer(data))
  685. if err != nil {
  686. return nil, fmt.Errorf("error creating embed request: %w", err)
  687. }
  688. req.Header.Set("Content-Type", "application/json")
  689. resp, err := http.DefaultClient.Do(req)
  690. if err != nil {
  691. return nil, fmt.Errorf("do embedding request: %w", err)
  692. }
  693. defer resp.Body.Close()
  694. body, err := io.ReadAll(resp.Body)
  695. if err != nil {
  696. return nil, fmt.Errorf("error reading embed response: %w", err)
  697. }
  698. if resp.StatusCode >= 400 {
  699. log.Printf("llm encode error: %s", body)
  700. return nil, fmt.Errorf("%s", body)
  701. }
  702. var embedding EmbeddingResponse
  703. if err := json.Unmarshal(body, &embedding); err != nil {
  704. return nil, fmt.Errorf("unmarshal tokenize response: %w", err)
  705. }
  706. return embedding.Embedding, nil
  707. }
  708. type TokenizeRequest struct {
  709. Content string `json:"content"`
  710. }
  711. type TokenizeResponse struct {
  712. Tokens []int `json:"tokens"`
  713. }
  714. func (s *llmServer) Tokenize(ctx context.Context, content string) ([]int, error) {
  715. // Make sure the server is ready
  716. status, err := s.getServerStatus(ctx)
  717. if err != nil {
  718. return nil, err
  719. } else if status != ServerStatusReady && status != ServerStatusNoSlotsAvailable {
  720. return nil, fmt.Errorf("unexpected server status: %s", status.ToString())
  721. }
  722. data, err := json.Marshal(TokenizeRequest{Content: content})
  723. if err != nil {
  724. return nil, fmt.Errorf("marshaling encode data: %w", err)
  725. }
  726. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/tokenize", s.port), bytes.NewBuffer(data))
  727. if err != nil {
  728. return nil, fmt.Errorf("encode request: %w", err)
  729. }
  730. req.Header.Set("Content-Type", "application/json")
  731. resp, err := http.DefaultClient.Do(req)
  732. if err != nil {
  733. return nil, fmt.Errorf("do encode request: %w", err)
  734. }
  735. defer resp.Body.Close()
  736. body, err := io.ReadAll(resp.Body)
  737. if err != nil {
  738. return nil, fmt.Errorf("read encode request: %w", err)
  739. }
  740. if resp.StatusCode >= 400 {
  741. log.Printf("llm encode error: %s", body)
  742. return nil, fmt.Errorf("%s", body)
  743. }
  744. var encoded TokenizeResponse
  745. if err := json.Unmarshal(body, &encoded); err != nil {
  746. return nil, fmt.Errorf("unmarshal encode response: %w", err)
  747. }
  748. return encoded.Tokens, nil
  749. }
  750. type DetokenizeRequest struct {
  751. Tokens []int `json:"tokens"`
  752. }
  753. type DetokenizeResponse struct {
  754. Content string `json:"content"`
  755. }
  756. func (s *llmServer) Detokenize(ctx context.Context, tokens []int) (string, error) {
  757. // Make sure the server is ready
  758. status, err := s.getServerStatus(ctx)
  759. if err != nil {
  760. return "", err
  761. } else if status != ServerStatusReady && status != ServerStatusNoSlotsAvailable {
  762. return "", fmt.Errorf("unexpected server status: %s", status.ToString())
  763. }
  764. data, err := json.Marshal(DetokenizeRequest{Tokens: tokens})
  765. if err != nil {
  766. return "", fmt.Errorf("marshaling decode data: %w", err)
  767. }
  768. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/detokenize", s.port), bytes.NewBuffer(data))
  769. if err != nil {
  770. return "", fmt.Errorf("decode request: %w", err)
  771. }
  772. req.Header.Set("Content-Type", "application/json")
  773. resp, err := http.DefaultClient.Do(req)
  774. if err != nil {
  775. return "", fmt.Errorf("do decode request: %w", err)
  776. }
  777. defer resp.Body.Close()
  778. body, err := io.ReadAll(resp.Body)
  779. if err != nil {
  780. return "", fmt.Errorf("read decode request: %w", err)
  781. }
  782. if resp.StatusCode >= 400 {
  783. log.Printf("llm decode error: %s", body)
  784. return "", fmt.Errorf("%s", body)
  785. }
  786. var decoded DetokenizeResponse
  787. if err := json.Unmarshal(body, &decoded); err != nil {
  788. return "", fmt.Errorf("unmarshal encode response: %w", err)
  789. }
  790. return decoded.Content, nil
  791. }
  792. func (s *llmServer) Close() error {
  793. if s.cmd != nil {
  794. slog.Debug("stopping llama server")
  795. if err := s.cmd.Process.Kill(); err != nil {
  796. return err
  797. }
  798. // if ProcessState is already populated, Wait already completed, no need to wait again
  799. if s.cmd.ProcessState == nil {
  800. slog.Debug("waiting for llama server to exit")
  801. <-s.done
  802. }
  803. slog.Debug("llama server stopped")
  804. }
  805. return nil
  806. }
  807. func (s *llmServer) EstimatedVRAM() uint64 {
  808. return s.estimatedVRAM
  809. }
  810. func parseDurationMs(ms float64) time.Duration {
  811. dur, err := time.ParseDuration(fmt.Sprintf("%fms", ms))
  812. if err != nil {
  813. panic(err)
  814. }
  815. return dur
  816. }