llama.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  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. "sync"
  23. "time"
  24. "github.com/jmorganca/ollama/api"
  25. "github.com/jmorganca/ollama/format"
  26. )
  27. const jsonGrammar = `
  28. root ::= object
  29. value ::= object | array | string | number | ("true" | "false" | "null") ws
  30. object ::=
  31. "{" ws (
  32. string ":" ws value
  33. ("," ws string ":" ws value)*
  34. )? "}" ws
  35. array ::=
  36. "[" ws (
  37. value
  38. ("," ws value)*
  39. )? "]" ws
  40. string ::=
  41. "\"" (
  42. [^"\\] |
  43. "\\" (["\\/bfnrt] | "u" [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F]) # escapes
  44. )* "\"" ws
  45. number ::= ("-"? ([0-9] | [1-9] [0-9]*)) ("." [0-9]+)? ([eE] [-+]? [0-9]+)? ws
  46. # Optional space: by convention, applied in this grammar after literal chars when allowed
  47. ws ::= ([ \t\n] ws)?
  48. `
  49. //go:embed llama.cpp/*/build/*/bin/*
  50. var llamaCppEmbed embed.FS
  51. type ModelRunner struct {
  52. Path string // path to the model runner executable
  53. Accelerated bool
  54. }
  55. func chooseRunners(workDir, runnerType string) []ModelRunner {
  56. buildPath := path.Join("llama.cpp", runnerType, "build")
  57. var runners []ModelRunner
  58. // set the runners based on the OS
  59. // IMPORTANT: the order of the runners in the array is the priority order
  60. switch runtime.GOOS {
  61. case "darwin":
  62. if runtime.GOARCH == "arm64" {
  63. runners = []ModelRunner{{Path: path.Join(buildPath, "metal", "bin", "ollama-runner")}}
  64. } else {
  65. runners = []ModelRunner{{Path: path.Join(buildPath, "cpu", "bin", "ollama-runner")}}
  66. }
  67. case "linux":
  68. runners = []ModelRunner{
  69. {Path: path.Join(buildPath, "cuda", "bin", "ollama-runner"), Accelerated: true},
  70. {Path: path.Join(buildPath, "cpu", "bin", "ollama-runner")},
  71. }
  72. case "windows":
  73. // TODO: select windows GPU runner here when available
  74. runners = []ModelRunner{
  75. {Path: path.Join(buildPath, "cuda", "bin", "Release", "ollama-runner.exe"), Accelerated: true},
  76. {Path: path.Join(buildPath, "cpu", "bin", "Release", "ollama-runner.exe")},
  77. }
  78. default:
  79. log.Printf("unknown OS, running on CPU: %s", runtime.GOOS)
  80. runners = []ModelRunner{
  81. {Path: path.Join(buildPath, "cpu", "bin", "ollama-runner")},
  82. }
  83. }
  84. runnerAvailable := false // if no runner files are found in the embed, this flag will cause a fast fail
  85. for _, r := range runners {
  86. // find all the files in the runner's bin directory
  87. files, err := fs.Glob(llamaCppEmbed, path.Join(path.Dir(r.Path), "*"))
  88. if err != nil {
  89. // this is expected, ollama may be compiled without all runners packed in
  90. log.Printf("%s runner not found: %v", r.Path, err)
  91. continue
  92. }
  93. for _, f := range files {
  94. runnerAvailable = true
  95. srcFile, err := llamaCppEmbed.Open(f)
  96. if err != nil {
  97. log.Fatalf("read llama runner %s: %v", f, err)
  98. }
  99. defer srcFile.Close()
  100. // create the directory in case it does not exist, filepath.Dir() converts the file path to the OS's format
  101. destPath := filepath.Join(workDir, filepath.Dir(f))
  102. if err := os.MkdirAll(destPath, 0o755); err != nil {
  103. log.Fatalf("create runner temp dir %s: %v", filepath.Dir(f), err)
  104. }
  105. // create the path to the destination file, filepath.Base() converts the file path to the OS's format
  106. destFile := filepath.Join(destPath, filepath.Base(f))
  107. _, err = os.Stat(destFile)
  108. switch {
  109. case errors.Is(err, os.ErrNotExist):
  110. destFile, err := os.OpenFile(destFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o755)
  111. if err != nil {
  112. log.Fatalf("write llama runner %s: %v", f, err)
  113. }
  114. defer destFile.Close()
  115. if _, err := io.Copy(destFile, srcFile); err != nil {
  116. log.Fatalf("copy llama runner %s: %v", f, err)
  117. }
  118. case err != nil:
  119. log.Fatalf("stat llama runner %s: %v", f, err)
  120. }
  121. }
  122. }
  123. if !runnerAvailable {
  124. log.Fatalf("%s runner not found", runnerType)
  125. }
  126. // return the runners to try in priority order
  127. localRunnersByPriority := []ModelRunner{}
  128. for _, r := range runners {
  129. // clean the ModelRunner paths so that they match the OS we are running on
  130. localRunnersByPriority = append(localRunnersByPriority, ModelRunner{
  131. Path: filepath.Clean(path.Join(workDir, r.Path)),
  132. Accelerated: r.Accelerated,
  133. })
  134. }
  135. return localRunnersByPriority
  136. }
  137. type llamaModel struct {
  138. hyperparameters llamaHyperparameters
  139. }
  140. func (llm *llamaModel) ModelFamily() string {
  141. return "llama"
  142. }
  143. func llamaModelType(numLayer uint32) string {
  144. switch numLayer {
  145. case 26:
  146. return "3B"
  147. case 32:
  148. return "7B"
  149. case 40:
  150. return "13B"
  151. case 48:
  152. return "34B"
  153. case 60:
  154. return "30B"
  155. case 80:
  156. return "65B"
  157. default:
  158. return "unknown"
  159. }
  160. }
  161. func (llm *llamaModel) ModelType() string {
  162. return llamaModelType(llm.hyperparameters.NumLayer)
  163. }
  164. func (llm *llamaModel) FileType() string {
  165. return fileType(llm.hyperparameters.FileType)
  166. }
  167. func (llm *llamaModel) NumLayers() int64 {
  168. return int64(llm.hyperparameters.NumLayer)
  169. }
  170. type llamaHyperparameters struct {
  171. // NumVocab is the size of the model's vocabulary.
  172. NumVocab uint32
  173. // NumEmbd is the size of the model's embedding layer.
  174. NumEmbd uint32
  175. NumMult uint32
  176. NumHead uint32
  177. // NumLayer is the number of layers in the model.
  178. NumLayer uint32
  179. NumRot uint32
  180. // FileType describes the quantization level of the model, e.g. Q4_0, Q5_K, etc.
  181. FileType uint32
  182. }
  183. type Running struct {
  184. Port int
  185. Cmd *exec.Cmd
  186. Cancel context.CancelFunc
  187. exitOnce sync.Once
  188. exitCh chan error // channel to receive the exit status of the subprocess
  189. *StatusWriter // captures error messages from the llama runner process
  190. }
  191. type llama struct {
  192. api.Options
  193. Running
  194. }
  195. var (
  196. errNvidiaSMI = errors.New("warning: gpu support may not be enabled, check that you have installed GPU drivers: nvidia-smi command failed")
  197. errAvailableVRAM = errors.New("not enough VRAM available, falling back to CPU only")
  198. )
  199. // CheckVRAM returns the free VRAM in bytes on Linux machines with NVIDIA GPUs
  200. func CheckVRAM() (int64, error) {
  201. cmd := exec.Command("nvidia-smi", "--query-gpu=memory.free", "--format=csv,noheader,nounits")
  202. var stdout bytes.Buffer
  203. cmd.Stdout = &stdout
  204. err := cmd.Run()
  205. if err != nil {
  206. return 0, errNvidiaSMI
  207. }
  208. var freeMiB int64
  209. scanner := bufio.NewScanner(&stdout)
  210. for scanner.Scan() {
  211. line := scanner.Text()
  212. if strings.Contains(line, "[Insufficient Permissions]") {
  213. return 0, fmt.Errorf("GPU support may not enabled, check you have installed GPU drivers and have the necessary permissions to run nvidia-smi")
  214. }
  215. vram, err := strconv.ParseInt(strings.TrimSpace(line), 10, 64)
  216. if err != nil {
  217. return 0, fmt.Errorf("failed to parse available VRAM: %v", err)
  218. }
  219. freeMiB += vram
  220. }
  221. freeBytes := freeMiB * 1024 * 1024
  222. if freeBytes < 2*format.GigaByte {
  223. log.Printf("less than 2 GB VRAM available")
  224. return 0, errAvailableVRAM
  225. }
  226. return freeBytes, nil
  227. }
  228. func NumGPU(numLayer, fileSizeBytes int64, opts api.Options) int {
  229. if opts.NumGPU != -1 {
  230. return opts.NumGPU
  231. }
  232. if runtime.GOOS == "linux" || runtime.GOOS == "windows" {
  233. freeBytes, err := CheckVRAM()
  234. if err != nil {
  235. if !errors.Is(err, errNvidiaSMI) {
  236. log.Print(err.Error())
  237. }
  238. // nvidia driver not installed or no nvidia GPU found
  239. return 0
  240. }
  241. /*
  242. Calculate bytes per layer, this will roughly be the size of the model file divided by the number of layers.
  243. We can store the model weights and the kv cache in vram,
  244. to enable kv chache vram storage add two additional layers to the number of layers retrieved from the model file.
  245. */
  246. bytesPerLayer := fileSizeBytes / numLayer
  247. // 75% of the absolute max number of layers we can fit in available VRAM, off-loading too many layers to the GPU can cause OOM errors
  248. layers := int(freeBytes/bytesPerLayer) * 3 / 4
  249. log.Printf("%d MB VRAM available, loading up to %d GPU layers", freeBytes/(1024*1024), layers)
  250. return layers
  251. }
  252. // default to enable metal on macOS
  253. return 1
  254. }
  255. // StatusWriter is a writer that captures error messages from the llama runner process
  256. type StatusWriter struct {
  257. ErrCh chan error
  258. LastErrMsg string
  259. }
  260. func NewStatusWriter() *StatusWriter {
  261. return &StatusWriter{
  262. ErrCh: make(chan error, 1),
  263. }
  264. }
  265. func (w *StatusWriter) Write(b []byte) (int, error) {
  266. var errMsg string
  267. if _, after, ok := bytes.Cut(b, []byte("error:")); ok {
  268. errMsg = string(bytes.TrimSpace(after))
  269. } else if _, after, ok := bytes.Cut(b, []byte("CUDA error")); ok {
  270. errMsg = string(bytes.TrimSpace(after))
  271. }
  272. if errMsg != "" {
  273. w.LastErrMsg = errMsg
  274. w.ErrCh <- fmt.Errorf("llama runner: %s", errMsg)
  275. }
  276. return os.Stderr.Write(b)
  277. }
  278. func newLlama(model string, adapters, projectors []string, runners []ModelRunner, numLayers int64, opts api.Options) (*llama, error) {
  279. fileInfo, err := os.Stat(model)
  280. if err != nil {
  281. return nil, err
  282. }
  283. if len(adapters) > 1 {
  284. return nil, errors.New("ollama supports only one lora adapter, but multiple were provided")
  285. }
  286. numGPU := NumGPU(numLayers, fileInfo.Size(), opts)
  287. params := []string{
  288. "--model", model,
  289. "--ctx-size", fmt.Sprintf("%d", opts.NumCtx),
  290. "--batch-size", fmt.Sprintf("%d", opts.NumBatch),
  291. "--n-gpu-layers", fmt.Sprintf("%d", numGPU),
  292. "--embedding",
  293. }
  294. if opts.MainGPU > 0 {
  295. params = append(params, "--main-gpu", fmt.Sprintf("%d", opts.MainGPU))
  296. }
  297. if opts.RopeFrequencyBase > 0 {
  298. params = append(params, "--rope-freq-base", fmt.Sprintf("%f", opts.RopeFrequencyBase))
  299. }
  300. if opts.RopeFrequencyScale > 0 {
  301. params = append(params, "--rope-freq-scale", fmt.Sprintf("%f", opts.RopeFrequencyScale))
  302. }
  303. if opts.NumGQA > 0 {
  304. params = append(params, "--gqa", fmt.Sprintf("%d", opts.NumGQA))
  305. }
  306. if len(adapters) > 0 {
  307. // TODO: applying multiple adapters is not supported by the llama.cpp server yet
  308. params = append(params, "--lora", adapters[0])
  309. }
  310. if len(projectors) > 0 {
  311. // TODO: applying multiple projectors is not supported by the llama.cpp server yet
  312. params = append(params, "--mmproj", projectors[0])
  313. }
  314. if opts.NumThread > 0 {
  315. params = append(params, "--threads", fmt.Sprintf("%d", opts.NumThread))
  316. }
  317. if !opts.F16KV {
  318. params = append(params, "--memory-f32")
  319. }
  320. if opts.UseMLock {
  321. params = append(params, "--mlock")
  322. }
  323. if !opts.UseMMap {
  324. params = append(params, "--no-mmap")
  325. }
  326. if opts.UseNUMA {
  327. params = append(params, "--numa")
  328. }
  329. var runnerErr error
  330. // start the llama.cpp server with a retry in case the port is already in use
  331. for _, runner := range runners {
  332. if runner.Accelerated && numGPU == 0 {
  333. log.Printf("skipping accelerated runner because num_gpu=0")
  334. continue
  335. }
  336. if _, err := os.Stat(runner.Path); err != nil {
  337. log.Printf("llama runner not found: %v", err)
  338. continue
  339. }
  340. port := rand.Intn(65535-49152) + 49152 // get a random port in the ephemeral range
  341. ctx, cancel := context.WithCancel(context.Background())
  342. cmd := exec.CommandContext(
  343. ctx,
  344. runner.Path,
  345. append(params, "--port", strconv.Itoa(port))...,
  346. )
  347. var libraryPaths []string
  348. if libraryPath, ok := os.LookupEnv("LD_LIBRARY_PATH"); ok {
  349. libraryPaths = append(libraryPaths, libraryPath)
  350. }
  351. libraryPaths = append(libraryPaths, filepath.Dir(runner.Path))
  352. cmd.Env = append(os.Environ(), fmt.Sprintf("LD_LIBRARY_PATH=%s", strings.Join(libraryPaths, ":")))
  353. cmd.Stdout = os.Stderr
  354. statusWriter := NewStatusWriter()
  355. cmd.Stderr = statusWriter
  356. llm := &llama{Options: opts, Running: Running{Port: port, Cmd: cmd, Cancel: cancel, exitCh: make(chan error)}}
  357. log.Print("starting llama runner")
  358. if err := llm.Cmd.Start(); err != nil {
  359. log.Printf("error starting the external llama runner: %v", err)
  360. continue
  361. }
  362. // monitor the llama runner process and signal when it exits
  363. go func() {
  364. err := llm.Cmd.Wait()
  365. // default to printing the exit message of the command process, it will probably just say 'exit staus 1'
  366. errMsg := err.Error()
  367. // try to set a better error message if llama runner logs captured an error
  368. if statusWriter.LastErrMsg != "" {
  369. errMsg = statusWriter.LastErrMsg
  370. }
  371. log.Println(errMsg)
  372. // llm.Cmd.Wait() can only be called once, use this exit channel to signal that the process has exited
  373. llm.exitOnce.Do(func() {
  374. close(llm.exitCh)
  375. })
  376. }()
  377. if err := waitForServer(llm); err != nil {
  378. log.Printf("error starting llama runner: %v", err)
  379. llm.Close()
  380. // default the runnerErr to the error returned by the most recent llama runner process
  381. runnerErr = err
  382. // capture the error directly from the runner process, if any
  383. select {
  384. case runnerErr = <-statusWriter.ErrCh:
  385. default:
  386. // the runner process probably timed out
  387. }
  388. // try again
  389. continue
  390. }
  391. // server started successfully
  392. return llm, nil
  393. }
  394. if runnerErr != nil {
  395. // this is the error returned from the llama runner process that failed most recently
  396. return nil, runnerErr
  397. }
  398. return nil, fmt.Errorf("failed to start a llama runner")
  399. }
  400. func waitForServer(llm *llama) error {
  401. start := time.Now()
  402. expiresAt := time.Now().Add(3 * time.Minute) // be generous with timeout, large models can take a while to load
  403. ticker := time.NewTicker(200 * time.Millisecond)
  404. defer ticker.Stop()
  405. log.Print("waiting for llama runner to start responding")
  406. for {
  407. select {
  408. case <-llm.exitCh:
  409. // failed to start subprocess
  410. return fmt.Errorf("llama runner process has terminated")
  411. case <-ticker.C:
  412. if time.Now().After(expiresAt) {
  413. // timeout
  414. return fmt.Errorf("timed out waiting for llama runner to start")
  415. }
  416. if err := llm.Ping(context.Background()); err == nil {
  417. // success
  418. log.Printf("llama runner started in %f seconds", time.Since(start).Seconds())
  419. return nil
  420. }
  421. }
  422. }
  423. }
  424. func (llm *llama) Close() {
  425. // signal the sub-process to terminate
  426. llm.Cancel()
  427. // wait for the command to exit to prevent race conditions with the next run
  428. <-llm.exitCh
  429. if llm.StatusWriter != nil && llm.StatusWriter.LastErrMsg != "" {
  430. log.Printf("llama runner stopped with error: %v", llm.StatusWriter.LastErrMsg)
  431. } else {
  432. log.Print("llama runner stopped successfully")
  433. }
  434. }
  435. func (llm *llama) SetOptions(opts api.Options) {
  436. llm.Options = opts
  437. }
  438. type prediction struct {
  439. Content string `json:"content"`
  440. Model string `json:"model"`
  441. Prompt string `json:"prompt"`
  442. Stop bool `json:"stop"`
  443. Timings struct {
  444. PredictedN int `json:"predicted_n"`
  445. PredictedMS float64 `json:"predicted_ms"`
  446. PromptN int `json:"prompt_n"`
  447. PromptMS float64 `json:"prompt_ms"`
  448. }
  449. }
  450. const maxBufferSize = 512 * format.KiloByte
  451. type PredictOpts struct {
  452. Model string
  453. Prompt string
  454. Format string
  455. CheckpointStart time.Time
  456. CheckpointLoaded time.Time
  457. }
  458. type PredictResult struct {
  459. Model string
  460. CreatedAt time.Time
  461. TotalDuration time.Duration
  462. LoadDuration time.Duration
  463. Content string
  464. Done bool
  465. PromptEvalCount int
  466. PromptEvalDuration time.Duration
  467. EvalCount int
  468. EvalDuration time.Duration
  469. }
  470. func (llm *llama) Predict(ctx context.Context, predict PredictOpts, fn func(PredictResult)) error {
  471. request := map[string]any{
  472. "prompt": predict.Prompt,
  473. "stream": true,
  474. "n_predict": llm.NumPredict,
  475. "n_keep": llm.NumKeep,
  476. "main_gpu": llm.MainGPU,
  477. "temperature": llm.Temperature,
  478. "top_k": llm.TopK,
  479. "top_p": llm.TopP,
  480. "tfs_z": llm.TFSZ,
  481. "typical_p": llm.TypicalP,
  482. "repeat_last_n": llm.RepeatLastN,
  483. "repeat_penalty": llm.RepeatPenalty,
  484. "presence_penalty": llm.PresencePenalty,
  485. "frequency_penalty": llm.FrequencyPenalty,
  486. "mirostat": llm.Mirostat,
  487. "mirostat_tau": llm.MirostatTau,
  488. "mirostat_eta": llm.MirostatEta,
  489. "penalize_nl": llm.PenalizeNewline,
  490. "seed": llm.Seed,
  491. "stop": llm.Stop,
  492. }
  493. if predict.Format == "json" {
  494. request["grammar"] = jsonGrammar
  495. }
  496. // Handling JSON marshaling with special characters unescaped.
  497. buffer := &bytes.Buffer{}
  498. enc := json.NewEncoder(buffer)
  499. enc.SetEscapeHTML(false)
  500. if err := enc.Encode(request); err != nil {
  501. return fmt.Errorf("failed to marshal data: %v", err)
  502. }
  503. endpoint := fmt.Sprintf("http://127.0.0.1:%d/completion", llm.Port)
  504. req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, buffer)
  505. if err != nil {
  506. return fmt.Errorf("error creating POST request: %v", err)
  507. }
  508. req.Header.Set("Content-Type", "application/json")
  509. resp, err := http.DefaultClient.Do(req)
  510. if err != nil {
  511. return fmt.Errorf("POST predict: %v", err)
  512. }
  513. defer resp.Body.Close()
  514. if resp.StatusCode >= 400 {
  515. bodyBytes, err := io.ReadAll(resp.Body)
  516. if err != nil {
  517. return fmt.Errorf("failed reading llm error response: %w", err)
  518. }
  519. log.Printf("llm predict error: %s", bodyBytes)
  520. return fmt.Errorf("%s", bodyBytes)
  521. }
  522. scanner := bufio.NewScanner(resp.Body)
  523. // increase the buffer size to avoid running out of space
  524. buf := make([]byte, 0, maxBufferSize)
  525. scanner.Buffer(buf, maxBufferSize)
  526. for scanner.Scan() {
  527. select {
  528. case <-ctx.Done():
  529. // This handles the request cancellation
  530. return ctx.Err()
  531. default:
  532. line := scanner.Bytes()
  533. if len(line) == 0 {
  534. continue
  535. }
  536. if evt, ok := bytes.CutPrefix(line, []byte("data: ")); ok {
  537. var p prediction
  538. if err := json.Unmarshal(evt, &p); err != nil {
  539. return fmt.Errorf("error unmarshaling llm prediction response: %v", err)
  540. }
  541. if p.Content != "" {
  542. fn(PredictResult{
  543. Model: predict.Model,
  544. CreatedAt: time.Now().UTC(),
  545. Content: p.Content,
  546. })
  547. }
  548. if p.Stop {
  549. fn(PredictResult{
  550. Model: predict.Model,
  551. CreatedAt: time.Now().UTC(),
  552. TotalDuration: time.Since(predict.CheckpointStart),
  553. Done: true,
  554. PromptEvalCount: p.Timings.PromptN,
  555. PromptEvalDuration: parseDurationMs(p.Timings.PromptMS),
  556. EvalCount: p.Timings.PredictedN,
  557. EvalDuration: parseDurationMs(p.Timings.PredictedMS),
  558. })
  559. return nil
  560. }
  561. }
  562. }
  563. }
  564. if err := scanner.Err(); err != nil {
  565. if strings.Contains(err.Error(), "unexpected EOF") {
  566. // this means the llama runner subprocess crashed
  567. llm.Close()
  568. if llm.StatusWriter != nil && llm.StatusWriter.LastErrMsg != "" {
  569. return fmt.Errorf("llama runner exited: %v", llm.StatusWriter.LastErrMsg)
  570. }
  571. return fmt.Errorf("llama runner exited, you may not have enough available memory to run this model")
  572. }
  573. return fmt.Errorf("error reading llm response: %v", err)
  574. }
  575. return nil
  576. }
  577. type TokenizeRequest struct {
  578. Content string `json:"content"`
  579. }
  580. type TokenizeResponse struct {
  581. Tokens []int `json:"tokens"`
  582. }
  583. func (llm *llama) Encode(ctx context.Context, prompt string) ([]int, error) {
  584. endpoint := fmt.Sprintf("http://127.0.0.1:%d/tokenize", llm.Port)
  585. data, err := json.Marshal(TokenizeRequest{Content: prompt})
  586. if err != nil {
  587. return nil, fmt.Errorf("marshaling encode data: %w", err)
  588. }
  589. req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewBuffer(data))
  590. if err != nil {
  591. return nil, fmt.Errorf("encode request: %w", err)
  592. }
  593. req.Header.Set("Content-Type", "application/json")
  594. resp, err := http.DefaultClient.Do(req)
  595. if err != nil {
  596. return nil, fmt.Errorf("do encode request: %w", err)
  597. }
  598. defer resp.Body.Close()
  599. body, err := io.ReadAll(resp.Body)
  600. if err != nil {
  601. return nil, fmt.Errorf("read encode request: %w", err)
  602. }
  603. if resp.StatusCode >= 400 {
  604. log.Printf("llm encode error: %s", body)
  605. return nil, fmt.Errorf("%s", body)
  606. }
  607. var encoded TokenizeResponse
  608. if err := json.Unmarshal(body, &encoded); err != nil {
  609. return nil, fmt.Errorf("unmarshal encode response: %w", err)
  610. }
  611. return encoded.Tokens, nil
  612. }
  613. type DetokenizeRequest struct {
  614. Tokens []int `json:"tokens"`
  615. }
  616. type DetokenizeResponse struct {
  617. Content string `json:"content"`
  618. }
  619. func (llm *llama) Decode(ctx context.Context, tokens []int) (string, error) {
  620. if len(tokens) == 0 {
  621. return "", nil
  622. }
  623. endpoint := fmt.Sprintf("http://127.0.0.1:%d/detokenize", llm.Port)
  624. data, err := json.Marshal(DetokenizeRequest{Tokens: tokens})
  625. if err != nil {
  626. return "", fmt.Errorf("marshaling decode data: %w", err)
  627. }
  628. req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewBuffer(data))
  629. if err != nil {
  630. return "", fmt.Errorf("decode request: %w", err)
  631. }
  632. req.Header.Set("Content-Type", "application/json")
  633. resp, err := http.DefaultClient.Do(req)
  634. if err != nil {
  635. return "", fmt.Errorf("do decode request: %w", err)
  636. }
  637. defer resp.Body.Close()
  638. body, err := io.ReadAll(resp.Body)
  639. if err != nil {
  640. return "", fmt.Errorf("read decode request: %w", err)
  641. }
  642. if resp.StatusCode >= 400 {
  643. log.Printf("llm decode error: %s", body)
  644. return "", fmt.Errorf("%s", body)
  645. }
  646. var decoded DetokenizeResponse
  647. if err := json.Unmarshal(body, &decoded); err != nil {
  648. return "", fmt.Errorf("unmarshal encode response: %w", err)
  649. }
  650. return decoded.Content, nil
  651. }
  652. type EmbeddingRequest struct {
  653. Content string `json:"content"`
  654. }
  655. type EmbeddingResponse struct {
  656. Embedding []float64 `json:"embedding"`
  657. }
  658. func (llm *llama) Embedding(ctx context.Context, input string) ([]float64, error) {
  659. endpoint := fmt.Sprintf("http://127.0.0.1:%d/embedding", llm.Port)
  660. data, err := json.Marshal(TokenizeRequest{Content: input})
  661. if err != nil {
  662. return nil, fmt.Errorf("error marshaling embed data: %w", err)
  663. }
  664. req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewBuffer(data))
  665. if err != nil {
  666. return nil, fmt.Errorf("error creating embed request: %w", err)
  667. }
  668. req.Header.Set("Content-Type", "application/json")
  669. resp, err := http.DefaultClient.Do(req)
  670. if err != nil {
  671. return nil, fmt.Errorf("POST embedding: %w", err)
  672. }
  673. defer resp.Body.Close()
  674. body, err := io.ReadAll(resp.Body)
  675. if err != nil {
  676. return nil, fmt.Errorf("error reading embed response: %w", err)
  677. }
  678. if resp.StatusCode >= 400 {
  679. log.Printf("llm encode error: %s", body)
  680. return nil, fmt.Errorf("%s", body)
  681. }
  682. var embedding EmbeddingResponse
  683. if err := json.Unmarshal(body, &embedding); err != nil {
  684. return nil, fmt.Errorf("unmarshal tokenize response: %w", err)
  685. }
  686. return embedding.Embedding, nil
  687. }
  688. // Ping checks that the server subprocess is still running and responding to requests
  689. func (llm *llama) Ping(ctx context.Context) error {
  690. resp, err := http.Head(fmt.Sprintf("http://127.0.0.1:%d", llm.Port))
  691. if err != nil {
  692. return fmt.Errorf("ping resp: %w", err)
  693. }
  694. if resp.StatusCode != http.StatusOK {
  695. return fmt.Errorf("unexpected ping status: %s", resp.Status)
  696. }
  697. return nil
  698. }