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