llama.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  1. package llm
  2. import (
  3. "bufio"
  4. "bytes"
  5. "context"
  6. "embed"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "io/fs"
  12. "log"
  13. "math/rand"
  14. "net/http"
  15. "os"
  16. "os/exec"
  17. "path"
  18. "path/filepath"
  19. "runtime"
  20. "strconv"
  21. "strings"
  22. "time"
  23. "github.com/jmorganca/ollama/api"
  24. )
  25. //go:embed llama.cpp/*/build/*/bin/*
  26. var llamaCppEmbed embed.FS
  27. type ModelRunner struct {
  28. Path string // path to the model runner executable
  29. }
  30. func chooseRunners(runnerType string) []ModelRunner {
  31. buildPath := path.Join("llama.cpp", runnerType, "build")
  32. var runners []string
  33. // set the runners based on the OS
  34. // IMPORTANT: the order of the runners in the array is the priority order
  35. switch runtime.GOOS {
  36. case "darwin":
  37. runners = []string{
  38. path.Join(buildPath, "metal", "bin", "server"),
  39. path.Join(buildPath, "cpu", "bin", "server"),
  40. }
  41. case "linux":
  42. runners = []string{
  43. path.Join(buildPath, "cuda", "bin", "server"),
  44. path.Join(buildPath, "cpu", "bin", "server"),
  45. }
  46. case "windows":
  47. // TODO: select windows GPU runner here when available
  48. runners = []string{
  49. path.Join(buildPath, "cpu", "bin", "Release", "server.exe"),
  50. }
  51. default:
  52. log.Printf("unknown OS, running on CPU: %s", runtime.GOOS)
  53. runners = []string{
  54. path.Join(buildPath, "cpu", "bin", "server"),
  55. }
  56. }
  57. // copy the files locally to run the llama.cpp server
  58. tmpDir, err := os.MkdirTemp("", "llama-*")
  59. if err != nil {
  60. log.Fatalf("load llama runner: failed to create temp dir: %v", err)
  61. }
  62. runnerAvailable := false // if no runner files are found in the embed, this flag will cause a fast fail
  63. for _, r := range runners {
  64. // find all the files in the runner's bin directory
  65. files, err := fs.Glob(llamaCppEmbed, filepath.Join(filepath.Dir(r), "*"))
  66. if err != nil {
  67. // this is expected, ollama may be compiled without all runners packed in
  68. log.Printf("%s runner not found: %v", r, err)
  69. continue
  70. }
  71. runnerAvailable = true
  72. for _, f := range files {
  73. srcFile, err := llamaCppEmbed.Open(f)
  74. if err != nil {
  75. log.Fatalf("read llama runner %s: %v", f, err)
  76. }
  77. defer srcFile.Close()
  78. // create the directory in case it does not exist
  79. destPath := filepath.Join(tmpDir, filepath.Dir(f))
  80. if err := os.MkdirAll(destPath, 0o755); err != nil {
  81. log.Fatalf("create runner temp dir %s: %v", filepath.Dir(f), err)
  82. }
  83. destFile, err := os.OpenFile(filepath.Join(destPath, filepath.Base(f)), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o755)
  84. if err != nil {
  85. log.Fatalf("write llama runner %s: %v", f, err)
  86. }
  87. defer destFile.Close()
  88. if _, err := io.Copy(destFile, srcFile); err != nil {
  89. log.Fatalf("copy llama runner %s: %v", f, err)
  90. }
  91. }
  92. }
  93. if !runnerAvailable {
  94. log.Fatalf("%s runner not found", runnerType)
  95. }
  96. // return the runners to try in priority order
  97. localRunnersByPriority := []ModelRunner{}
  98. for _, r := range runners {
  99. localRunnersByPriority = append(localRunnersByPriority, ModelRunner{Path: path.Join(tmpDir, r)})
  100. }
  101. return localRunnersByPriority
  102. }
  103. type llamaModel struct {
  104. hyperparameters llamaHyperparameters
  105. }
  106. func (llm *llamaModel) ModelFamily() string {
  107. return "llama"
  108. }
  109. func llamaModelType(numLayer uint32) string {
  110. switch numLayer {
  111. case 26:
  112. return "3B"
  113. case 32:
  114. return "7B"
  115. case 40:
  116. return "13B"
  117. case 48:
  118. return "34B"
  119. case 60:
  120. return "30B"
  121. case 80:
  122. return "65B"
  123. default:
  124. return "Unknown"
  125. }
  126. }
  127. func (llm *llamaModel) ModelType() string {
  128. return llamaModelType(llm.hyperparameters.NumLayer)
  129. }
  130. func (llm *llamaModel) FileType() string {
  131. return fileType(llm.hyperparameters.FileType)
  132. }
  133. type llamaHyperparameters struct {
  134. // NumVocab is the size of the model's vocabulary.
  135. NumVocab uint32
  136. // NumEmbd is the size of the model's embedding layer.
  137. NumEmbd uint32
  138. NumMult uint32
  139. NumHead uint32
  140. // NumLayer is the number of layers in the model.
  141. NumLayer uint32
  142. NumRot uint32
  143. // FileType describes the quantization level of the model, e.g. Q4_0, Q5_K, etc.
  144. FileType uint32
  145. }
  146. type Running struct {
  147. Port int
  148. Cmd *exec.Cmd
  149. Cancel context.CancelFunc
  150. }
  151. type llama struct {
  152. api.Options
  153. Running
  154. }
  155. var errNoGPU = errors.New("nvidia-smi command failed")
  156. // CheckVRAM returns the available VRAM in MiB on Linux machines with NVIDIA GPUs
  157. func CheckVRAM() (int, error) {
  158. cmd := exec.Command("nvidia-smi", "--query-gpu=memory.total", "--format=csv,noheader,nounits")
  159. var stdout bytes.Buffer
  160. cmd.Stdout = &stdout
  161. err := cmd.Run()
  162. if err != nil {
  163. return 0, errNoGPU
  164. }
  165. var total int
  166. scanner := bufio.NewScanner(&stdout)
  167. for scanner.Scan() {
  168. line := scanner.Text()
  169. vram, err := strconv.Atoi(line)
  170. if err != nil {
  171. return 0, fmt.Errorf("failed to parse available VRAM: %v", err)
  172. }
  173. total += vram
  174. }
  175. return total, nil
  176. }
  177. func NumGPU(opts api.Options) int {
  178. if opts.NumGPU != -1 {
  179. return opts.NumGPU
  180. }
  181. n := 1 // default to enable metal on macOS
  182. if runtime.GOOS == "linux" {
  183. vram, err := CheckVRAM()
  184. if err != nil {
  185. if err.Error() != "nvidia-smi command failed" {
  186. log.Print(err.Error())
  187. }
  188. // nvidia driver not installed or no nvidia GPU found
  189. return 0
  190. }
  191. // TODO: this is a very rough heuristic, better would be to calculate this based on number of layers and context size
  192. switch {
  193. case vram < 500:
  194. log.Printf("WARNING: Low VRAM detected, disabling GPU")
  195. n = 0
  196. case vram < 1000:
  197. n = 4
  198. case vram < 2000:
  199. n = 8
  200. case vram < 4000:
  201. n = 12
  202. case vram < 8000:
  203. n = 16
  204. case vram < 12000:
  205. n = 24
  206. case vram < 16000:
  207. n = 32
  208. default:
  209. n = 48
  210. }
  211. log.Printf("%d MB VRAM available, loading %d GPU layers", vram, n)
  212. }
  213. return n
  214. }
  215. func newLlama(model string, adapters []string, runners []ModelRunner, opts api.Options) (*llama, error) {
  216. if _, err := os.Stat(model); err != nil {
  217. return nil, err
  218. }
  219. if len(adapters) > 1 {
  220. return nil, errors.New("ollama supports only one lora adapter, but multiple were provided")
  221. }
  222. params := []string{
  223. "--model", model,
  224. "--ctx-size", fmt.Sprintf("%d", opts.NumCtx),
  225. "--rope-freq-base", fmt.Sprintf("%f", opts.RopeFrequencyBase),
  226. "--rope-freq-scale", fmt.Sprintf("%f", opts.RopeFrequencyScale),
  227. "--batch-size", fmt.Sprintf("%d", opts.NumBatch),
  228. "--n-gpu-layers", fmt.Sprintf("%d", NumGPU(opts)),
  229. "--embedding",
  230. }
  231. if opts.NumGQA > 0 {
  232. params = append(params, "--gqa", fmt.Sprintf("%d", opts.NumGQA))
  233. }
  234. if len(adapters) > 0 {
  235. // TODO: applying multiple adapters is not supported by the llama.cpp server yet
  236. params = append(params, "--lora", adapters[0])
  237. }
  238. if opts.NumThread > 0 {
  239. params = append(params, "--threads", fmt.Sprintf("%d", opts.NumThread))
  240. }
  241. if !opts.F16KV {
  242. params = append(params, "--memory-f32")
  243. }
  244. if opts.UseMLock {
  245. params = append(params, "--mlock")
  246. }
  247. if !opts.UseMMap {
  248. params = append(params, "--no-mmap")
  249. }
  250. if opts.UseNUMA {
  251. params = append(params, "--numa")
  252. }
  253. // start the llama.cpp server with a retry in case the port is already in use
  254. for _, runner := range runners {
  255. if _, err := os.Stat(runner.Path); err != nil {
  256. log.Printf("llama runner not found: %v", err)
  257. continue
  258. }
  259. port := rand.Intn(65535-49152) + 49152 // get a random port in the ephemeral range
  260. ctx, cancel := context.WithCancel(context.Background())
  261. cmd := exec.CommandContext(
  262. ctx,
  263. runner.Path,
  264. append(params, "--port", strconv.Itoa(port))...,
  265. )
  266. cmd.Env = append(os.Environ(), fmt.Sprintf("LD_LIBRARY_PATH=%s", filepath.Dir(runner.Path)))
  267. cmd.Stdout = os.Stderr
  268. cmd.Stderr = os.Stderr
  269. llm := &llama{Options: opts, Running: Running{Port: port, Cmd: cmd, Cancel: cancel}}
  270. log.Print("starting llama runner")
  271. if err := llm.Cmd.Start(); err != nil {
  272. log.Printf("error starting the external llama runner: %v", err)
  273. continue
  274. }
  275. // monitor the command, it is blocking, so if it exits we need to capture that
  276. go func() {
  277. err := llm.Cmd.Wait() // this will block until the command exits
  278. if err != nil {
  279. log.Printf("llama runner exited with error: %v", err)
  280. } else {
  281. log.Printf("llama runner exited")
  282. }
  283. }()
  284. if err := waitForServer(llm); err != nil {
  285. log.Printf("error starting llama runner: %v", err)
  286. llm.Close()
  287. // try again
  288. continue
  289. }
  290. // server started successfully
  291. return llm, nil
  292. }
  293. return nil, fmt.Errorf("failed to start a llama runner")
  294. }
  295. func waitForServer(llm *llama) error {
  296. // wait for the server to start responding
  297. start := time.Now()
  298. expiresAt := time.Now().Add(2 * time.Minute) // be generous with timeout, large models can take a while to load
  299. ticker := time.NewTicker(200 * time.Millisecond)
  300. log.Print("waiting for llama runner to start responding")
  301. for range ticker.C {
  302. if time.Now().After(expiresAt) {
  303. return fmt.Errorf("llama runner did not start within alloted time, retrying")
  304. }
  305. // check if the server process has terminated
  306. if llm.Cmd.ProcessState != nil && llm.Cmd.ProcessState.Exited() {
  307. return fmt.Errorf("llama runner process has terminated")
  308. }
  309. if err := llm.Ping(context.Background()); err == nil {
  310. break
  311. }
  312. }
  313. log.Printf("llama runner started in %f seconds", time.Since(start).Seconds())
  314. return nil
  315. }
  316. func (llm *llama) Close() {
  317. llm.Cancel()
  318. }
  319. func (llm *llama) SetOptions(opts api.Options) {
  320. llm.Options = opts
  321. }
  322. type GenerationSettings struct {
  323. FrequencyPenalty float64 `json:"frequency_penalty"`
  324. IgnoreEOS bool `json:"ignore_eos"`
  325. LogitBias []interface{} `json:"logit_bias"`
  326. Mirostat int `json:"mirostat"`
  327. MirostatEta float64 `json:"mirostat_eta"`
  328. MirostatTau float64 `json:"mirostat_tau"`
  329. Model string `json:"model"`
  330. NCtx int `json:"n_ctx"`
  331. NKeep int `json:"n_keep"`
  332. NPredict int `json:"n_predict"`
  333. NProbs int `json:"n_probs"`
  334. PenalizeNl bool `json:"penalize_nl"`
  335. PresencePenalty float64 `json:"presence_penalty"`
  336. RepeatLastN int `json:"repeat_last_n"`
  337. RepeatPenalty float64 `json:"repeat_penalty"`
  338. Seed uint32 `json:"seed"`
  339. Stop []string `json:"stop"`
  340. Stream bool `json:"stream"`
  341. Temp float64 `json:"temp"`
  342. TfsZ float64 `json:"tfs_z"`
  343. TopK int `json:"top_k"`
  344. TopP float64 `json:"top_p"`
  345. TypicalP float64 `json:"typical_p"`
  346. }
  347. type Timings struct {
  348. PredictedN int `json:"predicted_n"`
  349. PredictedMS float64 `json:"predicted_ms"`
  350. PromptN int `json:"prompt_n"`
  351. PromptMS float64 `json:"prompt_ms"`
  352. }
  353. type Prediction struct {
  354. Content string `json:"content"`
  355. Model string `json:"model"`
  356. Prompt string `json:"prompt"`
  357. Stop bool `json:"stop"`
  358. Timings `json:"timings"`
  359. }
  360. type PredictRequest struct {
  361. Stream bool `json:"stream"`
  362. NPredict int `json:"n_predict,omitempty"`
  363. TopK int `json:"top_k,omitempty"`
  364. TopP float32 `json:"top_p,omitempty"`
  365. TfsZ float32 `json:"tfs_z,omitempty"`
  366. TypicalP float32 `json:"typical_p,omitempty"`
  367. RepeatLastN int `json:"repeat_last_n,omitempty"`
  368. Temperature float32 `json:"temperature,omitempty"`
  369. RepeatPenalty float32 `json:"repeat_penalty,omitempty"`
  370. PresencePenalty float32 `json:"presence_penalty,omitempty"`
  371. FrequencyPenalty float32 `json:"frequency_penalty,omitempty"`
  372. Mirostat int `json:"mirostat,omitempty"`
  373. MirostatTau float32 `json:"mirostat_tau,omitempty"`
  374. MirostatEta float32 `json:"mirostat_eta,omitempty"`
  375. PenalizeNl bool `json:"penalize_nl,omitempty"`
  376. NKeep int `json:"n_keep,omitempty"`
  377. Seed int `json:"seed,omitempty"`
  378. Prompt string `json:"prompt,omitempty"`
  379. NProbs int `json:"n_probs,omitempty"`
  380. LogitBias map[int]float32 `json:"logit_bias,omitempty"`
  381. IgnoreEos bool `json:"ignore_eos,omitempty"`
  382. Stop []string `json:"stop,omitempty"`
  383. }
  384. func (llm *llama) Predict(ctx context.Context, prevContext []int, prompt string, fn func(api.GenerateResponse)) error {
  385. prevConvo, err := llm.Decode(ctx, prevContext)
  386. if err != nil {
  387. return err
  388. }
  389. var nextContext strings.Builder
  390. nextContext.WriteString(prevConvo)
  391. nextContext.WriteString(prompt)
  392. endpoint := fmt.Sprintf("http://127.0.0.1:%d/completion", llm.Port)
  393. predReq := PredictRequest{
  394. Prompt: nextContext.String(),
  395. Stream: true,
  396. NPredict: llm.NumPredict,
  397. NKeep: llm.NumKeep,
  398. Temperature: llm.Temperature,
  399. TopK: llm.TopK,
  400. TopP: llm.TopP,
  401. TfsZ: llm.TFSZ,
  402. TypicalP: llm.TypicalP,
  403. RepeatLastN: llm.RepeatLastN,
  404. RepeatPenalty: llm.RepeatPenalty,
  405. PresencePenalty: llm.PresencePenalty,
  406. FrequencyPenalty: llm.FrequencyPenalty,
  407. Mirostat: llm.Mirostat,
  408. MirostatTau: llm.MirostatTau,
  409. MirostatEta: llm.MirostatEta,
  410. PenalizeNl: llm.PenalizeNewline,
  411. Stop: llm.Stop,
  412. }
  413. data, err := json.Marshal(predReq)
  414. if err != nil {
  415. return fmt.Errorf("error marshaling data: %v", err)
  416. }
  417. req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewBuffer(data))
  418. if err != nil {
  419. return fmt.Errorf("error creating POST request: %v", err)
  420. }
  421. req.Header.Set("Content-Type", "application/json")
  422. resp, err := http.DefaultClient.Do(req)
  423. if err != nil {
  424. return fmt.Errorf("POST predict: %v", err)
  425. }
  426. defer resp.Body.Close()
  427. if resp.StatusCode >= 400 {
  428. bodyBytes, err := io.ReadAll(resp.Body)
  429. if err != nil {
  430. return fmt.Errorf("failed reading llm error response: %w", err)
  431. }
  432. log.Printf("llm predict error: %s", bodyBytes)
  433. return fmt.Errorf("%s", bodyBytes)
  434. }
  435. scanner := bufio.NewScanner(resp.Body)
  436. for scanner.Scan() {
  437. select {
  438. case <-ctx.Done():
  439. // This handles the request cancellation
  440. return ctx.Err()
  441. default:
  442. line := scanner.Text()
  443. if line == "" {
  444. continue
  445. }
  446. // Read data from the server-side event stream
  447. if strings.HasPrefix(line, "data: ") {
  448. evt := line[6:]
  449. var p Prediction
  450. if err := json.Unmarshal([]byte(evt), &p); err != nil {
  451. return fmt.Errorf("error unmarshaling llm prediction response: %v", err)
  452. }
  453. if p.Content != "" {
  454. fn(api.GenerateResponse{Response: p.Content})
  455. nextContext.WriteString(p.Content)
  456. }
  457. if p.Stop {
  458. embd, err := llm.Encode(ctx, nextContext.String())
  459. if err != nil {
  460. return fmt.Errorf("encoding context: %v", err)
  461. }
  462. fn(api.GenerateResponse{
  463. Done: true,
  464. Context: embd,
  465. PromptEvalCount: p.PromptN,
  466. PromptEvalDuration: parseDurationMs(p.PromptMS),
  467. EvalCount: p.PredictedN,
  468. EvalDuration: parseDurationMs(p.PredictedMS),
  469. })
  470. return nil
  471. }
  472. }
  473. }
  474. }
  475. if err := scanner.Err(); err != nil {
  476. return fmt.Errorf("error reading llm response: %v", err)
  477. }
  478. return nil
  479. }
  480. type TokenizeRequest struct {
  481. Content string `json:"content"`
  482. }
  483. type TokenizeResponse struct {
  484. Tokens []int `json:"tokens"`
  485. }
  486. func (llm *llama) Encode(ctx context.Context, prompt string) ([]int, error) {
  487. endpoint := fmt.Sprintf("http://127.0.0.1:%d/tokenize", llm.Port)
  488. data, err := json.Marshal(TokenizeRequest{Content: prompt})
  489. if err != nil {
  490. return nil, fmt.Errorf("marshaling encode data: %w", err)
  491. }
  492. req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewBuffer(data))
  493. if err != nil {
  494. return nil, fmt.Errorf("encode request: %w", err)
  495. }
  496. req.Header.Set("Content-Type", "application/json")
  497. resp, err := http.DefaultClient.Do(req)
  498. if err != nil {
  499. return nil, fmt.Errorf("do encode request: %w", err)
  500. }
  501. defer resp.Body.Close()
  502. body, err := io.ReadAll(resp.Body)
  503. if err != nil {
  504. return nil, fmt.Errorf("read encode request: %w", err)
  505. }
  506. if resp.StatusCode >= 400 {
  507. log.Printf("llm encode error: %s", body)
  508. return nil, fmt.Errorf("%s", body)
  509. }
  510. var encoded TokenizeResponse
  511. if err := json.Unmarshal(body, &encoded); err != nil {
  512. return nil, fmt.Errorf("unmarshal encode response: %w", err)
  513. }
  514. return encoded.Tokens, nil
  515. }
  516. type DetokenizeRequest struct {
  517. Tokens []int `json:"tokens"`
  518. }
  519. type DetokenizeResponse struct {
  520. Content string `json:"content"`
  521. }
  522. func (llm *llama) Decode(ctx context.Context, tokens []int) (string, error) {
  523. if len(tokens) == 0 {
  524. return "", nil
  525. }
  526. endpoint := fmt.Sprintf("http://127.0.0.1:%d/detokenize", llm.Port)
  527. data, err := json.Marshal(DetokenizeRequest{Tokens: tokens})
  528. if err != nil {
  529. return "", fmt.Errorf("marshaling decode data: %w", err)
  530. }
  531. req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewBuffer(data))
  532. if err != nil {
  533. return "", fmt.Errorf("decode request: %w", err)
  534. }
  535. req.Header.Set("Content-Type", "application/json")
  536. resp, err := http.DefaultClient.Do(req)
  537. if err != nil {
  538. return "", fmt.Errorf("do decode request: %w", err)
  539. }
  540. defer resp.Body.Close()
  541. body, err := io.ReadAll(resp.Body)
  542. if err != nil {
  543. return "", fmt.Errorf("read decode request: %w", err)
  544. }
  545. if resp.StatusCode >= 400 {
  546. log.Printf("llm decode error: %s", body)
  547. return "", fmt.Errorf("%s", body)
  548. }
  549. var decoded DetokenizeResponse
  550. if err := json.Unmarshal(body, &decoded); err != nil {
  551. return "", fmt.Errorf("unmarshal encode response: %w", err)
  552. }
  553. // decoded content contains a leading whitespace
  554. decoded.Content, _ = strings.CutPrefix(decoded.Content, "")
  555. return decoded.Content, nil
  556. }
  557. type EmbeddingRequest struct {
  558. Content string `json:"content"`
  559. }
  560. type EmbeddingResponse struct {
  561. Embedding []float64 `json:"embedding"`
  562. }
  563. func (llm *llama) Embedding(ctx context.Context, input string) ([]float64, error) {
  564. endpoint := fmt.Sprintf("http://127.0.0.1:%d/embedding", llm.Port)
  565. data, err := json.Marshal(TokenizeRequest{Content: input})
  566. if err != nil {
  567. return nil, fmt.Errorf("error marshaling embed data: %w", err)
  568. }
  569. req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewBuffer(data))
  570. if err != nil {
  571. return nil, fmt.Errorf("error creating embed request: %w", err)
  572. }
  573. req.Header.Set("Content-Type", "application/json")
  574. resp, err := http.DefaultClient.Do(req)
  575. if err != nil {
  576. return nil, fmt.Errorf("POST embedding: %w", err)
  577. }
  578. defer resp.Body.Close()
  579. body, err := io.ReadAll(resp.Body)
  580. if err != nil {
  581. return nil, fmt.Errorf("error reading embed response: %w", err)
  582. }
  583. if resp.StatusCode >= 400 {
  584. log.Printf("llm encode error: %s", body)
  585. return nil, fmt.Errorf("%s", body)
  586. }
  587. var embedding EmbeddingResponse
  588. if err := json.Unmarshal(body, &embedding); err != nil {
  589. return nil, fmt.Errorf("unmarshal tokenize response: %w", err)
  590. }
  591. return embedding.Embedding, nil
  592. }
  593. // Ping checks that the server subprocess is still running and responding to requests
  594. func (llm *llama) Ping(ctx context.Context) error {
  595. resp, err := http.Head(fmt.Sprintf("http://127.0.0.1:%d", llm.Port))
  596. if err != nil {
  597. return fmt.Errorf("ping resp: %w", err)
  598. }
  599. if resp.StatusCode != http.StatusOK {
  600. return fmt.Errorf("unexpected ping status: %s", resp.Status)
  601. }
  602. return nil
  603. }