server.go 26 KB

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