config.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. package envconfig
  2. import (
  3. "errors"
  4. "fmt"
  5. "log/slog"
  6. "net"
  7. "os"
  8. "path/filepath"
  9. "runtime"
  10. "strconv"
  11. "strings"
  12. )
  13. type OllamaHost struct {
  14. Scheme string
  15. Host string
  16. Port string
  17. }
  18. func (o OllamaHost) String() string {
  19. return fmt.Sprintf("%s://%s:%s", o.Scheme, o.Host, o.Port)
  20. }
  21. var ErrInvalidHostPort = errors.New("invalid port specified in OLLAMA_HOST")
  22. var (
  23. // Set via OLLAMA_ORIGINS in the environment
  24. AllowOrigins []string
  25. // Set via OLLAMA_DEBUG in the environment
  26. Debug bool
  27. // Experimental flash attention
  28. FlashAttention bool
  29. // Set via OLLAMA_HOST in the environment
  30. Host *OllamaHost
  31. // Set via OLLAMA_KEEP_ALIVE in the environment
  32. KeepAlive string
  33. // Set via OLLAMA_LLM_LIBRARY in the environment
  34. LLMLibrary string
  35. // Set via OLLAMA_MAX_LOADED_MODELS in the environment
  36. MaxRunners int
  37. // Set via OLLAMA_MAX_QUEUE in the environment
  38. MaxQueuedRequests int
  39. // Set via OLLAMA_MODELS in the environment
  40. ModelsDir string
  41. // Set via OLLAMA_MAX_VRAM in the environment
  42. MaxVRAM uint64
  43. // Set via OLLAMA_NOHISTORY in the environment
  44. NoHistory bool
  45. // Set via OLLAMA_NOPRUNE in the environment
  46. NoPrune bool
  47. // Set via OLLAMA_NUM_PARALLEL in the environment
  48. NumParallel int
  49. // Set via OLLAMA_RUNNERS_DIR in the environment
  50. RunnersDir string
  51. // Set via OLLAMA_SCHED_SPREAD in the environment
  52. SchedSpread bool
  53. // Set via OLLAMA_TMPDIR in the environment
  54. TmpDir string
  55. )
  56. type EnvVar struct {
  57. Name string
  58. Value any
  59. Description string
  60. }
  61. func AsMap() map[string]EnvVar {
  62. return map[string]EnvVar{
  63. "OLLAMA_DEBUG": {"OLLAMA_DEBUG", Debug, "Show additional debug information (e.g. OLLAMA_DEBUG=1)"},
  64. "OLLAMA_FLASH_ATTENTION": {"OLLAMA_FLASH_ATTENTION", FlashAttention, "Enabled flash attention"},
  65. "OLLAMA_HOST": {"OLLAMA_HOST", Host, "IP Address for the ollama server (default 127.0.0.1:11434)"},
  66. "OLLAMA_KEEP_ALIVE": {"OLLAMA_KEEP_ALIVE", KeepAlive, "The duration that models stay loaded in memory (default \"5m\")"},
  67. "OLLAMA_LLM_LIBRARY": {"OLLAMA_LLM_LIBRARY", LLMLibrary, "Set LLM library to bypass autodetection"},
  68. "OLLAMA_MAX_LOADED_MODELS": {"OLLAMA_MAX_LOADED_MODELS", MaxRunners, "Maximum number of loaded models (default 1)"},
  69. "OLLAMA_MAX_QUEUE": {"OLLAMA_MAX_QUEUE", MaxQueuedRequests, "Maximum number of queued requests"},
  70. "OLLAMA_MAX_VRAM": {"OLLAMA_MAX_VRAM", MaxVRAM, "Maximum VRAM"},
  71. "OLLAMA_MODELS": {"OLLAMA_MODELS", ModelsDir, "The path to the models directory"},
  72. "OLLAMA_NOHISTORY": {"OLLAMA_NOHISTORY", NoHistory, "Do not preserve readline history"},
  73. "OLLAMA_NOPRUNE": {"OLLAMA_NOPRUNE", NoPrune, "Do not prune model blobs on startup"},
  74. "OLLAMA_NUM_PARALLEL": {"OLLAMA_NUM_PARALLEL", NumParallel, "Maximum number of parallel requests (default 1)"},
  75. "OLLAMA_ORIGINS": {"OLLAMA_ORIGINS", AllowOrigins, "A comma separated list of allowed origins"},
  76. "OLLAMA_RUNNERS_DIR": {"OLLAMA_RUNNERS_DIR", RunnersDir, "Location for runners"},
  77. "OLLAMA_SCHED_SPREAD": {"OLLAMA_SCHED_SPREAD", SchedSpread, "Always schedule model across all GPUs"},
  78. "OLLAMA_TMPDIR": {"OLLAMA_TMPDIR", TmpDir, "Location for temporary files"},
  79. }
  80. }
  81. func Values() map[string]string {
  82. vals := make(map[string]string)
  83. for k, v := range AsMap() {
  84. vals[k] = fmt.Sprintf("%v", v.Value)
  85. }
  86. return vals
  87. }
  88. var defaultAllowOrigins = []string{
  89. "localhost",
  90. "127.0.0.1",
  91. "0.0.0.0",
  92. }
  93. // Clean quotes and spaces from the value
  94. func clean(key string) string {
  95. return strings.Trim(os.Getenv(key), "\"' ")
  96. }
  97. func init() {
  98. // default values
  99. NumParallel = 1
  100. MaxRunners = 1
  101. MaxQueuedRequests = 512
  102. LoadConfig()
  103. }
  104. func LoadConfig() {
  105. if debug := clean("OLLAMA_DEBUG"); debug != "" {
  106. d, err := strconv.ParseBool(debug)
  107. if err == nil {
  108. Debug = d
  109. } else {
  110. Debug = true
  111. }
  112. }
  113. if fa := clean("OLLAMA_FLASH_ATTENTION"); fa != "" {
  114. d, err := strconv.ParseBool(fa)
  115. if err == nil {
  116. FlashAttention = d
  117. }
  118. }
  119. RunnersDir = clean("OLLAMA_RUNNERS_DIR")
  120. if runtime.GOOS == "windows" && RunnersDir == "" {
  121. // On Windows we do not carry the payloads inside the main executable
  122. appExe, err := os.Executable()
  123. if err != nil {
  124. slog.Error("failed to lookup executable path", "error", err)
  125. }
  126. cwd, err := os.Getwd()
  127. if err != nil {
  128. slog.Error("failed to lookup working directory", "error", err)
  129. }
  130. var paths []string
  131. for _, root := range []string{filepath.Dir(appExe), cwd} {
  132. paths = append(paths,
  133. root,
  134. filepath.Join(root, "windows-"+runtime.GOARCH),
  135. filepath.Join(root, "dist", "windows-"+runtime.GOARCH),
  136. )
  137. }
  138. // Try a few variations to improve developer experience when building from source in the local tree
  139. for _, p := range paths {
  140. candidate := filepath.Join(p, "ollama_runners")
  141. _, err := os.Stat(candidate)
  142. if err == nil {
  143. RunnersDir = candidate
  144. break
  145. }
  146. }
  147. if RunnersDir == "" {
  148. slog.Error("unable to locate llm runner directory. Set OLLAMA_RUNNERS_DIR to the location of 'ollama_runners'")
  149. }
  150. }
  151. TmpDir = clean("OLLAMA_TMPDIR")
  152. userLimit := clean("OLLAMA_MAX_VRAM")
  153. if userLimit != "" {
  154. avail, err := strconv.ParseUint(userLimit, 10, 64)
  155. if err != nil {
  156. slog.Error("invalid setting, ignoring", "OLLAMA_MAX_VRAM", userLimit, "error", err)
  157. } else {
  158. MaxVRAM = avail
  159. }
  160. }
  161. LLMLibrary = clean("OLLAMA_LLM_LIBRARY")
  162. if onp := clean("OLLAMA_NUM_PARALLEL"); onp != "" {
  163. val, err := strconv.Atoi(onp)
  164. if err != nil || val <= 0 {
  165. slog.Error("invalid setting must be greater than zero", "OLLAMA_NUM_PARALLEL", onp, "error", err)
  166. } else {
  167. NumParallel = val
  168. }
  169. }
  170. if nohistory := clean("OLLAMA_NOHISTORY"); nohistory != "" {
  171. NoHistory = true
  172. }
  173. if spread := clean("OLLAMA_SCHED_SPREAD"); spread != "" {
  174. s, err := strconv.ParseBool(spread)
  175. if err == nil {
  176. SchedSpread = s
  177. } else {
  178. SchedSpread = true
  179. }
  180. }
  181. if noprune := clean("OLLAMA_NOPRUNE"); noprune != "" {
  182. NoPrune = true
  183. }
  184. if origins := clean("OLLAMA_ORIGINS"); origins != "" {
  185. AllowOrigins = strings.Split(origins, ",")
  186. }
  187. for _, allowOrigin := range defaultAllowOrigins {
  188. AllowOrigins = append(AllowOrigins,
  189. fmt.Sprintf("http://%s", allowOrigin),
  190. fmt.Sprintf("https://%s", allowOrigin),
  191. fmt.Sprintf("http://%s", net.JoinHostPort(allowOrigin, "*")),
  192. fmt.Sprintf("https://%s", net.JoinHostPort(allowOrigin, "*")),
  193. )
  194. }
  195. AllowOrigins = append(AllowOrigins,
  196. "app://*",
  197. "file://*",
  198. "tauri://*",
  199. )
  200. maxRunners := clean("OLLAMA_MAX_LOADED_MODELS")
  201. if maxRunners != "" {
  202. m, err := strconv.Atoi(maxRunners)
  203. if err != nil {
  204. slog.Error("invalid setting", "OLLAMA_MAX_LOADED_MODELS", maxRunners, "error", err)
  205. } else {
  206. MaxRunners = m
  207. }
  208. }
  209. if onp := os.Getenv("OLLAMA_MAX_QUEUE"); onp != "" {
  210. p, err := strconv.Atoi(onp)
  211. if err != nil || p <= 0 {
  212. slog.Error("invalid setting", "OLLAMA_MAX_QUEUE", onp, "error", err)
  213. } else {
  214. MaxQueuedRequests = p
  215. }
  216. }
  217. KeepAlive = clean("OLLAMA_KEEP_ALIVE")
  218. var err error
  219. ModelsDir, err = getModelsDir()
  220. if err != nil {
  221. slog.Error("invalid setting", "OLLAMA_MODELS", ModelsDir, "error", err)
  222. }
  223. Host, err = getOllamaHost()
  224. if err != nil {
  225. slog.Error("invalid setting", "OLLAMA_HOST", Host, "error", err, "using default port", Host.Port)
  226. }
  227. }
  228. func getModelsDir() (string, error) {
  229. if models, exists := os.LookupEnv("OLLAMA_MODELS"); exists {
  230. return models, nil
  231. }
  232. home, err := os.UserHomeDir()
  233. if err != nil {
  234. return "", err
  235. }
  236. return filepath.Join(home, ".ollama", "models"), nil
  237. }
  238. func getOllamaHost() (*OllamaHost, error) {
  239. defaultPort := "11434"
  240. hostVar := os.Getenv("OLLAMA_HOST")
  241. hostVar = strings.TrimSpace(strings.Trim(strings.TrimSpace(hostVar), "\"'"))
  242. scheme, hostport, ok := strings.Cut(hostVar, "://")
  243. switch {
  244. case !ok:
  245. scheme, hostport = "http", hostVar
  246. case scheme == "http":
  247. defaultPort = "80"
  248. case scheme == "https":
  249. defaultPort = "443"
  250. }
  251. // trim trailing slashes
  252. hostport = strings.TrimRight(hostport, "/")
  253. host, port, err := net.SplitHostPort(hostport)
  254. if err != nil {
  255. host, port = "127.0.0.1", defaultPort
  256. if ip := net.ParseIP(strings.Trim(hostport, "[]")); ip != nil {
  257. host = ip.String()
  258. } else if hostport != "" {
  259. host = hostport
  260. }
  261. }
  262. if portNum, err := strconv.ParseInt(port, 10, 32); err != nil || portNum > 65535 || portNum < 0 {
  263. return &OllamaHost{
  264. Scheme: scheme,
  265. Host: host,
  266. Port: defaultPort,
  267. }, ErrInvalidHostPort
  268. }
  269. return &OllamaHost{
  270. Scheme: scheme,
  271. Host: host,
  272. Port: port,
  273. }, nil
  274. }