config.go 10.0 KB

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