llama.go 19 KB

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