interactive.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. package cmd
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "os"
  8. "path/filepath"
  9. "regexp"
  10. "slices"
  11. "sort"
  12. "strings"
  13. "github.com/spf13/cobra"
  14. "github.com/ollama/ollama/api"
  15. "github.com/ollama/ollama/envconfig"
  16. "github.com/ollama/ollama/progress"
  17. "github.com/ollama/ollama/readline"
  18. "github.com/ollama/ollama/types/errtypes"
  19. )
  20. type MultilineState int
  21. const (
  22. MultilineNone MultilineState = iota
  23. MultilinePrompt
  24. MultilineSystem
  25. MultilineTemplate
  26. )
  27. func loadModel(cmd *cobra.Command, opts *runOptions) error {
  28. p := progress.NewProgress(os.Stderr)
  29. defer p.StopAndClear()
  30. spinner := progress.NewSpinner("")
  31. p.Add("", spinner)
  32. client, err := api.ClientFromEnvironment()
  33. if err != nil {
  34. return err
  35. }
  36. chatReq := &api.ChatRequest{
  37. Model: opts.Model,
  38. KeepAlive: opts.KeepAlive,
  39. }
  40. return client.Chat(cmd.Context(), chatReq, func(resp api.ChatResponse) error {
  41. p.StopAndClear()
  42. for _, msg := range opts.Messages {
  43. switch msg.Role {
  44. case "user":
  45. fmt.Printf(">>> %s\n", msg.Content)
  46. case "assistant":
  47. state := &displayResponseState{}
  48. displayResponse(msg.Content, opts.WordWrap, state)
  49. fmt.Println()
  50. fmt.Println()
  51. }
  52. }
  53. return nil
  54. })
  55. }
  56. func generateInteractive(cmd *cobra.Command, opts runOptions) error {
  57. err := loadModel(cmd, &opts)
  58. if err != nil {
  59. return err
  60. }
  61. usage := func() {
  62. fmt.Fprintln(os.Stderr, "Available Commands:")
  63. fmt.Fprintln(os.Stderr, " /set Set session variables")
  64. fmt.Fprintln(os.Stderr, " /show Show model information")
  65. fmt.Fprintln(os.Stderr, " /load <model> Load a session or model")
  66. fmt.Fprintln(os.Stderr, " /save <model> Save your current session")
  67. fmt.Fprintln(os.Stderr, " /clear Clear session context")
  68. fmt.Fprintln(os.Stderr, " /bye Exit")
  69. fmt.Fprintln(os.Stderr, " /?, /help Help for a command")
  70. fmt.Fprintln(os.Stderr, " /? shortcuts Help for keyboard shortcuts")
  71. fmt.Fprintln(os.Stderr, "")
  72. fmt.Fprintln(os.Stderr, "Use \"\"\" to begin a multi-line message.")
  73. if opts.MultiModal {
  74. fmt.Fprintf(os.Stderr, "Use %s to include .jpg or .png images.\n", filepath.FromSlash("/path/to/file"))
  75. }
  76. fmt.Fprintln(os.Stderr, "")
  77. }
  78. usageSet := func() {
  79. fmt.Fprintln(os.Stderr, "Available Commands:")
  80. fmt.Fprintln(os.Stderr, " /set parameter ... Set a parameter")
  81. fmt.Fprintln(os.Stderr, " /set system <string> Set system message")
  82. fmt.Fprintln(os.Stderr, " /set template <string> Set prompt template")
  83. fmt.Fprintln(os.Stderr, " /set history Enable history")
  84. fmt.Fprintln(os.Stderr, " /set nohistory Disable history")
  85. fmt.Fprintln(os.Stderr, " /set wordwrap Enable wordwrap")
  86. fmt.Fprintln(os.Stderr, " /set nowordwrap Disable wordwrap")
  87. fmt.Fprintln(os.Stderr, " /set format json Enable JSON mode")
  88. fmt.Fprintln(os.Stderr, " /set noformat Disable formatting")
  89. fmt.Fprintln(os.Stderr, " /set verbose Show LLM stats")
  90. fmt.Fprintln(os.Stderr, " /set quiet Disable LLM stats")
  91. fmt.Fprintln(os.Stderr, "")
  92. }
  93. usageShortcuts := func() {
  94. fmt.Fprintln(os.Stderr, "Available keyboard shortcuts:")
  95. fmt.Fprintln(os.Stderr, " Ctrl + a Move to the beginning of the line (Home)")
  96. fmt.Fprintln(os.Stderr, " Ctrl + e Move to the end of the line (End)")
  97. fmt.Fprintln(os.Stderr, " Alt + b Move back (left) one word")
  98. fmt.Fprintln(os.Stderr, " Alt + f Move forward (right) one word")
  99. fmt.Fprintln(os.Stderr, " Ctrl + k Delete the sentence after the cursor")
  100. fmt.Fprintln(os.Stderr, " Ctrl + u Delete the sentence before the cursor")
  101. fmt.Fprintln(os.Stderr, " Ctrl + w Delete the word before the cursor")
  102. fmt.Fprintln(os.Stderr, "")
  103. fmt.Fprintln(os.Stderr, " Ctrl + l Clear the screen")
  104. fmt.Fprintln(os.Stderr, " Ctrl + c Stop the model from responding")
  105. fmt.Fprintln(os.Stderr, " Ctrl + d Exit ollama (/bye)")
  106. fmt.Fprintln(os.Stderr, "")
  107. }
  108. usageShow := func() {
  109. fmt.Fprintln(os.Stderr, "Available Commands:")
  110. fmt.Fprintln(os.Stderr, " /show info Show details for this model")
  111. fmt.Fprintln(os.Stderr, " /show license Show model license")
  112. fmt.Fprintln(os.Stderr, " /show modelfile Show Modelfile for this model")
  113. fmt.Fprintln(os.Stderr, " /show parameters Show parameters for this model")
  114. fmt.Fprintln(os.Stderr, " /show system Show system message")
  115. fmt.Fprintln(os.Stderr, " /show template Show prompt template")
  116. fmt.Fprintln(os.Stderr, "")
  117. }
  118. // only list out the most common parameters
  119. usageParameters := func() {
  120. fmt.Fprintln(os.Stderr, "Available Parameters:")
  121. fmt.Fprintln(os.Stderr, " /set parameter seed <int> Random number seed")
  122. fmt.Fprintln(os.Stderr, " /set parameter num_predict <int> Max number of tokens to predict")
  123. fmt.Fprintln(os.Stderr, " /set parameter top_k <int> Pick from top k num of tokens")
  124. fmt.Fprintln(os.Stderr, " /set parameter top_p <float> Pick token based on sum of probabilities")
  125. fmt.Fprintln(os.Stderr, " /set parameter num_ctx <int> Set the context size")
  126. fmt.Fprintln(os.Stderr, " /set parameter temperature <float> Set creativity level")
  127. fmt.Fprintln(os.Stderr, " /set parameter repeat_penalty <float> How strongly to penalize repetitions")
  128. fmt.Fprintln(os.Stderr, " /set parameter repeat_last_n <int> Set how far back to look for repetitions")
  129. fmt.Fprintln(os.Stderr, " /set parameter num_gpu <int> The number of layers to send to the GPU")
  130. fmt.Fprintln(os.Stderr, " /set parameter stop <string> <string> ... Set the stop parameters")
  131. fmt.Fprintln(os.Stderr, "")
  132. }
  133. scanner, err := readline.New(readline.Prompt{
  134. Prompt: ">>> ",
  135. AltPrompt: "... ",
  136. Placeholder: "Send a message (/? for help)",
  137. AltPlaceholder: `Use """ to end multi-line input`,
  138. })
  139. if err != nil {
  140. return err
  141. }
  142. if envconfig.NoHistory {
  143. scanner.HistoryDisable()
  144. }
  145. fmt.Print(readline.StartBracketedPaste)
  146. defer fmt.Printf(readline.EndBracketedPaste)
  147. var sb strings.Builder
  148. var multiline MultilineState
  149. for {
  150. line, err := scanner.Readline()
  151. switch {
  152. case errors.Is(err, io.EOF):
  153. fmt.Println()
  154. return nil
  155. case errors.Is(err, readline.ErrInterrupt):
  156. if line == "" {
  157. fmt.Println("\nUse Ctrl + d or /bye to exit.")
  158. }
  159. scanner.Prompt.UseAlt = false
  160. sb.Reset()
  161. continue
  162. case err != nil:
  163. return err
  164. }
  165. switch {
  166. case multiline != MultilineNone:
  167. // check if there's a multiline terminating string
  168. before, ok := strings.CutSuffix(line, `"""`)
  169. sb.WriteString(before)
  170. if !ok {
  171. fmt.Fprintln(&sb)
  172. continue
  173. }
  174. switch multiline {
  175. case MultilineSystem:
  176. opts.System = sb.String()
  177. opts.Messages = append(opts.Messages, api.Message{Role: "system", Content: opts.System})
  178. fmt.Println("Set system message.")
  179. sb.Reset()
  180. case MultilineTemplate:
  181. opts.Template = sb.String()
  182. fmt.Println("Set prompt template.")
  183. sb.Reset()
  184. }
  185. multiline = MultilineNone
  186. scanner.Prompt.UseAlt = false
  187. case strings.HasPrefix(line, `"""`):
  188. line := strings.TrimPrefix(line, `"""`)
  189. line, ok := strings.CutSuffix(line, `"""`)
  190. sb.WriteString(line)
  191. if !ok {
  192. // no multiline terminating string; need more input
  193. fmt.Fprintln(&sb)
  194. multiline = MultilinePrompt
  195. scanner.Prompt.UseAlt = true
  196. }
  197. case scanner.Pasting:
  198. fmt.Fprintln(&sb, line)
  199. continue
  200. case strings.HasPrefix(line, "/list"):
  201. args := strings.Fields(line)
  202. if err := ListHandler(cmd, args[1:]); err != nil {
  203. return err
  204. }
  205. case strings.HasPrefix(line, "/load"):
  206. args := strings.Fields(line)
  207. if len(args) != 2 {
  208. fmt.Println("Usage:\n /load <modelname>")
  209. continue
  210. }
  211. opts.Model = args[1]
  212. opts.Messages = []api.Message{}
  213. fmt.Printf("Loading model '%s'\n", opts.Model)
  214. if err := loadModel(cmd, &opts); err != nil {
  215. return err
  216. }
  217. continue
  218. case strings.HasPrefix(line, "/save"):
  219. args := strings.Fields(line)
  220. if len(args) != 2 {
  221. fmt.Println("Usage:\n /save <modelname>")
  222. continue
  223. }
  224. client, err := api.ClientFromEnvironment()
  225. if err != nil {
  226. fmt.Println("error: couldn't connect to ollama server")
  227. return err
  228. }
  229. req := &api.CreateRequest{
  230. Name: args[1],
  231. Modelfile: buildModelfile(opts),
  232. }
  233. fn := func(resp api.ProgressResponse) error { return nil }
  234. err = client.Create(cmd.Context(), req, fn)
  235. if err != nil {
  236. if strings.Contains(err.Error(), errtypes.InvalidModelNameErrMsg) {
  237. fmt.Printf("error: The model name '%s' is invalid\n", args[1])
  238. continue
  239. }
  240. return err
  241. }
  242. fmt.Printf("Created new model '%s'\n", args[1])
  243. continue
  244. case strings.HasPrefix(line, "/clear"):
  245. opts.Messages = []api.Message{}
  246. if opts.System != "" {
  247. newMessage := api.Message{Role: "system", Content: opts.System}
  248. opts.Messages = append(opts.Messages, newMessage)
  249. }
  250. fmt.Println("Cleared session context")
  251. continue
  252. case strings.HasPrefix(line, "/set"):
  253. args := strings.Fields(line)
  254. if len(args) > 1 {
  255. switch args[1] {
  256. case "history":
  257. scanner.HistoryEnable()
  258. case "nohistory":
  259. scanner.HistoryDisable()
  260. case "wordwrap":
  261. opts.WordWrap = true
  262. fmt.Println("Set 'wordwrap' mode.")
  263. case "nowordwrap":
  264. opts.WordWrap = false
  265. fmt.Println("Set 'nowordwrap' mode.")
  266. case "verbose":
  267. if err := cmd.Flags().Set("verbose", "true"); err != nil {
  268. return err
  269. }
  270. fmt.Println("Set 'verbose' mode.")
  271. case "quiet":
  272. if err := cmd.Flags().Set("verbose", "false"); err != nil {
  273. return err
  274. }
  275. fmt.Println("Set 'quiet' mode.")
  276. case "format":
  277. if len(args) < 3 || args[2] != "json" {
  278. fmt.Println("Invalid or missing format. For 'json' mode use '/set format json'")
  279. } else {
  280. opts.Format = args[2]
  281. fmt.Printf("Set format to '%s' mode.\n", args[2])
  282. }
  283. case "noformat":
  284. opts.Format = ""
  285. fmt.Println("Disabled format.")
  286. case "parameter":
  287. if len(args) < 4 {
  288. usageParameters()
  289. continue
  290. }
  291. params := args[3:]
  292. fp, err := api.FormatParams(map[string][]string{args[2]: params})
  293. if err != nil {
  294. fmt.Printf("Couldn't set parameter: %q\n", err)
  295. continue
  296. }
  297. fmt.Printf("Set parameter '%s' to '%s'\n", args[2], strings.Join(params, ", "))
  298. opts.Options[args[2]] = fp[args[2]]
  299. case "system", "template":
  300. if len(args) < 3 {
  301. usageSet()
  302. continue
  303. }
  304. if args[1] == "system" {
  305. multiline = MultilineSystem
  306. } else if args[1] == "template" {
  307. multiline = MultilineTemplate
  308. }
  309. line := strings.Join(args[2:], " ")
  310. line, ok := strings.CutPrefix(line, `"""`)
  311. if !ok {
  312. multiline = MultilineNone
  313. } else {
  314. // only cut suffix if the line is multiline
  315. line, ok = strings.CutSuffix(line, `"""`)
  316. if ok {
  317. multiline = MultilineNone
  318. }
  319. }
  320. sb.WriteString(line)
  321. if multiline != MultilineNone {
  322. scanner.Prompt.UseAlt = true
  323. continue
  324. }
  325. if args[1] == "system" {
  326. opts.System = sb.String() // for display in modelfile
  327. newMessage := api.Message{Role: "system", Content: sb.String()}
  328. // Check if the slice is not empty and the last message is from 'system'
  329. if len(opts.Messages) > 0 && opts.Messages[len(opts.Messages)-1].Role == "system" {
  330. // Replace the last message
  331. opts.Messages[len(opts.Messages)-1] = newMessage
  332. } else {
  333. opts.Messages = append(opts.Messages, newMessage)
  334. }
  335. fmt.Println("Set system message.")
  336. sb.Reset()
  337. } else if args[1] == "template" {
  338. opts.Template = sb.String()
  339. fmt.Println("Set prompt template.")
  340. sb.Reset()
  341. }
  342. sb.Reset()
  343. continue
  344. default:
  345. fmt.Printf("Unknown command '/set %s'. Type /? for help\n", args[1])
  346. }
  347. } else {
  348. usageSet()
  349. }
  350. case strings.HasPrefix(line, "/show"):
  351. args := strings.Fields(line)
  352. if len(args) > 1 {
  353. client, err := api.ClientFromEnvironment()
  354. if err != nil {
  355. fmt.Println("error: couldn't connect to ollama server")
  356. return err
  357. }
  358. req := &api.ShowRequest{
  359. Name: opts.Model,
  360. System: opts.System,
  361. Template: opts.Template,
  362. Options: opts.Options,
  363. }
  364. resp, err := client.Show(cmd.Context(), req)
  365. if err != nil {
  366. fmt.Println("error: couldn't get model")
  367. return err
  368. }
  369. switch args[1] {
  370. case "info":
  371. showInfo(resp)
  372. case "license":
  373. if resp.License == "" {
  374. fmt.Println("No license was specified for this model.")
  375. } else {
  376. fmt.Println(resp.License)
  377. }
  378. case "modelfile":
  379. fmt.Println(resp.Modelfile)
  380. case "parameters":
  381. if resp.Parameters == "" {
  382. fmt.Println("No parameters were specified for this model.")
  383. } else {
  384. if len(opts.Options) > 0 {
  385. fmt.Println("User defined parameters:")
  386. for k, v := range opts.Options {
  387. fmt.Printf("%-*s %v\n", 30, k, v)
  388. }
  389. fmt.Println()
  390. }
  391. fmt.Println("Model defined parameters:")
  392. fmt.Println(resp.Parameters)
  393. }
  394. case "system":
  395. switch {
  396. case opts.System != "":
  397. fmt.Println(opts.System + "\n")
  398. case resp.System != "":
  399. fmt.Println(resp.System + "\n")
  400. default:
  401. fmt.Println("No system message was specified for this model.")
  402. }
  403. case "template":
  404. switch {
  405. case opts.Template != "":
  406. fmt.Println(opts.Template + "\n")
  407. case resp.Template != "":
  408. fmt.Println(resp.Template)
  409. default:
  410. fmt.Println("No prompt template was specified for this model.")
  411. }
  412. default:
  413. fmt.Printf("Unknown command '/show %s'. Type /? for help\n", args[1])
  414. }
  415. } else {
  416. usageShow()
  417. }
  418. case strings.HasPrefix(line, "/help"), strings.HasPrefix(line, "/?"):
  419. args := strings.Fields(line)
  420. if len(args) > 1 {
  421. switch args[1] {
  422. case "set", "/set":
  423. usageSet()
  424. case "show", "/show":
  425. usageShow()
  426. case "shortcut", "shortcuts":
  427. usageShortcuts()
  428. }
  429. } else {
  430. usage()
  431. }
  432. case strings.HasPrefix(line, "/exit"), strings.HasPrefix(line, "/bye"):
  433. return nil
  434. case strings.HasPrefix(line, "/"):
  435. args := strings.Fields(line)
  436. isFile := false
  437. if opts.MultiModal {
  438. for _, f := range extractFileNames(line) {
  439. if strings.HasPrefix(f, args[0]) {
  440. isFile = true
  441. break
  442. }
  443. }
  444. }
  445. if !isFile {
  446. fmt.Printf("Unknown command '%s'. Type /? for help\n", args[0])
  447. continue
  448. }
  449. sb.WriteString(line)
  450. default:
  451. sb.WriteString(line)
  452. }
  453. if sb.Len() > 0 && multiline == MultilineNone {
  454. newMessage := api.Message{Role: "user", Content: sb.String()}
  455. if opts.MultiModal {
  456. msg, images, err := extractFileData(sb.String())
  457. if err != nil {
  458. return err
  459. }
  460. // clear all previous images for better responses
  461. if len(images) > 0 {
  462. for i := range opts.Messages {
  463. opts.Messages[i].Images = nil
  464. }
  465. }
  466. newMessage.Content = msg
  467. newMessage.Images = images
  468. }
  469. opts.Messages = append(opts.Messages, newMessage)
  470. assistant, err := chat(cmd, opts)
  471. if err != nil {
  472. return err
  473. }
  474. if assistant != nil {
  475. opts.Messages = append(opts.Messages, *assistant)
  476. }
  477. sb.Reset()
  478. }
  479. }
  480. }
  481. func buildModelfile(opts runOptions) string {
  482. var mf strings.Builder
  483. model := opts.ParentModel
  484. if model == "" {
  485. model = opts.Model
  486. }
  487. fmt.Fprintf(&mf, "FROM %s\n", model)
  488. if opts.System != "" {
  489. fmt.Fprintf(&mf, "SYSTEM \"\"\"%s\"\"\"\n", opts.System)
  490. }
  491. if opts.Template != "" {
  492. fmt.Fprintf(&mf, "TEMPLATE \"\"\"%s\"\"\"\n", opts.Template)
  493. }
  494. keys := make([]string, 0)
  495. for k := range opts.Options {
  496. keys = append(keys, k)
  497. }
  498. sort.Strings(keys)
  499. for _, k := range keys {
  500. fmt.Fprintf(&mf, "PARAMETER %s %v\n", k, opts.Options[k])
  501. }
  502. fmt.Fprintln(&mf)
  503. for _, msg := range opts.Messages {
  504. fmt.Fprintf(&mf, "MESSAGE %s \"\"\"%s\"\"\"\n", msg.Role, msg.Content)
  505. }
  506. return mf.String()
  507. }
  508. func normalizeFilePath(fp string) string {
  509. // Define a map of escaped characters and their replacements
  510. replacements := map[string]string{
  511. "\\ ": " ", // Escaped space
  512. "\\(": "(", // Escaped left parenthesis
  513. "\\)": ")", // Escaped right parenthesis
  514. "\\[": "[", // Escaped left square bracket
  515. "\\]": "]", // Escaped right square bracket
  516. "\\{": "{", // Escaped left curly brace
  517. "\\}": "}", // Escaped right curly brace
  518. "\\$": "$", // Escaped dollar sign
  519. "\\&": "&", // Escaped ampersand
  520. "\\;": ";", // Escaped semicolon
  521. "\\'": "'", // Escaped single quote
  522. "\\\\": "\\", // Escaped backslash
  523. "\\*": "*", // Escaped asterisk
  524. "\\?": "?", // Escaped question mark
  525. }
  526. for escaped, actual := range replacements {
  527. fp = strings.ReplaceAll(fp, escaped, actual)
  528. }
  529. return fp
  530. }
  531. func extractFileNames(input string) []string {
  532. // Regex to match file paths starting with optional drive letter, / ./ \ or .\ and include escaped or unescaped spaces (\ or %20)
  533. // and followed by more characters and a file extension
  534. // This will capture non filename strings, but we'll check for file existence to remove mismatches
  535. regexPattern := `(?:[a-zA-Z]:)?(?:\./|/|\\)[\S\\ ]+?\.(?i:jpg|jpeg|png|svg)\b`
  536. re := regexp.MustCompile(regexPattern)
  537. return re.FindAllString(input, -1)
  538. }
  539. func extractFileData(input string) (string, []api.ImageData, error) {
  540. filePaths := extractFileNames(input)
  541. var imgs []api.ImageData
  542. for _, fp := range filePaths {
  543. nfp := normalizeFilePath(fp)
  544. data, err := getImageData(nfp)
  545. if err != nil {
  546. if os.IsNotExist(err) {
  547. continue
  548. }
  549. fmt.Fprintf(os.Stderr, "Couldn't process image: %q\n", err)
  550. return "", imgs, err
  551. }
  552. fmt.Fprintf(os.Stderr, "Added image '%s'\n", nfp)
  553. input = strings.ReplaceAll(input, fp, "")
  554. imgs = append(imgs, data)
  555. }
  556. return input, imgs, nil
  557. }
  558. func getImageData(filePath string) ([]byte, error) {
  559. file, err := os.Open(filePath)
  560. if err != nil {
  561. return nil, err
  562. }
  563. defer file.Close()
  564. buf := make([]byte, 512)
  565. _, err = file.Read(buf)
  566. if err != nil {
  567. return nil, err
  568. }
  569. contentType := http.DetectContentType(buf)
  570. allowedTypes := []string{"image/jpeg", "image/jpg", "image/png"}
  571. if !slices.Contains(allowedTypes, contentType) {
  572. return nil, fmt.Errorf("invalid image type: %s", contentType)
  573. }
  574. info, err := file.Stat()
  575. if err != nil {
  576. return nil, err
  577. }
  578. // Check if the file size exceeds 100MB
  579. var maxSize int64 = 100 * 1024 * 1024 // 100MB in bytes
  580. if info.Size() > maxSize {
  581. return nil, fmt.Errorf("file size exceeds maximum limit (100MB)")
  582. }
  583. buf = make([]byte, info.Size())
  584. _, err = file.Seek(0, 0)
  585. if err != nil {
  586. return nil, err
  587. }
  588. _, err = io.ReadFull(file, buf)
  589. if err != nil {
  590. return nil, err
  591. }
  592. return buf, nil
  593. }