server.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  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. expiresAt := time.Now().Add(3 * time.Minute) // be generous with timeout, large models can take a while to load
  323. ticker := time.NewTicker(50 * time.Millisecond)
  324. defer ticker.Stop()
  325. slog.Info("waiting for llama runner to start responding")
  326. var lastStatus ServerStatus = -1
  327. for {
  328. select {
  329. case err := <-s.done:
  330. msg := ""
  331. if s.status != nil && s.status.LastErrMsg != "" {
  332. msg = s.status.LastErrMsg
  333. }
  334. return fmt.Errorf("llama runner process has terminated: %v %s", err, msg)
  335. case <-ticker.C:
  336. if time.Now().After(expiresAt) {
  337. // timeout
  338. msg := ""
  339. if s.status != nil && s.status.LastErrMsg != "" {
  340. msg = s.status.LastErrMsg
  341. }
  342. return fmt.Errorf("timed out waiting for llama runner to start: %s", msg)
  343. }
  344. if s.cmd.ProcessState != nil {
  345. msg := ""
  346. if s.status != nil && s.status.LastErrMsg != "" {
  347. msg = s.status.LastErrMsg
  348. }
  349. return fmt.Errorf("llama runner process no longer running: %d %s", s.cmd.ProcessState.ExitCode(), msg)
  350. }
  351. ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
  352. defer cancel()
  353. status, err := s.getServerStatus(ctx)
  354. if err != nil && lastStatus != status {
  355. slog.Debug("server not yet available", "error", err)
  356. lastStatus = status
  357. continue
  358. }
  359. switch status {
  360. case ServerStatusLoadingModel:
  361. // TODO - this state never seems to happen with the current server.cpp code (bug?)
  362. // it doesn't respond to the health endpoint until after the model is loaded
  363. slog.Debug("loading model")
  364. case ServerStatusReady:
  365. slog.Debug(fmt.Sprintf("llama runner started in %f seconds", time.Since(start).Seconds()))
  366. return nil
  367. }
  368. }
  369. }
  370. }
  371. const jsonGrammar = `
  372. root ::= object
  373. value ::= object | array | string | number | ("true" | "false" | "null") ws
  374. object ::=
  375. "{" ws (
  376. string ":" ws value
  377. ("," ws string ":" ws value)*
  378. )? "}" ws
  379. array ::=
  380. "[" ws (
  381. value
  382. ("," ws value)*
  383. )? "]" ws
  384. string ::=
  385. "\"" (
  386. [^"\\] |
  387. "\\" (["\\/bfnrt] | "u" [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F]) # escapes
  388. )* "\"" ws
  389. number ::= ("-"? ([0-9] | [1-9] [0-9]*)) ("." [0-9]+)? ([eE] [-+]? [0-9]+)? ws
  390. # Optional space: by convention, applied in this grammar after literal chars when allowed
  391. ws ::= ([ \t\n] ws)?
  392. `
  393. const maxBufferSize = 512 * format.KiloByte
  394. const maxRetries = 3
  395. type ImageData struct {
  396. Data []byte `json:"data"`
  397. ID int `json:"id"`
  398. }
  399. type completion struct {
  400. Content string `json:"content"`
  401. Model string `json:"model"`
  402. Prompt string `json:"prompt"`
  403. Stop bool `json:"stop"`
  404. Timings struct {
  405. PredictedN int `json:"predicted_n"`
  406. PredictedMS float64 `json:"predicted_ms"`
  407. PromptN int `json:"prompt_n"`
  408. PromptMS float64 `json:"prompt_ms"`
  409. }
  410. }
  411. type CompletionRequest struct {
  412. Prompt string
  413. Format string
  414. Images []ImageData
  415. Options api.Options
  416. }
  417. type CompletionResponse struct {
  418. Content string
  419. Done bool
  420. PromptEvalCount int
  421. PromptEvalDuration time.Duration
  422. EvalCount int
  423. EvalDuration time.Duration
  424. }
  425. func (s *LlamaServer) Completion(ctx context.Context, req CompletionRequest, fn func(CompletionResponse)) error {
  426. request := map[string]any{
  427. "prompt": req.Prompt,
  428. "stream": true,
  429. "n_predict": req.Options.NumPredict,
  430. "n_keep": req.Options.NumKeep,
  431. "main_gpu": req.Options.MainGPU,
  432. "temperature": req.Options.Temperature,
  433. "top_k": req.Options.TopK,
  434. "top_p": req.Options.TopP,
  435. "tfs_z": req.Options.TFSZ,
  436. "typical_p": req.Options.TypicalP,
  437. "repeat_last_n": req.Options.RepeatLastN,
  438. "repeat_penalty": req.Options.RepeatPenalty,
  439. "presence_penalty": req.Options.PresencePenalty,
  440. "frequency_penalty": req.Options.FrequencyPenalty,
  441. "mirostat": req.Options.Mirostat,
  442. "mirostat_tau": req.Options.MirostatTau,
  443. "mirostat_eta": req.Options.MirostatEta,
  444. "penalize_nl": req.Options.PenalizeNewline,
  445. "seed": req.Options.Seed,
  446. "stop": req.Options.Stop,
  447. "image_data": req.Images,
  448. "cache_prompt": true,
  449. }
  450. // Make sure the server is ready
  451. status, err := s.getServerStatus(ctx)
  452. if err != nil {
  453. return err
  454. } else if status != ServerStatusReady {
  455. return fmt.Errorf("unexpected server status: %d", status)
  456. }
  457. if req.Format == "json" {
  458. request["grammar"] = jsonGrammar
  459. if !strings.Contains(strings.ToLower(req.Prompt), "json") {
  460. 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.")
  461. }
  462. }
  463. retryDelay := 100 * time.Microsecond
  464. for retries := 0; retries < maxRetries; retries++ {
  465. if retries > 0 {
  466. time.Sleep(retryDelay) // wait before retrying
  467. retryDelay *= 2 // exponential backoff
  468. }
  469. // Handling JSON marshaling with special characters unescaped.
  470. buffer := &bytes.Buffer{}
  471. enc := json.NewEncoder(buffer)
  472. enc.SetEscapeHTML(false)
  473. if err := enc.Encode(request); err != nil {
  474. return fmt.Errorf("failed to marshal data: %v", err)
  475. }
  476. endpoint := fmt.Sprintf("http://127.0.0.1:%d/completion", s.port)
  477. req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, buffer)
  478. if err != nil {
  479. return fmt.Errorf("error creating POST request: %v", err)
  480. }
  481. req.Header.Set("Content-Type", "application/json")
  482. resp, err := http.DefaultClient.Do(req)
  483. if err != nil {
  484. return fmt.Errorf("POST predict: %v", err)
  485. }
  486. defer resp.Body.Close()
  487. if resp.StatusCode >= 400 {
  488. bodyBytes, err := io.ReadAll(resp.Body)
  489. if err != nil {
  490. return fmt.Errorf("failed reading llm error response: %w", err)
  491. }
  492. log.Printf("llm predict error: %s", bodyBytes)
  493. return fmt.Errorf("%s", bodyBytes)
  494. }
  495. scanner := bufio.NewScanner(resp.Body)
  496. buf := make([]byte, 0, maxBufferSize)
  497. scanner.Buffer(buf, maxBufferSize)
  498. retryNeeded := false
  499. // keep track of the last token generated, this is used to abort if the model starts looping
  500. var lastToken string
  501. var tokenRepeat int
  502. for scanner.Scan() {
  503. select {
  504. case <-ctx.Done():
  505. // This handles the request cancellation
  506. return ctx.Err()
  507. default:
  508. line := scanner.Bytes()
  509. if len(line) == 0 {
  510. continue
  511. }
  512. // try again on slot unavailable
  513. if bytes.Contains(line, []byte("slot unavailable")) {
  514. retryNeeded = true
  515. break
  516. }
  517. evt, ok := bytes.CutPrefix(line, []byte("data: "))
  518. if !ok {
  519. return fmt.Errorf("error parsing llm response stream: %s", line)
  520. }
  521. var c completion
  522. if err := json.Unmarshal(evt, &c); err != nil {
  523. return fmt.Errorf("error unmarshaling llm prediction response: %v", err)
  524. }
  525. switch {
  526. case strings.TrimSpace(c.Content) == lastToken:
  527. tokenRepeat++
  528. default:
  529. lastToken = strings.TrimSpace(c.Content)
  530. tokenRepeat = 0
  531. }
  532. // 30 picked as an arbitrary max token repeat limit, modify as needed
  533. if tokenRepeat > 30 {
  534. slog.Debug("prediction aborted, token repeat limit reached")
  535. return ctx.Err()
  536. }
  537. if c.Content != "" {
  538. fn(CompletionResponse{
  539. Content: c.Content,
  540. })
  541. }
  542. if c.Stop {
  543. fn(CompletionResponse{
  544. Done: true,
  545. PromptEvalCount: c.Timings.PromptN,
  546. PromptEvalDuration: parseDurationMs(c.Timings.PromptMS),
  547. EvalCount: c.Timings.PredictedN,
  548. EvalDuration: parseDurationMs(c.Timings.PredictedMS),
  549. })
  550. return nil
  551. }
  552. }
  553. }
  554. if err := scanner.Err(); err != nil {
  555. if strings.Contains(err.Error(), "unexpected EOF") {
  556. s.Close()
  557. msg := ""
  558. if s.status != nil && s.status.LastErrMsg != "" {
  559. msg = s.status.LastErrMsg
  560. }
  561. return fmt.Errorf("an unknown error was encountered while running the model %s", msg)
  562. }
  563. return fmt.Errorf("error reading llm response: %v", err)
  564. }
  565. if !retryNeeded {
  566. return nil // success
  567. }
  568. }
  569. // should never reach here ideally
  570. return fmt.Errorf("max retries exceeded")
  571. }
  572. type EmbeddingRequest struct {
  573. Content string `json:"content"`
  574. }
  575. type EmbeddingResponse struct {
  576. Embedding []float64 `json:"embedding"`
  577. }
  578. func (s *LlamaServer) Embedding(ctx context.Context, prompt string) ([]float64, error) {
  579. // Make sure the server is ready
  580. status, err := s.getServerStatus(ctx)
  581. if err != nil {
  582. return nil, err
  583. } else if status != ServerStatusReady {
  584. return nil, fmt.Errorf("unexpected server status: %d", status)
  585. }
  586. data, err := json.Marshal(TokenizeRequest{Content: prompt})
  587. if err != nil {
  588. return nil, fmt.Errorf("error marshaling embed data: %w", err)
  589. }
  590. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/embedding", s.port), bytes.NewBuffer(data))
  591. if err != nil {
  592. return nil, fmt.Errorf("error creating embed request: %w", err)
  593. }
  594. req.Header.Set("Content-Type", "application/json")
  595. resp, err := http.DefaultClient.Do(req)
  596. if err != nil {
  597. return nil, fmt.Errorf("do embedding request: %w", err)
  598. }
  599. defer resp.Body.Close()
  600. body, err := io.ReadAll(resp.Body)
  601. if err != nil {
  602. return nil, fmt.Errorf("error reading embed response: %w", err)
  603. }
  604. if resp.StatusCode >= 400 {
  605. log.Printf("llm encode error: %s", body)
  606. return nil, fmt.Errorf("%s", body)
  607. }
  608. var embedding EmbeddingResponse
  609. if err := json.Unmarshal(body, &embedding); err != nil {
  610. return nil, fmt.Errorf("unmarshal tokenize response: %w", err)
  611. }
  612. return embedding.Embedding, nil
  613. }
  614. type TokenizeRequest struct {
  615. Content string `json:"content"`
  616. }
  617. type TokenizeResponse struct {
  618. Tokens []int `json:"tokens"`
  619. }
  620. func (s *LlamaServer) Tokenize(ctx context.Context, content string) ([]int, error) {
  621. // Make sure the server is ready
  622. status, err := s.getServerStatus(ctx)
  623. if err != nil {
  624. return nil, err
  625. } else if status != ServerStatusReady {
  626. return nil, fmt.Errorf("unexpected server status: %d", status)
  627. }
  628. data, err := json.Marshal(TokenizeRequest{Content: content})
  629. if err != nil {
  630. return nil, fmt.Errorf("marshaling encode data: %w", err)
  631. }
  632. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/tokenize", s.port), bytes.NewBuffer(data))
  633. if err != nil {
  634. return nil, fmt.Errorf("encode request: %w", err)
  635. }
  636. req.Header.Set("Content-Type", "application/json")
  637. resp, err := http.DefaultClient.Do(req)
  638. if err != nil {
  639. return nil, fmt.Errorf("do encode request: %w", err)
  640. }
  641. defer resp.Body.Close()
  642. body, err := io.ReadAll(resp.Body)
  643. if err != nil {
  644. return nil, fmt.Errorf("read encode request: %w", err)
  645. }
  646. if resp.StatusCode >= 400 {
  647. log.Printf("llm encode error: %s", body)
  648. return nil, fmt.Errorf("%s", body)
  649. }
  650. var encoded TokenizeResponse
  651. if err := json.Unmarshal(body, &encoded); err != nil {
  652. return nil, fmt.Errorf("unmarshal encode response: %w", err)
  653. }
  654. return encoded.Tokens, nil
  655. }
  656. type DetokenizeRequest struct {
  657. Tokens []int `json:"tokens"`
  658. }
  659. type DetokenizeResponse struct {
  660. Content string `json:"content"`
  661. }
  662. func (s *LlamaServer) Detokenize(ctx context.Context, tokens []int) (string, error) {
  663. // Make sure the server is ready
  664. status, err := s.getServerStatus(ctx)
  665. if err != nil {
  666. return "", err
  667. } else if status != ServerStatusReady {
  668. return "", fmt.Errorf("unexpected server status: %d", status)
  669. }
  670. data, err := json.Marshal(DetokenizeRequest{Tokens: tokens})
  671. if err != nil {
  672. return "", fmt.Errorf("marshaling decode data: %w", err)
  673. }
  674. req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/detokenize", s.port), bytes.NewBuffer(data))
  675. if err != nil {
  676. return "", fmt.Errorf("decode request: %w", err)
  677. }
  678. req.Header.Set("Content-Type", "application/json")
  679. resp, err := http.DefaultClient.Do(req)
  680. if err != nil {
  681. return "", fmt.Errorf("do decode request: %w", err)
  682. }
  683. defer resp.Body.Close()
  684. body, err := io.ReadAll(resp.Body)
  685. if err != nil {
  686. return "", fmt.Errorf("read decode request: %w", err)
  687. }
  688. if resp.StatusCode >= 400 {
  689. log.Printf("llm decode error: %s", body)
  690. return "", fmt.Errorf("%s", body)
  691. }
  692. var decoded DetokenizeResponse
  693. if err := json.Unmarshal(body, &decoded); err != nil {
  694. return "", fmt.Errorf("unmarshal encode response: %w", err)
  695. }
  696. return decoded.Content, nil
  697. }
  698. func (s *LlamaServer) Close() error {
  699. if s.cmd != nil {
  700. slog.Debug("stopping llama server")
  701. return s.cmd.Process.Kill()
  702. }
  703. return nil
  704. }
  705. func parseDurationMs(ms float64) time.Duration {
  706. dur, err := time.ParseDuration(fmt.Sprintf("%fms", ms))
  707. if err != nil {
  708. panic(err)
  709. }
  710. return dur
  711. }