config.go 9.36 KB
Newer Older
1
2
3
package envconfig

import (
4
	"errors"
5
6
	"fmt"
	"log/slog"
7
	"math"
Michael Yang's avatar
Michael Yang committed
8
	"net"
Michael Yang's avatar
host  
Michael Yang committed
9
	"net/url"
10
11
12
13
14
	"os"
	"path/filepath"
	"runtime"
	"strconv"
	"strings"
15
	"time"
16
17
)

18
19
var ErrInvalidHostPort = errors.New("invalid port specified in OLLAMA_HOST")

Michael Yang's avatar
host  
Michael Yang committed
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Host returns the scheme and host. Host can be configured via the OLLAMA_HOST environment variable.
// Default is scheme "http" and host "127.0.0.1:11434"
func Host() *url.URL {
	defaultPort := "11434"

	s := os.Getenv("OLLAMA_HOST")
	s = strings.TrimSpace(strings.Trim(strings.TrimSpace(s), "\"'"))
	scheme, hostport, ok := strings.Cut(s, "://")
	switch {
	case !ok:
		scheme, hostport = "http", s
	case scheme == "http":
		defaultPort = "80"
	case scheme == "https":
		defaultPort = "443"
	}

	// trim trailing slashes
	hostport = strings.TrimRight(hostport, "/")

	host, port, err := net.SplitHostPort(hostport)
	if err != nil {
		host, port = "127.0.0.1", defaultPort
		if ip := net.ParseIP(strings.Trim(hostport, "[]")); ip != nil {
			host = ip.String()
		} else if hostport != "" {
			host = hostport
		}
	}

	if n, err := strconv.ParseInt(port, 10, 32); err != nil || n > 65535 || n < 0 {
		return &url.URL{
			Scheme: scheme,
			Host:   net.JoinHostPort(host, defaultPort),
		}
	}

	return &url.URL{
		Scheme: scheme,
		Host:   net.JoinHostPort(host, port),
	}
}

Michael Yang's avatar
origins  
Michael Yang committed
63
64
// Origins returns a list of allowed origins. Origins can be configured via the OLLAMA_ORIGINS environment variable.
func Origins() (origins []string) {
Michael Yang's avatar
bool  
Michael Yang committed
65
	if s := getenv("OLLAMA_ORIGINS"); s != "" {
Michael Yang's avatar
origins  
Michael Yang committed
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
		origins = strings.Split(s, ",")
	}

	for _, origin := range []string{"localhost", "127.0.0.1", "0.0.0.0"} {
		origins = append(origins,
			fmt.Sprintf("http://%s", origin),
			fmt.Sprintf("https://%s", origin),
			fmt.Sprintf("http://%s", net.JoinHostPort(origin, "*")),
			fmt.Sprintf("https://%s", net.JoinHostPort(origin, "*")),
		)
	}

	origins = append(origins,
		"app://*",
		"file://*",
		"tauri://*",
	)

	return origins
}

Michael Yang's avatar
models  
Michael Yang committed
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// Models returns the path to the models directory. Models directory can be configured via the OLLAMA_MODELS environment variable.
// Default is $HOME/.ollama/models
func Models() string {
	if s, ok := os.LookupEnv("OLLAMA_MODELS"); ok {
		return s
	}

	home, err := os.UserHomeDir()
	if err != nil {
		panic(err)
	}

	return filepath.Join(home, ".ollama", "models")
}

Michael Yang's avatar
bool  
Michael Yang committed
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
func Bool(k string) func() bool {
	return func() bool {
		if s := getenv(k); s != "" {
			b, err := strconv.ParseBool(s)
			if err != nil {
				return true
			}

			return b
		}

		return false
	}
}

var (
	// Debug enabled additional debug information.
	Debug = Bool("OLLAMA_DEBUG")
	// FlashAttention enables the experimental flash attention feature.
	FlashAttention = Bool("OLLAMA_FLASH_ATTENTION")
	// NoHistory disables readline history.
	NoHistory = Bool("OLLAMA_NOHISTORY")
	// NoPrune disables pruning of model blobs on startup.
	NoPrune = Bool("OLLAMA_NOPRUNE")
	// SchedSpread allows scheduling models across all GPUs.
	SchedSpread = Bool("OLLAMA_SCHED_SPREAD")
	// IntelGPU enables experimental Intel GPU detection.
	IntelGPU = Bool("OLLAMA_INTEL_GPU")
)

132
var (
133
	// Set via OLLAMA_KEEP_ALIVE in the environment
134
	KeepAlive time.Duration
135
136
137
138
139
140
141
142
143
144
145
146
	// Set via OLLAMA_LLM_LIBRARY in the environment
	LLMLibrary string
	// Set via OLLAMA_MAX_LOADED_MODELS in the environment
	MaxRunners int
	// Set via OLLAMA_MAX_QUEUE in the environment
	MaxQueuedRequests int
	// Set via OLLAMA_NUM_PARALLEL in the environment
	NumParallel int
	// Set via OLLAMA_RUNNERS_DIR in the environment
	RunnersDir string
	// Set via OLLAMA_TMPDIR in the environment
	TmpDir string
147
148
149
150
151
152
153
154
155
156
157

	// Set via CUDA_VISIBLE_DEVICES in the environment
	CudaVisibleDevices string
	// Set via HIP_VISIBLE_DEVICES in the environment
	HipVisibleDevices string
	// Set via ROCR_VISIBLE_DEVICES in the environment
	RocrVisibleDevices string
	// Set via GPU_DEVICE_ORDINAL in the environment
	GpuDeviceOrdinal string
	// Set via HSA_OVERRIDE_GFX_VERSION in the environment
	HsaOverrideGfxVersion string
158
159
)

160
161
162
163
164
165
166
type EnvVar struct {
	Name        string
	Value       any
	Description string
}

func AsMap() map[string]EnvVar {
167
	ret := map[string]EnvVar{
Michael Yang's avatar
Michael Yang committed
168
		"OLLAMA_DEBUG":             {"OLLAMA_DEBUG", Debug(), "Show additional debug information (e.g. OLLAMA_DEBUG=1)"},
Michael Yang's avatar
bool  
Michael Yang committed
169
		"OLLAMA_FLASH_ATTENTION":   {"OLLAMA_FLASH_ATTENTION", FlashAttention(), "Enabled flash attention"},
Michael Yang's avatar
host  
Michael Yang committed
170
		"OLLAMA_HOST":              {"OLLAMA_HOST", Host(), "IP Address for the ollama server (default 127.0.0.1:11434)"},
171
		"OLLAMA_KEEP_ALIVE":        {"OLLAMA_KEEP_ALIVE", KeepAlive, "The duration that models stay loaded in memory (default \"5m\")"},
172
		"OLLAMA_LLM_LIBRARY":       {"OLLAMA_LLM_LIBRARY", LLMLibrary, "Set LLM library to bypass autodetection"},
173
		"OLLAMA_MAX_LOADED_MODELS": {"OLLAMA_MAX_LOADED_MODELS", MaxRunners, "Maximum number of loaded models per GPU"},
174
		"OLLAMA_MAX_QUEUE":         {"OLLAMA_MAX_QUEUE", MaxQueuedRequests, "Maximum number of queued requests"},
Michael Yang's avatar
models  
Michael Yang committed
175
		"OLLAMA_MODELS":            {"OLLAMA_MODELS", Models(), "The path to the models directory"},
Michael Yang's avatar
bool  
Michael Yang committed
176
177
		"OLLAMA_NOHISTORY":         {"OLLAMA_NOHISTORY", NoHistory(), "Do not preserve readline history"},
		"OLLAMA_NOPRUNE":           {"OLLAMA_NOPRUNE", NoPrune(), "Do not prune model blobs on startup"},
178
		"OLLAMA_NUM_PARALLEL":      {"OLLAMA_NUM_PARALLEL", NumParallel, "Maximum number of parallel requests"},
Michael Yang's avatar
origins  
Michael Yang committed
179
		"OLLAMA_ORIGINS":           {"OLLAMA_ORIGINS", Origins(), "A comma separated list of allowed origins"},
180
		"OLLAMA_RUNNERS_DIR":       {"OLLAMA_RUNNERS_DIR", RunnersDir, "Location for runners"},
Michael Yang's avatar
bool  
Michael Yang committed
181
		"OLLAMA_SCHED_SPREAD":      {"OLLAMA_SCHED_SPREAD", SchedSpread(), "Always schedule model across all GPUs"},
182
		"OLLAMA_TMPDIR":            {"OLLAMA_TMPDIR", TmpDir, "Location for temporary files"},
183
	}
184
185
186
187
188
189
	if runtime.GOOS != "darwin" {
		ret["CUDA_VISIBLE_DEVICES"] = EnvVar{"CUDA_VISIBLE_DEVICES", CudaVisibleDevices, "Set which NVIDIA devices are visible"}
		ret["HIP_VISIBLE_DEVICES"] = EnvVar{"HIP_VISIBLE_DEVICES", HipVisibleDevices, "Set which AMD devices are visible"}
		ret["ROCR_VISIBLE_DEVICES"] = EnvVar{"ROCR_VISIBLE_DEVICES", RocrVisibleDevices, "Set which AMD devices are visible"}
		ret["GPU_DEVICE_ORDINAL"] = EnvVar{"GPU_DEVICE_ORDINAL", GpuDeviceOrdinal, "Set which AMD devices are visible"}
		ret["HSA_OVERRIDE_GFX_VERSION"] = EnvVar{"HSA_OVERRIDE_GFX_VERSION", HsaOverrideGfxVersion, "Override the gfx used for all detected AMD GPUs"}
Michael Yang's avatar
bool  
Michael Yang committed
190
		ret["OLLAMA_INTEL_GPU"] = EnvVar{"OLLAMA_INTEL_GPU", IntelGPU(), "Enable experimental Intel GPU detection"}
191
192
	}
	return ret
193
194
}

195
196
197
198
199
200
201
202
func Values() map[string]string {
	vals := make(map[string]string)
	for k, v := range AsMap() {
		vals[k] = fmt.Sprintf("%v", v.Value)
	}
	return vals
}

Michael Yang's avatar
bool  
Michael Yang committed
203
204
// getenv returns an environment variable stripped of leading and trailing quotes or spaces
func getenv(key string) string {
205
206
207
208
209
	return strings.Trim(os.Getenv(key), "\"' ")
}

func init() {
	// default values
210
211
	NumParallel = 0 // Autoselect
	MaxRunners = 0  // Autoselect
212
	MaxQueuedRequests = 512
213
	KeepAlive = 5 * time.Minute
214
215
216
217
218

	LoadConfig()
}

func LoadConfig() {
Michael Yang's avatar
bool  
Michael Yang committed
219
	RunnersDir = getenv("OLLAMA_RUNNERS_DIR")
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
	if runtime.GOOS == "windows" && RunnersDir == "" {
		// On Windows we do not carry the payloads inside the main executable
		appExe, err := os.Executable()
		if err != nil {
			slog.Error("failed to lookup executable path", "error", err)
		}

		cwd, err := os.Getwd()
		if err != nil {
			slog.Error("failed to lookup working directory", "error", err)
		}

		var paths []string
		for _, root := range []string{filepath.Dir(appExe), cwd} {
			paths = append(paths,
Michael Yang's avatar
Michael Yang committed
235
				root,
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
				filepath.Join(root, "windows-"+runtime.GOARCH),
				filepath.Join(root, "dist", "windows-"+runtime.GOARCH),
			)
		}

		// Try a few variations to improve developer experience when building from source in the local tree
		for _, p := range paths {
			candidate := filepath.Join(p, "ollama_runners")
			_, err := os.Stat(candidate)
			if err == nil {
				RunnersDir = candidate
				break
			}
		}
		if RunnersDir == "" {
			slog.Error("unable to locate llm runner directory.  Set OLLAMA_RUNNERS_DIR to the location of 'ollama_runners'")
		}
	}

Michael Yang's avatar
bool  
Michael Yang committed
255
	TmpDir = getenv("OLLAMA_TMPDIR")
256

Michael Yang's avatar
bool  
Michael Yang committed
257
	LLMLibrary = getenv("OLLAMA_LLM_LIBRARY")
258

Michael Yang's avatar
bool  
Michael Yang committed
259
	if onp := getenv("OLLAMA_NUM_PARALLEL"); onp != "" {
260
		val, err := strconv.Atoi(onp)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
261
262
		if err != nil {
			slog.Error("invalid setting, ignoring", "OLLAMA_NUM_PARALLEL", onp, "error", err)
263
264
265
266
267
		} else {
			NumParallel = val
		}
	}

Michael Yang's avatar
bool  
Michael Yang committed
268
	maxRunners := getenv("OLLAMA_MAX_LOADED_MODELS")
269
270
271
	if maxRunners != "" {
		m, err := strconv.Atoi(maxRunners)
		if err != nil {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
272
			slog.Error("invalid setting, ignoring", "OLLAMA_MAX_LOADED_MODELS", maxRunners, "error", err)
273
274
275
276
277
278
279
280
		} else {
			MaxRunners = m
		}
	}

	if onp := os.Getenv("OLLAMA_MAX_QUEUE"); onp != "" {
		p, err := strconv.Atoi(onp)
		if err != nil || p <= 0 {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
281
			slog.Error("invalid setting, ignoring", "OLLAMA_MAX_QUEUE", onp, "error", err)
282
283
284
285
		} else {
			MaxQueuedRequests = p
		}
	}
286

Michael Yang's avatar
bool  
Michael Yang committed
287
	ka := getenv("OLLAMA_KEEP_ALIVE")
288
289
290
	if ka != "" {
		loadKeepAlive(ka)
	}
291

Michael Yang's avatar
bool  
Michael Yang committed
292
293
294
295
296
	CudaVisibleDevices = getenv("CUDA_VISIBLE_DEVICES")
	HipVisibleDevices = getenv("HIP_VISIBLE_DEVICES")
	RocrVisibleDevices = getenv("ROCR_VISIBLE_DEVICES")
	GpuDeviceOrdinal = getenv("GPU_DEVICE_ORDINAL")
	HsaOverrideGfxVersion = getenv("HSA_OVERRIDE_GFX_VERSION")
297
298
}

299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
func loadKeepAlive(ka string) {
	v, err := strconv.Atoi(ka)
	if err != nil {
		d, err := time.ParseDuration(ka)
		if err == nil {
			if d < 0 {
				KeepAlive = time.Duration(math.MaxInt64)
			} else {
				KeepAlive = d
			}
		}
	} else {
		d := time.Duration(v) * time.Second
		if d < 0 {
			KeepAlive = time.Duration(math.MaxInt64)
		} else {
			KeepAlive = d
		}
	}
}