server.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  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. "slices"
  20. "strconv"
  21. "strings"
  22. "time"
  23. "github.com/ollama/ollama/api"
  24. "github.com/ollama/ollama/format"
  25. "github.com/ollama/ollama/gpu"
  26. )
  27. // LlamaServer is an instance of the llama.cpp server
  28. type LlamaServer struct {
  29. port int
  30. cmd *exec.Cmd
  31. done chan error // Channel to signal when the process exits
  32. status *StatusWriter
  33. options api.Options
  34. }
  35. var cpuOnlyFamilies = []string{
  36. "mamba",
  37. }
  38. func NewLlamaServer(model string, adapters, projectors []string, opts api.Options) (*LlamaServer, error) {
  39. if _, err := os.Stat(model); err != nil {
  40. return nil, err
  41. }
  42. f, err := os.Open(model)
  43. if err != nil {
  44. return nil, err
  45. }
  46. defer f.Close()
  47. ggml, _, err := DecodeGGML(f)
  48. if err != nil {
  49. return nil, err
  50. }
  51. if opts.NumCtx > int(ggml.KV().ContextLength()) {
  52. slog.Warn("requested context length is greater than model max context length", "requested", opts.NumCtx, "model", ggml.KV().ContextLength())
  53. opts.NumCtx = int(ggml.KV().ContextLength())
  54. }
  55. if opts.NumCtx < 4 {
  56. opts.NumCtx = 4
  57. }
  58. availableMemory, _ := gpu.CheckVRAM()
  59. info := gpu.GetGPUInfo()
  60. usedMemory := info.MinimumMemory
  61. for _, projector := range projectors {
  62. usedMemory += projectorMemoryRequirements(projector)
  63. // multimodal models require at least 2048 context
  64. opts.NumCtx = max(opts.NumCtx, 2048)
  65. }
  66. // fp16 k,v = (1 (k) + 1 (v)) * sizeof(float16) * n_ctx * n_layer * n_embd / n_head * n_head_kv
  67. kv := 2 * 2 * int64(opts.NumCtx) * int64(ggml.KV().BlockCount()) * int64(ggml.KV().EmbeddingLength()) / int64(ggml.KV().HeadCount()) * int64(ggml.KV().HeadCountKV())
  68. graph, ok := ggml.GraphSize(opts.NumCtx, min(opts.NumCtx, opts.NumBatch))
  69. if !ok {
  70. graph = int64(ggml.KV().GQA()) * kv / 6
  71. }
  72. usedMemory += graph
  73. if (usedMemory > availableMemory || slices.Contains(cpuOnlyFamilies, ggml.KV().Architecture())) && info.Library != "metal" {
  74. info.Library = "cpu"
  75. }
  76. requiredMemory := usedMemory
  77. var layers int
  78. for i := 0; i < int(ggml.KV().BlockCount()); i++ {
  79. layerMemory := ggml.LayerSize(fmt.Sprintf("blk.%d.", i)) + kv/int64(ggml.KV().BlockCount())
  80. requiredMemory += layerMemory
  81. if availableMemory > usedMemory+layerMemory && (opts.NumGPU < 0 || layers < opts.NumGPU) {
  82. usedMemory += layerMemory
  83. layers++
  84. }
  85. }
  86. memOutputLayer := ggml.LayerSize("output.")
  87. requiredMemory += memOutputLayer
  88. // only offload output layer if all repeating layers are offloaded
  89. if layers >= int(ggml.KV().BlockCount()) && availableMemory > usedMemory+memOutputLayer {
  90. usedMemory += memOutputLayer
  91. layers++
  92. }
  93. slog.Info(
  94. "offload to gpu",
  95. "layers", layers,
  96. "required", format.HumanBytes2(requiredMemory),
  97. "used", format.HumanBytes2(usedMemory),
  98. "available", format.HumanBytes2(availableMemory),
  99. "kv", format.HumanBytes2(kv),
  100. "graph", format.HumanBytes2(graph),
  101. )
  102. if opts.NumGPU < 0 && info.Library != "cpu" {
  103. opts.NumGPU = layers
  104. }
  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. servers := serversForGpu(info)
  110. demandLib := os.Getenv("OLLAMA_LLM_LIBRARY")
  111. if demandLib != "" {
  112. serverPath := availableServers[demandLib]
  113. if serverPath == "" {
  114. slog.Info(fmt.Sprintf("Invalid OLLAMA_LLM_LIBRARY %s - not found", demandLib))
  115. } else {
  116. slog.Info("user override", "OLLAMA_LLM_LIBRARY", demandLib, "path", serverPath)
  117. servers = []string{demandLib}
  118. }
  119. }
  120. if len(servers) == 0 {
  121. return nil, fmt.Errorf("no servers found for %v", info)
  122. }
  123. params := []string{
  124. "--model", model,
  125. "--ctx-size", fmt.Sprintf("%d", opts.NumCtx),
  126. "--batch-size", fmt.Sprintf("%d", opts.NumBatch),
  127. "--embedding",
  128. }
  129. if debug := os.Getenv("OLLAMA_DEBUG"); debug != "" {
  130. params = append(params, "--log-format", "json")
  131. } else {
  132. params = append(params, "--log-disable")
  133. }
  134. if opts.NumGPU >= 0 {
  135. params = append(params, "--n-gpu-layers", fmt.Sprintf("%d", opts.NumGPU))
  136. }
  137. if debug := os.Getenv("OLLAMA_DEBUG"); debug != "" {
  138. params = append(params, "--verbose")
  139. }
  140. if opts.MainGPU > 0 {
  141. params = append(params, "--main-gpu", fmt.Sprintf("%d", opts.MainGPU))
  142. }
  143. if len(adapters) > 0 {
  144. // TODO: applying multiple adapters is not supported by the llama.cpp server yet
  145. params = append(params, "--lora", adapters[0])
  146. }
  147. if len(projectors) > 0 {
  148. // TODO: applying multiple projectors is not supported by the llama.cpp server yet
  149. params = append(params, "--mmproj", projectors[0])
  150. }
  151. if opts.NumThread > 0 {
  152. params = append(params, "--threads", fmt.Sprintf("%d", opts.NumThread))
  153. }
  154. if !opts.F16KV {
  155. params = append(params, "--memory-f32")
  156. }
  157. if opts.UseMLock {
  158. params = append(params, "--mlock")
  159. }
  160. if !opts.UseMMap {
  161. params = append(params, "--no-mmap")
  162. }
  163. if opts.UseNUMA {
  164. params = append(params, "--numa")
  165. }
  166. // Loop through potential servers
  167. var finalErr error
  168. for i := 0; i < len(servers); i++ {
  169. dir := availableServers[servers[i]]
  170. // Find an availableServers port, retry on each iterration in case the failure was a port conflict race
  171. port := 0
  172. if a, err := net.ResolveTCPAddr("tcp", "localhost:0"); err == nil {
  173. var l *net.TCPListener
  174. if l, err = net.ListenTCP("tcp", a); err == nil {
  175. port = l.Addr().(*net.TCPAddr).Port
  176. l.Close()
  177. }
  178. }
  179. if port == 0 {
  180. slog.Debug("ResolveTCPAddr failed ", "error", err)
  181. port = rand.Intn(65535-49152) + 49152 // get a random port in the ephemeral range
  182. }
  183. finalParams := append(params, "--port", strconv.Itoa(port))
  184. pathEnv := "LD_LIBRARY_PATH"
  185. if runtime.GOOS == "windows" {
  186. pathEnv = "PATH"
  187. }
  188. // append the server directory to LD_LIBRARY_PATH/PATH
  189. libraryPaths := []string{dir}
  190. if libraryPath, ok := os.LookupEnv(pathEnv); ok {
  191. // Append our runner directory to the path
  192. // This will favor system libraries over our bundled library dependencies
  193. libraryPaths = append(filepath.SplitList(libraryPath), libraryPaths...)
  194. }
  195. server := filepath.Join(dir, "ollama_llama_server")
  196. if runtime.GOOS == "windows" {
  197. server = server + ".exe"
  198. }
  199. s := &LlamaServer{
  200. port: port,
  201. cmd: exec.Command(server, finalParams...),
  202. status: NewStatusWriter(os.Stderr),
  203. options: opts,
  204. }
  205. libEnv := fmt.Sprintf("%s=%s", pathEnv, strings.Join(libraryPaths, string(filepath.ListSeparator)))
  206. slog.Debug(libEnv)
  207. s.cmd.Env = append(os.Environ(), libEnv)
  208. s.cmd.Stdout = os.Stdout
  209. s.cmd.Stderr = s.status
  210. slog.Info("starting llama server", "cmd", s.cmd.String())
  211. if err = s.cmd.Start(); err != nil {
  212. msg := ""
  213. if s.status != nil && s.status.LastErrMsg != "" {
  214. msg = s.status.LastErrMsg
  215. }
  216. err = fmt.Errorf("error starting the external llama server: %v %s", err, msg)
  217. finalErr = err
  218. continue
  219. }
  220. // reap subprocess when it exits
  221. go func() {
  222. // Exit status managed via getServerStatus
  223. _ = s.cmd.Wait()
  224. }()
  225. if err = s.waitUntilRunning(); err != nil {
  226. slog.Error("error starting llama server", "server", servers[i], "error", err)
  227. s.Close()
  228. finalErr = err
  229. continue
  230. }
  231. return s, nil
  232. }
  233. slog.Error("unable to load any llama server", "error", finalErr)
  234. return nil, finalErr
  235. }
  236. func projectorMemoryRequirements(filename string) int64 {
  237. file, err := os.Open(filename)
  238. if err != nil {
  239. return 0
  240. }
  241. defer file.Close()
  242. ggml, _, err := DecodeGGML(file)
  243. if err != nil {
  244. return 0
  245. }
  246. prefixes := make(map[string]struct{})
  247. for _, layer := range ggml.Tensors() {
  248. parts := strings.Split(layer.Name, ".")
  249. prefixes[strings.Join(parts[:2], ".")] = struct{}{}
  250. }
  251. var ask int64
  252. for prefix := range prefixes {
  253. ask += ggml.LayerSize(prefix)
  254. }
  255. return ask
  256. }
  257. type ServerStatus int
  258. const ( // iota is reset to 0
  259. ServerStatusReady ServerStatus = iota
  260. ServerStatusNoSlotsAvaialble
  261. ServerStatusLoadingModel
  262. ServerStatusNotResponding
  263. ServerStatusError
  264. )
  265. type ServerStatusResp struct {
  266. Status string `json:"status"`
  267. SlotsIdle int `json:"slots_idle"`
  268. SlotsProcessing int `json:"slots_processing"`
  269. Error string `json:"error"`
  270. }
  271. func (s *LlamaServer) getServerStatus(ctx context.Context) (ServerStatus, error) {
  272. // Fail fast if its exited
  273. if s.cmd.ProcessState != nil {
  274. msg := ""
  275. if s.status != nil && s.status.LastErrMsg != "" {
  276. msg = s.status.LastErrMsg
  277. }
  278. return ServerStatusError, fmt.Errorf("llama runner process no longer running: %d %s", s.cmd.ProcessState.ExitCode(), msg)
  279. }
  280. req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://127.0.0.1:%d/health", s.port), nil)
  281. if err != nil {
  282. return ServerStatusError, fmt.Errorf("error creating GET request: %v", err)
  283. }
  284. req.Header.Set("Content-Type", "application/json")
  285. resp, err := http.DefaultClient.Do(req)
  286. if err != nil {
  287. if errors.Is(err, context.DeadlineExceeded) {
  288. return ServerStatusNotResponding, fmt.Errorf("server not responding")
  289. }
  290. return ServerStatusError, fmt.Errorf("health resp: %w", err)
  291. }
  292. defer resp.Body.Close()
  293. body, err := io.ReadAll(resp.Body)
  294. if err != nil {
  295. return ServerStatusError, fmt.Errorf("read health request: %w", err)
  296. }
  297. var status ServerStatusResp
  298. if err := json.Unmarshal(body, &status); err != nil {
  299. return ServerStatusError, fmt.Errorf("health unmarshal encode response: %w", err)
  300. }
  301. switch status.Status {
  302. case "ok":
  303. return ServerStatusReady, nil
  304. case "no slot available":
  305. return ServerStatusNoSlotsAvaialble, nil
  306. case "loading model":
  307. return ServerStatusLoadingModel, nil
  308. default:
  309. return ServerStatusError, fmt.Errorf("server error: %+v", status)
  310. }
  311. }
  312. func (s *LlamaServer) Ping(ctx context.Context) error {
  313. _, err := s.getServerStatus(ctx)
  314. if err != nil {
  315. slog.Debug("server unhealthy", "error", err)
  316. return err
  317. }
  318. return nil
  319. }
  320. func (s *LlamaServer) waitUntilRunning() error {
  321. start := time.Now()
  322. // TODO we need to wire up a better way to detect hangs during model load and startup of the server
  323. expiresAt := time.Now().Add(10 * time.Minute) // be generous with timeout, large models can take a while to load
  324. ticker := time.NewTicker(50 * time.Millisecond)
  325. defer ticker.Stop()
  326. slog.Info("waiting for llama runner to start responding")
  327. var lastStatus ServerStatus = -1
  328. for {
  329. select {
  330. case err := <-s.done:
  331. msg := ""
  332. if s.status != nil && s.status.LastErrMsg != "" {
  333. msg = s.status.LastErrMsg
  334. }
  335. return fmt.Errorf("llama runner process has terminated: %v %s", err, msg)
  336. case <-ticker.C:
  337. if time.Now().After(expiresAt) {
  338. // timeout
  339. msg := ""
  340. if s.status != nil && s.status.LastErrMsg != "" {
  341. msg = s.status.LastErrMsg
  342. }
  343. return fmt.Errorf("timed out waiting for llama runner to start: %s", msg)
  344. }
  345. if s.cmd.ProcessState != nil {
  346. msg := ""
  347. if s.status != nil && s.status.LastErrMsg != "" {
  348. msg = s.status.LastErrMsg
  349. }
  350. return fmt.Errorf("llama runner process no longer running: %d %s", s.cmd.ProcessState.ExitCode(), msg)
  351. }
  352. ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
  353. defer cancel()
  354. status, err := s.getServerStatus(ctx)
  355. if err != nil && lastStatus != status {
  356. slog.Debug("server not yet available", "error", err)
  357. lastStatus = status
  358. continue
  359. }
  360. switch status {
  361. case ServerStatusLoadingModel:
  362. // TODO - this state never seems to happen with the current server.cpp code (bug?)
  363. // it doesn't respond to the health endpoint until after the model is loaded
  364. slog.Debug("loading model")
  365. case ServerStatusReady:
  366. slog.Debug(fmt.Sprintf("llama runner started in %f seconds", time.Since(start).Seconds()))
  367. return nil
  368. }
  369. }
  370. }
  371. }
  372. const jsonGrammar = `
  373. root ::= object
  374. value ::= object | array | string | number | ("true" | "false" | "null") ws
  375. object ::=
  376. "{" ws (
  377. string ":" ws value
  378. ("," ws string ":" ws value)*
  379. )? "}" ws
  380. array ::=
  381. "[" ws (
  382. value
  383. ("," ws value)*
  384. )? "]" ws
  385. string ::=
  386. "\"" (
  387. [^"\\] |
  388. "\\" (["\\/bfnrt] | "u" [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F]) # escapes
  389. )* "\"" ws
  390. number ::= ("-"? ([0-9] | [1-9] [0-9]*)) ("." [0-9]+)? ([eE] [-+]? [0-9]+)? ws
  391. # Optional space: by convention, applied in this grammar after literal chars when allowed
  392. ws ::= ([ \t\n] ws)?
  393. `
  394. const maxBufferSize = 512 * format.KiloByte
  395. const maxRetries = 3
  396. type ImageData struct {
  397. Data []byte `json:"data"`
  398. ID int `json:"id"`
  399. }
  400. type completion struct {
  401. Content string `json:"content"`
  402. Model string `json:"model"`
  403. Prompt string `json:"prompt"`
  404. Stop bool `json:"stop"`
  405. Timings struct {
  406. PredictedN int `json:"predicted_n"`
  407. PredictedMS float64 `json:"predicted_ms"`
  408. PromptN int `json:"prompt_n"`
  409. PromptMS float64 `json:"prompt_ms"`
  410. }
  411. }
  412. type CompletionRequest struct {
  413. Prompt string
  414. Format string
  415. Images []ImageData
  416. Options api.Options
  417. }
  418. type CompletionResponse struct {
  419. Content string
  420. Done bool
  421. PromptEvalCount int
  422. PromptEvalDuration time.Duration
  423. EvalCount int
  424. EvalDuration time.Duration
  425. }
  426. func (s *LlamaServer) Completion(ctx context.Context, req CompletionRequest, fn func(CompletionResponse)) error {
  427. request := map[string]any{
  428. "prompt": req.Prompt,
  429. "stream": true,
  430. "n_predict": req.Options.NumPredict,
  431. "n_keep": req.Options.NumKeep,
  432. "main_gpu": req.Options.MainGPU,
  433. "temperature": req.Options.Temperature,
  434. "top_k": req.Options.TopK,
  435. "top_p": req.Options.TopP,
  436. "tfs_z": req.Options.TFSZ,
  437. "typical_p": req.Options.TypicalP,
  438. "repeat_last_n": req.Options.RepeatLastN,
  439. "repeat_penalty": req.Options.RepeatPenalty,
  440. "presence_penalty": req.Options.PresencePenalty,
  441. "frequency_penalty": req.Options.FrequencyPenalty,
  442. "mirostat": req.Options.Mirostat,
  443. "mirostat_tau": req.Options.MirostatTau,
  444. "mirostat_eta": req.Options.MirostatEta,
  445. "penalize_nl": req.Options.PenalizeNewline,
  446. "seed": req.Options.Seed,
  447. "stop": req.Options.Stop,
  448. "image_data": req.Images,
  449. "cache_prompt": true,
  450. }
  451. // Make sure the server is ready
  452. status, err := s.getServerStatus(ctx)
  453. if err != nil {
  454. return err
  455. } else if status != ServerStatusReady {
  456. return fmt.Errorf("unexpected server status: %d", status)
  457. }
  458. if req.Format == "json" {
  459. request["grammar"] = jsonGrammar
  460. if !strings.Contains(strings.ToLower(req.Prompt), "json") {
  461. 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.")
  462. }
  463. }
  464. retryDelay := 100 * time.Microsecond
  465. for retries := 0; retries < maxRetries; retries++ {
  466. if retries > 0 {
  467. time.Sleep(retryDelay) // wait before retrying
  468. retryDelay *= 2 // exponential backoff
  469. }
  470. // Handling JSON marshaling with special characters unescaped.
  471. buffer := &bytes.Buffer{}
  472. enc := json.NewEncoder(buffer)
  473. enc.SetEscapeHTML(false)
  474. if err := enc.Encode(request); err != nil {
  475. return fmt.Errorf("failed to marshal data: %v", err)
  476. }
  477. endpoint := fmt.Sprintf("http://127.0.0.1:%d/completion", s.port)
  478. req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, buffer)
  479. if err != nil {
  480. return fmt.Errorf("error creating POST request: %v", err)
  481. }
  482. req.Header.Set("Content-Type", "application/json")
  483. resp, err := http.DefaultClient.Do(req)
  484. if err != nil {
  485. return fmt.Errorf("POST predict: %v", err)
  486. }
  487. defer resp.Body.Close()
  488. if resp.StatusCode >= 400 {
  489. bodyBytes, err := io.ReadAll(resp.Body)
  490. if err != nil {
  491. return fmt.Errorf("failed reading llm error response: %w", err)
  492. }
  493. log.Printf("llm predict error: %s", bodyBytes)
  494. return fmt.Errorf("%s", bodyBytes)
  495. }
  496. scanner := bufio.NewScanner(resp.Body)
  497. buf := make([]byte, 0, maxBufferSize)
  498. scanner.Buffer(buf, maxBufferSize)
  499. retryNeeded := false
  500. // keep track of the last token generated, this is used to abort if the model starts looping
  501. var lastToken string
  502. var tokenRepeat int
  503. for scanner.Scan() {
  504. select {
  505. case <-ctx.Done():
  506. // This handles the request cancellation
  507. return ctx.Err()
  508. default:
  509. line := scanner.Bytes()
  510. if len(line) == 0 {
  511. continue
  512. }
  513. // try again on slot unavailable
  514. if bytes.Contains(line, []byte("slot unavailable")) {
  515. retryNeeded = true
  516. break
  517. }
  518. evt, ok := bytes.CutPrefix(line, []byte("data: "))
  519. if !ok {
  520. return fmt.Errorf("error parsing llm response stream: %s", line)
  521. }
  522. var c completion
  523. if err := json.Unmarshal(evt, &c); err != nil {
  524. return fmt.Errorf("error unmarshaling llm prediction response: %v", err)
  525. }
  526. switch {
  527. case strings.TrimSpace(c.Content) == lastToken:
  528. tokenRepeat++
  529. default:
  530. lastToken = strings.TrimSpace(c.Content)
  531. tokenRepeat = 0
  532. }
  533. // 30 picked as an arbitrary max token repeat limit, modify as needed
  534. if tokenRepeat > 30 {
  535. slog.Debug("prediction aborted, token repeat limit reached")
  536. return ctx.Err()
  537. }
  538. if c.Content != "" {
  539. fn(CompletionResponse{
  540. Content: c.Content,
  541. })
  542. }
  543. if c.Stop {
  544. fn(CompletionResponse{
  545. Done: true,
  546. PromptEvalCount: c.Timings.PromptN,
  547. PromptEvalDuration: parseDurationMs(c.Timings.PromptMS),
  548. EvalCount: c.Timings.PredictedN,
  549. EvalDuration: parseDurationMs(c.Timings.PredictedMS),
  550. })
  551. return nil
  552. }
  553. }
  554. }
  555. if err := scanner.Err(); err != nil {
  556. if strings.Contains(err.Error(), "unexpected EOF") {
  557. s.Close()
  558. msg := ""
  559. if s.status != nil && s.status.LastErrMsg != "" {
  560. msg = s.status.LastErrMsg
  561. }
  562. return fmt.Errorf("an unknown error was encountered while running the model %s", msg)
  563. }
  564. return fmt.Errorf("error reading llm response: %v", err)
  565. }
  566. if !retryNeeded {
  567. return nil // success
  568. }
  569. }
  570. // should never reach here ideally
  571. return fmt.Errorf("max retries exceeded")
  572. }
  573. type EmbeddingRequest struct {
  574. Content string `json:"content"`
  575. }
  576. type EmbeddingResponse struct {
  577. Embedding []float64 `json:"embedding"`
  578. }
  579. func (s *LlamaServer) Embedding(ctx context.Context, prompt string) ([]float64, error) {
  580. // Make sure the server is ready
  581. status, err := s.getServerStatus(ctx)
  582. if err != nil {
  583. return nil, err
  584. } else if status != ServerStatusReady {
  585. return nil, fmt.Errorf("unexpected server status: %d", status)
  586. }
  587. data, err := json.Marshal(TokenizeRequest{Content: prompt})
  588. if err != nil {
  589. return nil, fmt.Errorf("error marshaling embed data: %w", err)
  590. }
  591. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/embedding", s.port), bytes.NewBuffer(data))
  592. if err != nil {
  593. return nil, fmt.Errorf("error creating embed request: %w", err)
  594. }
  595. req.Header.Set("Content-Type", "application/json")
  596. resp, err := http.DefaultClient.Do(req)
  597. if err != nil {
  598. return nil, fmt.Errorf("do embedding request: %w", err)
  599. }
  600. defer resp.Body.Close()
  601. body, err := io.ReadAll(resp.Body)
  602. if err != nil {
  603. return nil, fmt.Errorf("error reading embed response: %w", err)
  604. }
  605. if resp.StatusCode >= 400 {
  606. log.Printf("llm encode error: %s", body)
  607. return nil, fmt.Errorf("%s", body)
  608. }
  609. var embedding EmbeddingResponse
  610. if err := json.Unmarshal(body, &embedding); err != nil {
  611. return nil, fmt.Errorf("unmarshal tokenize response: %w", err)
  612. }
  613. return embedding.Embedding, nil
  614. }
  615. type TokenizeRequest struct {
  616. Content string `json:"content"`
  617. }
  618. type TokenizeResponse struct {
  619. Tokens []int `json:"tokens"`
  620. }
  621. func (s *LlamaServer) Tokenize(ctx context.Context, content string) ([]int, error) {
  622. // Make sure the server is ready
  623. status, err := s.getServerStatus(ctx)
  624. if err != nil {
  625. return nil, err
  626. } else if status != ServerStatusReady {
  627. return nil, fmt.Errorf("unexpected server status: %d", status)
  628. }
  629. data, err := json.Marshal(TokenizeRequest{Content: content})
  630. if err != nil {
  631. return nil, fmt.Errorf("marshaling encode data: %w", err)
  632. }
  633. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/tokenize", s.port), bytes.NewBuffer(data))
  634. if err != nil {
  635. return nil, fmt.Errorf("encode request: %w", err)
  636. }
  637. req.Header.Set("Content-Type", "application/json")
  638. resp, err := http.DefaultClient.Do(req)
  639. if err != nil {
  640. return nil, fmt.Errorf("do encode request: %w", err)
  641. }
  642. defer resp.Body.Close()
  643. body, err := io.ReadAll(resp.Body)
  644. if err != nil {
  645. return nil, fmt.Errorf("read encode request: %w", err)
  646. }
  647. if resp.StatusCode >= 400 {
  648. log.Printf("llm encode error: %s", body)
  649. return nil, fmt.Errorf("%s", body)
  650. }
  651. var encoded TokenizeResponse
  652. if err := json.Unmarshal(body, &encoded); err != nil {
  653. return nil, fmt.Errorf("unmarshal encode response: %w", err)
  654. }
  655. return encoded.Tokens, nil
  656. }
  657. type DetokenizeRequest struct {
  658. Tokens []int `json:"tokens"`
  659. }
  660. type DetokenizeResponse struct {
  661. Content string `json:"content"`
  662. }
  663. func (s *LlamaServer) Detokenize(ctx context.Context, tokens []int) (string, error) {
  664. // Make sure the server is ready
  665. status, err := s.getServerStatus(ctx)
  666. if err != nil {
  667. return "", err
  668. } else if status != ServerStatusReady {
  669. return "", fmt.Errorf("unexpected server status: %d", status)
  670. }
  671. data, err := json.Marshal(DetokenizeRequest{Tokens: tokens})
  672. if err != nil {
  673. return "", fmt.Errorf("marshaling decode data: %w", err)
  674. }
  675. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/detokenize", s.port), bytes.NewBuffer(data))
  676. if err != nil {
  677. return "", fmt.Errorf("decode request: %w", err)
  678. }
  679. req.Header.Set("Content-Type", "application/json")
  680. resp, err := http.DefaultClient.Do(req)
  681. if err != nil {
  682. return "", fmt.Errorf("do decode request: %w", err)
  683. }
  684. defer resp.Body.Close()
  685. body, err := io.ReadAll(resp.Body)
  686. if err != nil {
  687. return "", fmt.Errorf("read decode request: %w", err)
  688. }
  689. if resp.StatusCode >= 400 {
  690. log.Printf("llm decode error: %s", body)
  691. return "", fmt.Errorf("%s", body)
  692. }
  693. var decoded DetokenizeResponse
  694. if err := json.Unmarshal(body, &decoded); err != nil {
  695. return "", fmt.Errorf("unmarshal encode response: %w", err)
  696. }
  697. return decoded.Content, nil
  698. }
  699. func (s *LlamaServer) Close() error {
  700. if s.cmd != nil {
  701. slog.Debug("stopping llama server")
  702. return s.cmd.Process.Kill()
  703. }
  704. return nil
  705. }
  706. func parseDurationMs(ms float64) time.Duration {
  707. dur, err := time.ParseDuration(fmt.Sprintf("%fms", ms))
  708. if err != nil {
  709. panic(err)
  710. }
  711. return dur
  712. }