llmctl-cli 0.4.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- llmctl/__init__.py +12 -0
- llmctl/__main__.py +10 -0
- llmctl/bench.py +192 -0
- llmctl/cache.py +109 -0
- llmctl/chat.py +199 -0
- llmctl/cli.py +1275 -0
- llmctl/completions.py +321 -0
- llmctl/config.py +718 -0
- llmctl/doctor.py +204 -0
- llmctl/hardware.py +506 -0
- llmctl/hf.py +580 -0
- llmctl/http_client.py +187 -0
- llmctl/presets.py +288 -0
- llmctl/server_installer.py +350 -0
- llmctl/service/__init__.py +42 -0
- llmctl/service/base.py +282 -0
- llmctl/service/launchd.py +190 -0
- llmctl/service/process.py +300 -0
- llmctl/service/remote.py +80 -0
- llmctl/service/systemd.py +212 -0
- llmctl/skills.py +418 -0
- llmctl/tester.py +408 -0
- llmctl/ui.py +194 -0
- llmctl_cli-0.4.1.dist-info/METADATA +173 -0
- llmctl_cli-0.4.1.dist-info/RECORD +28 -0
- llmctl_cli-0.4.1.dist-info/WHEEL +4 -0
- llmctl_cli-0.4.1.dist-info/entry_points.txt +5 -0
- llmctl_cli-0.4.1.dist-info/licenses/LICENSE +21 -0
llmctl/config.py
ADDED
|
@@ -0,0 +1,718 @@
|
|
|
1
|
+
"""Cross-platform configuration, path resolution, and settings loading."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import shutil
|
|
7
|
+
import sys
|
|
8
|
+
import tomllib
|
|
9
|
+
from collections.abc import Mapping
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
from urllib.parse import urlparse
|
|
14
|
+
|
|
15
|
+
DEFAULT_HOST = "127.0.0.1"
|
|
16
|
+
DEFAULT_PORT = 8080
|
|
17
|
+
DEFAULT_MODELS_MAX = 1
|
|
18
|
+
LOOPBACK_HOSTS = {"127.0.0.1", "localhost", "::1", "0.0.0.0"} # noqa: S104
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _env_map(env: Mapping[str, str] | None) -> Mapping[str, str]:
|
|
22
|
+
return os.environ if env is None else env
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _platform(sys_platform: str | None) -> str:
|
|
26
|
+
return sys.platform if sys_platform is None else sys_platform
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _home_dir(home: Path | None) -> Path:
|
|
30
|
+
return Path.home() if home is None else home
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def platform_config_dir(
|
|
34
|
+
app: str,
|
|
35
|
+
*,
|
|
36
|
+
sys_platform: str | None = None,
|
|
37
|
+
env: Mapping[str, str] | None = None,
|
|
38
|
+
home: Path | None = None,
|
|
39
|
+
) -> Path:
|
|
40
|
+
"""Return the OS-idiomatic user configuration directory for *app*."""
|
|
41
|
+
plat = _platform(sys_platform)
|
|
42
|
+
environ = _env_map(env)
|
|
43
|
+
user_home = _home_dir(home)
|
|
44
|
+
|
|
45
|
+
if plat == "win32":
|
|
46
|
+
appdata = environ.get("APPDATA", "").strip()
|
|
47
|
+
base = Path(appdata) if appdata else user_home / "AppData" / "Roaming"
|
|
48
|
+
return base / app
|
|
49
|
+
if plat == "darwin":
|
|
50
|
+
return user_home / "Library" / "Application Support" / app
|
|
51
|
+
|
|
52
|
+
xdg = environ.get("XDG_CONFIG_HOME", "").strip()
|
|
53
|
+
base = Path(xdg) if xdg else user_home / ".config"
|
|
54
|
+
return base / app
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def platform_state_dir(
|
|
58
|
+
app: str,
|
|
59
|
+
*,
|
|
60
|
+
sys_platform: str | None = None,
|
|
61
|
+
env: Mapping[str, str] | None = None,
|
|
62
|
+
home: Path | None = None,
|
|
63
|
+
) -> Path:
|
|
64
|
+
"""Return the OS-idiomatic runtime state directory (PIDs, metadata)."""
|
|
65
|
+
plat = _platform(sys_platform)
|
|
66
|
+
environ = _env_map(env)
|
|
67
|
+
user_home = _home_dir(home)
|
|
68
|
+
|
|
69
|
+
if plat == "win32":
|
|
70
|
+
local = environ.get("LOCALAPPDATA", "").strip()
|
|
71
|
+
base = Path(local) if local else user_home / "AppData" / "Local"
|
|
72
|
+
return base / app
|
|
73
|
+
if plat == "darwin":
|
|
74
|
+
return user_home / "Library" / "Application Support" / app / "state"
|
|
75
|
+
|
|
76
|
+
xdg = environ.get("XDG_STATE_HOME", "").strip()
|
|
77
|
+
base = Path(xdg) if xdg else user_home / ".local" / "state"
|
|
78
|
+
return base / app
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def platform_log_dir(
|
|
82
|
+
app: str,
|
|
83
|
+
*,
|
|
84
|
+
sys_platform: str | None = None,
|
|
85
|
+
env: Mapping[str, str] | None = None,
|
|
86
|
+
home: Path | None = None,
|
|
87
|
+
) -> Path:
|
|
88
|
+
"""Return the OS-idiomatic user log directory."""
|
|
89
|
+
plat = _platform(sys_platform)
|
|
90
|
+
environ = _env_map(env)
|
|
91
|
+
user_home = _home_dir(home)
|
|
92
|
+
|
|
93
|
+
if plat == "win32":
|
|
94
|
+
local = environ.get("LOCALAPPDATA", "").strip()
|
|
95
|
+
base = Path(local) if local else user_home / "AppData" / "Local"
|
|
96
|
+
return base / app / "logs"
|
|
97
|
+
if plat == "darwin":
|
|
98
|
+
return user_home / "Library" / "Logs" / app
|
|
99
|
+
|
|
100
|
+
return platform_state_dir(app, sys_platform=plat, env=environ, home=user_home) / "logs"
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def default_models_ini(
|
|
104
|
+
*,
|
|
105
|
+
sys_platform: str | None = None,
|
|
106
|
+
env: Mapping[str, str] | None = None,
|
|
107
|
+
home: Path | None = None,
|
|
108
|
+
) -> Path:
|
|
109
|
+
"""Resolve models.ini path, preserving legacy ~/.config/llama.cpp/models.ini if present."""
|
|
110
|
+
user_home = _home_dir(home)
|
|
111
|
+
legacy = user_home / ".config" / "llama.cpp" / "models.ini"
|
|
112
|
+
if legacy.exists():
|
|
113
|
+
return legacy
|
|
114
|
+
return (
|
|
115
|
+
platform_config_dir("llama.cpp", sys_platform=sys_platform, env=env, home=user_home)
|
|
116
|
+
/ "models.ini"
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def default_hf_cache(
|
|
121
|
+
*,
|
|
122
|
+
env: Mapping[str, str] | None = None,
|
|
123
|
+
home: Path | None = None,
|
|
124
|
+
) -> Path:
|
|
125
|
+
"""Resolve Hugging Face Hub cache directory following official HF env vars."""
|
|
126
|
+
environ = _env_map(env)
|
|
127
|
+
user_home = _home_dir(home)
|
|
128
|
+
|
|
129
|
+
hub_cache = environ.get("HF_HUB_CACHE", "").strip()
|
|
130
|
+
if hub_cache:
|
|
131
|
+
return Path(hub_cache).expanduser()
|
|
132
|
+
hf_home = environ.get("HF_HOME", "").strip()
|
|
133
|
+
if hf_home:
|
|
134
|
+
return Path(hf_home).expanduser() / "hub"
|
|
135
|
+
return user_home / ".cache" / "huggingface" / "hub"
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def resolve_hf_token(
|
|
139
|
+
*,
|
|
140
|
+
env: Mapping[str, str] | None = None,
|
|
141
|
+
home: Path | None = None,
|
|
142
|
+
) -> str | None:
|
|
143
|
+
"""Read HF token from HF_TOKEN env var or token file on disk."""
|
|
144
|
+
environ = _env_map(env)
|
|
145
|
+
user_home = _home_dir(home)
|
|
146
|
+
|
|
147
|
+
token = environ.get("HF_TOKEN", "").strip()
|
|
148
|
+
if token:
|
|
149
|
+
return token
|
|
150
|
+
|
|
151
|
+
candidates: list[Path] = []
|
|
152
|
+
hf_home = environ.get("HF_HOME", "").strip()
|
|
153
|
+
if hf_home:
|
|
154
|
+
candidates.append(Path(hf_home).expanduser() / "token")
|
|
155
|
+
candidates.append(user_home / ".cache" / "huggingface" / "token")
|
|
156
|
+
|
|
157
|
+
for candidate in candidates:
|
|
158
|
+
if candidate.is_file():
|
|
159
|
+
try:
|
|
160
|
+
content = candidate.read_text(encoding="utf-8").strip()
|
|
161
|
+
except OSError:
|
|
162
|
+
continue
|
|
163
|
+
if content:
|
|
164
|
+
return content
|
|
165
|
+
return None
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def default_skills_dir(
|
|
169
|
+
*,
|
|
170
|
+
sys_platform: str | None = None,
|
|
171
|
+
env: Mapping[str, str] | None = None,
|
|
172
|
+
home: Path | None = None,
|
|
173
|
+
) -> Path:
|
|
174
|
+
"""Resolve central skills store, preserving legacy ~/.config/llmctl/skills if present."""
|
|
175
|
+
user_home = _home_dir(home)
|
|
176
|
+
legacy = user_home / ".config" / "llmctl" / "skills"
|
|
177
|
+
if legacy.is_dir():
|
|
178
|
+
return legacy
|
|
179
|
+
return (
|
|
180
|
+
platform_config_dir("llmctl", sys_platform=sys_platform, env=env, home=user_home) / "skills"
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def normalize_api_root(raw_url: str) -> str:
|
|
185
|
+
"""Normalize an API URL (accepting full endpoint URLs like .../v1/chat/completions)."""
|
|
186
|
+
cleaned = raw_url.strip().rstrip("/")
|
|
187
|
+
if not cleaned:
|
|
188
|
+
return f"http://{DEFAULT_HOST}:{DEFAULT_PORT}"
|
|
189
|
+
if "://" not in cleaned:
|
|
190
|
+
cleaned = f"http://{cleaned}"
|
|
191
|
+
parsed = urlparse(cleaned)
|
|
192
|
+
path = parsed.path
|
|
193
|
+
if "/v1/" in path:
|
|
194
|
+
path = path.split("/v1/", 1)[0]
|
|
195
|
+
elif path.endswith("/v1"):
|
|
196
|
+
path = path[:-3]
|
|
197
|
+
elif path in {"/infill", "/health", "/models"}:
|
|
198
|
+
path = ""
|
|
199
|
+
path = path.rstrip("/")
|
|
200
|
+
return f"{parsed.scheme}://{parsed.netloc}{path}"
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def is_remote_api_url(api_root: str) -> bool:
|
|
204
|
+
"""Return True if *api_root* targets a non-loopback host."""
|
|
205
|
+
parsed = urlparse(api_root)
|
|
206
|
+
host = (parsed.hostname or "").lower()
|
|
207
|
+
if not host:
|
|
208
|
+
return False
|
|
209
|
+
return host not in LOOPBACK_HOSTS
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def find_llama_server(
|
|
213
|
+
configured: str = "",
|
|
214
|
+
*,
|
|
215
|
+
sys_platform: str | None = None,
|
|
216
|
+
env: Mapping[str, str] | None = None,
|
|
217
|
+
home: Path | None = None,
|
|
218
|
+
) -> Path | None:
|
|
219
|
+
"""Locate the llama-server executable across Linux, macOS, and Windows."""
|
|
220
|
+
plat = _platform(sys_platform)
|
|
221
|
+
environ = _env_map(env)
|
|
222
|
+
user_home = _home_dir(home)
|
|
223
|
+
|
|
224
|
+
explicit = configured.strip() or environ.get("LLMCTL_SERVER_BIN", "").strip()
|
|
225
|
+
if explicit:
|
|
226
|
+
explicit_path = Path(explicit).expanduser()
|
|
227
|
+
if explicit_path.is_file():
|
|
228
|
+
return explicit_path
|
|
229
|
+
found_explicit = shutil.which(explicit)
|
|
230
|
+
if found_explicit:
|
|
231
|
+
return Path(found_explicit)
|
|
232
|
+
|
|
233
|
+
exe_name = "llama-server.exe" if plat == "win32" else "llama-server"
|
|
234
|
+
in_path = shutil.which(exe_name) or shutil.which("llama-server")
|
|
235
|
+
if in_path:
|
|
236
|
+
return Path(in_path)
|
|
237
|
+
|
|
238
|
+
managed = (
|
|
239
|
+
platform_state_dir("llmctl", sys_platform=plat, env=environ, home=user_home)
|
|
240
|
+
/ "bin"
|
|
241
|
+
/ "llama.cpp"
|
|
242
|
+
/ "current"
|
|
243
|
+
/ exe_name
|
|
244
|
+
)
|
|
245
|
+
candidates = [
|
|
246
|
+
managed,
|
|
247
|
+
user_home / "llama.cpp" / "build" / "bin" / exe_name,
|
|
248
|
+
user_home / "llama.cpp" / "build" / "bin" / "Release" / exe_name,
|
|
249
|
+
user_home / ".local" / "bin" / exe_name,
|
|
250
|
+
]
|
|
251
|
+
if plat == "darwin":
|
|
252
|
+
candidates.extend(
|
|
253
|
+
[
|
|
254
|
+
Path("/opt/homebrew/bin/llama-server"),
|
|
255
|
+
Path("/usr/local/bin/llama-server"),
|
|
256
|
+
]
|
|
257
|
+
)
|
|
258
|
+
elif plat == "win32":
|
|
259
|
+
local = environ.get("LOCALAPPDATA", "").strip()
|
|
260
|
+
if local:
|
|
261
|
+
candidates.append(Path(local) / "llama.cpp" / exe_name)
|
|
262
|
+
else:
|
|
263
|
+
candidates.extend(
|
|
264
|
+
[
|
|
265
|
+
Path("/usr/local/bin/llama-server"),
|
|
266
|
+
Path("/usr/bin/llama-server"),
|
|
267
|
+
]
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
for candidate in candidates:
|
|
271
|
+
if candidate.is_file():
|
|
272
|
+
return candidate
|
|
273
|
+
return None
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
@dataclass
|
|
277
|
+
class AppConfig:
|
|
278
|
+
"""Resolved runtime configuration for llmctl."""
|
|
279
|
+
|
|
280
|
+
config_file: Path
|
|
281
|
+
models_ini: Path
|
|
282
|
+
hf_cache: Path
|
|
283
|
+
skills_dir: Path
|
|
284
|
+
state_dir: Path
|
|
285
|
+
log_dir: Path
|
|
286
|
+
host: str = DEFAULT_HOST
|
|
287
|
+
port: int = DEFAULT_PORT
|
|
288
|
+
models_max: int = DEFAULT_MODELS_MAX
|
|
289
|
+
extra_args: list[str] = field(default_factory=list)
|
|
290
|
+
backend: str = "auto"
|
|
291
|
+
api_root: str = f"http://{DEFAULT_HOST}:{DEFAULT_PORT}"
|
|
292
|
+
api_key: str | None = None
|
|
293
|
+
profile: str = ""
|
|
294
|
+
server_binary: Path | None = None
|
|
295
|
+
editor: str = ""
|
|
296
|
+
color: str = "auto"
|
|
297
|
+
hf_token: str | None = None
|
|
298
|
+
sys_platform: str = field(default_factory=lambda: sys.platform)
|
|
299
|
+
|
|
300
|
+
@property
|
|
301
|
+
def chat_completions_url(self) -> str:
|
|
302
|
+
return f"{self.api_root}/v1/chat/completions"
|
|
303
|
+
|
|
304
|
+
@property
|
|
305
|
+
def embeddings_url(self) -> str:
|
|
306
|
+
return f"{self.api_root}/v1/embeddings"
|
|
307
|
+
|
|
308
|
+
@property
|
|
309
|
+
def infill_url(self) -> str:
|
|
310
|
+
return f"{self.api_root}/infill"
|
|
311
|
+
|
|
312
|
+
@property
|
|
313
|
+
def models_url(self) -> str:
|
|
314
|
+
return f"{self.api_root}/v1/models"
|
|
315
|
+
|
|
316
|
+
@property
|
|
317
|
+
def router_models_url(self) -> str:
|
|
318
|
+
return f"{self.api_root}/models"
|
|
319
|
+
|
|
320
|
+
@property
|
|
321
|
+
def health_url(self) -> str:
|
|
322
|
+
return f"{self.api_root}/health"
|
|
323
|
+
|
|
324
|
+
@property
|
|
325
|
+
def is_remote(self) -> bool:
|
|
326
|
+
return self.backend == "remote" or is_remote_api_url(self.api_root)
|
|
327
|
+
|
|
328
|
+
def to_dict(self) -> dict[str, object]:
|
|
329
|
+
return {
|
|
330
|
+
"config_file": str(self.config_file),
|
|
331
|
+
"profile": self.profile or "default",
|
|
332
|
+
"models_ini": str(self.models_ini),
|
|
333
|
+
"hf_cache": str(self.hf_cache),
|
|
334
|
+
"skills_dir": str(self.skills_dir),
|
|
335
|
+
"state_dir": str(self.state_dir),
|
|
336
|
+
"log_dir": str(self.log_dir),
|
|
337
|
+
"host": self.host,
|
|
338
|
+
"port": self.port,
|
|
339
|
+
"models_max": self.models_max,
|
|
340
|
+
"extra_args": list(self.extra_args),
|
|
341
|
+
"backend": self.backend,
|
|
342
|
+
"api_root": self.api_root,
|
|
343
|
+
"has_api_key": bool(self.api_key),
|
|
344
|
+
"server_binary": str(self.server_binary) if self.server_binary else None,
|
|
345
|
+
"editor": self.editor,
|
|
346
|
+
"color": self.color,
|
|
347
|
+
"has_hf_token": bool(self.hf_token),
|
|
348
|
+
"is_remote": self.is_remote,
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
DEFAULT_CONFIG_TEMPLATE = """# llmctl configuration file
|
|
353
|
+
[server]
|
|
354
|
+
# Path to llama-server binary (empty = auto-detect in PATH / managed dir)
|
|
355
|
+
binary = ""
|
|
356
|
+
host = "127.0.0.1"
|
|
357
|
+
port = 8080
|
|
358
|
+
models_max = 1
|
|
359
|
+
extra_args = []
|
|
360
|
+
# Service backend: auto | systemd | launchd | process | remote
|
|
361
|
+
backend = "auto"
|
|
362
|
+
# Optional API URL override (e.g. "http://192.168.1.50:8080" for remote servers)
|
|
363
|
+
api_url = ""
|
|
364
|
+
# Optional bearer token if llama-server runs with --api-key
|
|
365
|
+
api_key = ""
|
|
366
|
+
|
|
367
|
+
[paths]
|
|
368
|
+
# Leave empty to use platform defaults
|
|
369
|
+
models_ini = ""
|
|
370
|
+
hf_cache = ""
|
|
371
|
+
skills_dir = ""
|
|
372
|
+
|
|
373
|
+
[ui]
|
|
374
|
+
# Preferred editor (empty = $VISUAL / $EDITOR / OS default)
|
|
375
|
+
editor = ""
|
|
376
|
+
# auto | always | never
|
|
377
|
+
color = "auto"
|
|
378
|
+
|
|
379
|
+
[profiles]
|
|
380
|
+
# Active profile name (empty = default [server] settings)
|
|
381
|
+
active = ""
|
|
382
|
+
"""
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def write_default_config(path: Path, *, overwrite: bool = False) -> Path:
|
|
386
|
+
"""Create a starter config.toml if it does not already exist."""
|
|
387
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
388
|
+
if overwrite or not path.exists():
|
|
389
|
+
path.write_text(DEFAULT_CONFIG_TEMPLATE, encoding="utf-8")
|
|
390
|
+
return path
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def _toml_value(val: Any) -> str:
|
|
394
|
+
if isinstance(val, bool):
|
|
395
|
+
return "true" if val else "false"
|
|
396
|
+
if isinstance(val, int):
|
|
397
|
+
return str(val)
|
|
398
|
+
if isinstance(val, list):
|
|
399
|
+
inner = ", ".join(_toml_value(v) for v in val)
|
|
400
|
+
return f"[{inner}]"
|
|
401
|
+
escaped = str(val).replace("\\", "\\\\").replace('"', '\\"')
|
|
402
|
+
return f'"{escaped}"'
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def _dump_toml(data: dict[str, Any]) -> str:
|
|
406
|
+
"""Minimal stdlib TOML serializer supporting flat tables and [profiles.<name>]."""
|
|
407
|
+
lines: list[str] = []
|
|
408
|
+
|
|
409
|
+
def emit_table(header: str, tbl: dict[str, Any]) -> None:
|
|
410
|
+
scalar_items = [(k, v) for k, v in tbl.items() if not isinstance(v, dict)]
|
|
411
|
+
sub_tables = [(k, v) for k, v in tbl.items() if isinstance(v, dict)]
|
|
412
|
+
if scalar_items or not sub_tables:
|
|
413
|
+
lines.append(f"[{header}]")
|
|
414
|
+
for key, val in scalar_items:
|
|
415
|
+
if val is not None:
|
|
416
|
+
lines.append(f"{key} = {_toml_value(val)}")
|
|
417
|
+
lines.append("")
|
|
418
|
+
for sub_key, sub_tbl in sub_tables:
|
|
419
|
+
emit_table(f"{header}.{sub_key}", sub_tbl)
|
|
420
|
+
|
|
421
|
+
for top_key, top_val in data.items():
|
|
422
|
+
if isinstance(top_val, dict):
|
|
423
|
+
emit_table(top_key, top_val)
|
|
424
|
+
elif top_val is not None:
|
|
425
|
+
lines.append(f"{top_key} = {_toml_value(top_val)}")
|
|
426
|
+
return "\n".join(lines).rstrip() + "\n"
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def _save_toml_file(path: Path, data: dict[str, Any]) -> None:
|
|
430
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
431
|
+
tmp_path = path.with_suffix(".toml.tmp")
|
|
432
|
+
tmp_path.write_text(_dump_toml(data), encoding="utf-8")
|
|
433
|
+
os.replace(tmp_path, path)
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def _load_toml_file(path: Path) -> dict[str, Any]:
|
|
437
|
+
if not path.is_file():
|
|
438
|
+
return {}
|
|
439
|
+
try:
|
|
440
|
+
with path.open("rb") as fh:
|
|
441
|
+
data = tomllib.load(fh)
|
|
442
|
+
return data if isinstance(data, dict) else {}
|
|
443
|
+
except (OSError, tomllib.TOMLDecodeError):
|
|
444
|
+
return {}
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def _toml_section(raw: dict[str, Any], key: str) -> dict[str, Any]:
|
|
448
|
+
val = raw.get(key)
|
|
449
|
+
return val if isinstance(val, dict) else {}
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def list_profiles(config_file: Path) -> tuple[str, dict[str, dict[str, Any]]]:
|
|
453
|
+
"""Return (active_profile_name, {profile_name: profile_settings})."""
|
|
454
|
+
raw = _load_toml_file(config_file)
|
|
455
|
+
profiles_sec = _toml_section(raw, "profiles")
|
|
456
|
+
active = str(profiles_sec.get("active") or "").strip()
|
|
457
|
+
profiles = {
|
|
458
|
+
k: dict(v) for k, v in profiles_sec.items() if k != "active" and isinstance(v, dict)
|
|
459
|
+
}
|
|
460
|
+
return active, profiles
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def save_profile(
|
|
464
|
+
config_file: Path,
|
|
465
|
+
name: str,
|
|
466
|
+
*,
|
|
467
|
+
api_url: str | None = None,
|
|
468
|
+
backend: str | None = None,
|
|
469
|
+
api_key: str | None = None,
|
|
470
|
+
host: str | None = None,
|
|
471
|
+
port: int | None = None,
|
|
472
|
+
models_ini: str | None = None,
|
|
473
|
+
activate: bool = False,
|
|
474
|
+
) -> dict[str, Any]:
|
|
475
|
+
"""Create or update a named profile in config.toml."""
|
|
476
|
+
clean = name.strip()
|
|
477
|
+
if not clean or clean in {"active", "default"} or any(c.isspace() or c in ".[]" for c in clean):
|
|
478
|
+
raise ValueError(f"Nombre de perfil inválido: {name!r}")
|
|
479
|
+
|
|
480
|
+
raw = _load_toml_file(config_file)
|
|
481
|
+
profiles_sec = dict(_toml_section(raw, "profiles"))
|
|
482
|
+
existing = profiles_sec.get(clean)
|
|
483
|
+
entry: dict[str, Any] = dict(existing) if isinstance(existing, dict) else {}
|
|
484
|
+
|
|
485
|
+
if api_url is not None:
|
|
486
|
+
entry["api_url"] = api_url.strip()
|
|
487
|
+
if backend is not None:
|
|
488
|
+
entry["backend"] = backend.strip().lower()
|
|
489
|
+
if api_key is not None:
|
|
490
|
+
entry["api_key"] = api_key.strip()
|
|
491
|
+
if host is not None:
|
|
492
|
+
entry["host"] = host.strip()
|
|
493
|
+
if port is not None:
|
|
494
|
+
entry["port"] = int(port)
|
|
495
|
+
if models_ini is not None:
|
|
496
|
+
entry["models_ini"] = models_ini.strip()
|
|
497
|
+
|
|
498
|
+
profiles_sec[clean] = entry
|
|
499
|
+
if activate:
|
|
500
|
+
profiles_sec["active"] = clean
|
|
501
|
+
raw["profiles"] = profiles_sec
|
|
502
|
+
_save_toml_file(config_file, raw)
|
|
503
|
+
return entry
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
def set_active_profile(config_file: Path, name: str) -> str:
|
|
507
|
+
"""Switch the active profile in config.toml ('default' or '' resets to default)."""
|
|
508
|
+
clean = name.strip()
|
|
509
|
+
raw = _load_toml_file(config_file)
|
|
510
|
+
profiles_sec = dict(_toml_section(raw, "profiles"))
|
|
511
|
+
if clean in {"", "default"}:
|
|
512
|
+
profiles_sec["active"] = ""
|
|
513
|
+
raw["profiles"] = profiles_sec
|
|
514
|
+
_save_toml_file(config_file, raw)
|
|
515
|
+
return "default"
|
|
516
|
+
|
|
517
|
+
if not isinstance(profiles_sec.get(clean), dict):
|
|
518
|
+
raise KeyError(f"El perfil '{clean}' no existe en {config_file}.")
|
|
519
|
+
profiles_sec["active"] = clean
|
|
520
|
+
raw["profiles"] = profiles_sec
|
|
521
|
+
_save_toml_file(config_file, raw)
|
|
522
|
+
return clean
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
def delete_profile(config_file: Path, name: str) -> bool:
|
|
526
|
+
"""Delete a named profile from config.toml."""
|
|
527
|
+
clean = name.strip()
|
|
528
|
+
raw = _load_toml_file(config_file)
|
|
529
|
+
profiles_sec = dict(_toml_section(raw, "profiles"))
|
|
530
|
+
if clean not in profiles_sec or not isinstance(profiles_sec.get(clean), dict):
|
|
531
|
+
return False
|
|
532
|
+
del profiles_sec[clean]
|
|
533
|
+
if profiles_sec.get("active") == clean:
|
|
534
|
+
profiles_sec["active"] = ""
|
|
535
|
+
raw["profiles"] = profiles_sec
|
|
536
|
+
_save_toml_file(config_file, raw)
|
|
537
|
+
return True
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def set_config_server_binary(config_file: Path, binary_path: Path) -> None:
|
|
541
|
+
"""Persist [server].binary in config.toml after installing llama-server."""
|
|
542
|
+
raw = _load_toml_file(config_file)
|
|
543
|
+
server_sec = dict(_toml_section(raw, "server"))
|
|
544
|
+
server_sec["binary"] = str(binary_path)
|
|
545
|
+
raw["server"] = server_sec
|
|
546
|
+
_save_toml_file(config_file, raw)
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
def load_config(
|
|
550
|
+
*,
|
|
551
|
+
config_path: str | Path | None = None,
|
|
552
|
+
ini_override: str | Path | None = None,
|
|
553
|
+
api_url_override: str | None = None,
|
|
554
|
+
api_key_override: str | None = None,
|
|
555
|
+
backend_override: str | None = None,
|
|
556
|
+
profile_override: str | None = None,
|
|
557
|
+
no_color: bool = False,
|
|
558
|
+
sys_platform: str | None = None,
|
|
559
|
+
env: Mapping[str, str] | None = None,
|
|
560
|
+
home: Path | None = None,
|
|
561
|
+
) -> AppConfig:
|
|
562
|
+
"""Load merged configuration: CLI > env > active profile > config.toml > OS defaults."""
|
|
563
|
+
plat = _platform(sys_platform)
|
|
564
|
+
environ = _env_map(env)
|
|
565
|
+
user_home = _home_dir(home)
|
|
566
|
+
|
|
567
|
+
cfg_env = environ.get("LLMCTL_CONFIG", "").strip()
|
|
568
|
+
if config_path is not None:
|
|
569
|
+
cfg_file = Path(config_path).expanduser()
|
|
570
|
+
elif cfg_env:
|
|
571
|
+
cfg_file = Path(cfg_env).expanduser()
|
|
572
|
+
else:
|
|
573
|
+
cfg_file = (
|
|
574
|
+
platform_config_dir("llmctl", sys_platform=plat, env=environ, home=user_home)
|
|
575
|
+
/ "config.toml"
|
|
576
|
+
)
|
|
577
|
+
|
|
578
|
+
raw = _load_toml_file(cfg_file)
|
|
579
|
+
server_sec = _toml_section(raw, "server")
|
|
580
|
+
paths_sec = _toml_section(raw, "paths")
|
|
581
|
+
ui_sec = _toml_section(raw, "ui")
|
|
582
|
+
profiles_sec = _toml_section(raw, "profiles")
|
|
583
|
+
|
|
584
|
+
active_profile = str(
|
|
585
|
+
profile_override
|
|
586
|
+
if profile_override is not None
|
|
587
|
+
else (environ.get("LLMCTL_PROFILE") or profiles_sec.get("active") or "")
|
|
588
|
+
).strip()
|
|
589
|
+
if active_profile == "default":
|
|
590
|
+
active_profile = ""
|
|
591
|
+
profile_sec = _toml_section(profiles_sec, active_profile) if active_profile else {}
|
|
592
|
+
|
|
593
|
+
host = str(
|
|
594
|
+
environ.get("LLMCTL_HOST")
|
|
595
|
+
or profile_sec.get("host")
|
|
596
|
+
or server_sec.get("host")
|
|
597
|
+
or DEFAULT_HOST
|
|
598
|
+
).strip()
|
|
599
|
+
|
|
600
|
+
port_raw = (
|
|
601
|
+
environ.get("LLMCTL_PORT")
|
|
602
|
+
or profile_sec.get("port")
|
|
603
|
+
or server_sec.get("port")
|
|
604
|
+
or DEFAULT_PORT
|
|
605
|
+
)
|
|
606
|
+
try:
|
|
607
|
+
port = int(port_raw)
|
|
608
|
+
except (TypeError, ValueError):
|
|
609
|
+
port = DEFAULT_PORT
|
|
610
|
+
|
|
611
|
+
models_max_raw = (
|
|
612
|
+
environ.get("LLMCTL_MODELS_MAX")
|
|
613
|
+
or profile_sec.get("models_max")
|
|
614
|
+
or server_sec.get("models_max")
|
|
615
|
+
or DEFAULT_MODELS_MAX
|
|
616
|
+
)
|
|
617
|
+
try:
|
|
618
|
+
models_max = max(1, int(models_max_raw))
|
|
619
|
+
except (TypeError, ValueError):
|
|
620
|
+
models_max = DEFAULT_MODELS_MAX
|
|
621
|
+
|
|
622
|
+
raw_extra = profile_sec.get("extra_args") or server_sec.get("extra_args", [])
|
|
623
|
+
extra_args = [str(item) for item in raw_extra] if isinstance(raw_extra, list) else []
|
|
624
|
+
|
|
625
|
+
backend = (
|
|
626
|
+
str(
|
|
627
|
+
backend_override
|
|
628
|
+
or environ.get("LLMCTL_BACKEND")
|
|
629
|
+
or profile_sec.get("backend")
|
|
630
|
+
or server_sec.get("backend")
|
|
631
|
+
or "auto"
|
|
632
|
+
)
|
|
633
|
+
.strip()
|
|
634
|
+
.lower()
|
|
635
|
+
)
|
|
636
|
+
|
|
637
|
+
raw_api_url = (
|
|
638
|
+
api_url_override
|
|
639
|
+
or environ.get("LLMCTL_API_URL")
|
|
640
|
+
or environ.get("LLM_API_URL")
|
|
641
|
+
or str(profile_sec.get("api_url") or "")
|
|
642
|
+
or str(server_sec.get("api_url") or "")
|
|
643
|
+
).strip()
|
|
644
|
+
api_root = (
|
|
645
|
+
normalize_api_root(raw_api_url)
|
|
646
|
+
if raw_api_url
|
|
647
|
+
else normalize_api_root(f"http://{host}:{port}")
|
|
648
|
+
)
|
|
649
|
+
|
|
650
|
+
raw_api_key = (
|
|
651
|
+
api_key_override
|
|
652
|
+
or environ.get("LLMCTL_API_KEY")
|
|
653
|
+
or str(profile_sec.get("api_key") or "")
|
|
654
|
+
or str(server_sec.get("api_key") or "")
|
|
655
|
+
).strip()
|
|
656
|
+
api_key = raw_api_key or None
|
|
657
|
+
|
|
658
|
+
if ini_override is not None:
|
|
659
|
+
models_ini = Path(ini_override).expanduser()
|
|
660
|
+
else:
|
|
661
|
+
ini_env = (environ.get("LLMCTL_INI_PATH") or environ.get("LLM_INI_PATH") or "").strip()
|
|
662
|
+
ini_cfg = str(profile_sec.get("models_ini") or paths_sec.get("models_ini") or "").strip()
|
|
663
|
+
if ini_env:
|
|
664
|
+
models_ini = Path(ini_env).expanduser()
|
|
665
|
+
elif ini_cfg:
|
|
666
|
+
models_ini = Path(ini_cfg).expanduser()
|
|
667
|
+
else:
|
|
668
|
+
models_ini = default_models_ini(sys_platform=plat, env=environ, home=user_home)
|
|
669
|
+
|
|
670
|
+
hf_cache_cfg = str(paths_sec.get("hf_cache") or "").strip()
|
|
671
|
+
if environ.get("HF_HUB_CACHE") or environ.get("HF_HOME"):
|
|
672
|
+
hf_cache = default_hf_cache(env=environ, home=user_home)
|
|
673
|
+
elif hf_cache_cfg:
|
|
674
|
+
hf_cache = Path(hf_cache_cfg).expanduser()
|
|
675
|
+
else:
|
|
676
|
+
hf_cache = default_hf_cache(env=environ, home=user_home)
|
|
677
|
+
|
|
678
|
+
skills_cfg = str(paths_sec.get("skills_dir") or "").strip()
|
|
679
|
+
skills_env = environ.get("LLMCTL_SKILLS_DIR", "").strip()
|
|
680
|
+
if skills_env:
|
|
681
|
+
skills_dir = Path(skills_env).expanduser()
|
|
682
|
+
elif skills_cfg:
|
|
683
|
+
skills_dir = Path(skills_cfg).expanduser()
|
|
684
|
+
else:
|
|
685
|
+
skills_dir = default_skills_dir(sys_platform=plat, env=environ, home=user_home)
|
|
686
|
+
|
|
687
|
+
state_dir = platform_state_dir("llmctl", sys_platform=plat, env=environ, home=user_home)
|
|
688
|
+
log_dir = platform_log_dir("llmctl", sys_platform=plat, env=environ, home=user_home)
|
|
689
|
+
|
|
690
|
+
configured_bin = str(profile_sec.get("binary") or server_sec.get("binary") or "").strip()
|
|
691
|
+
server_binary = find_llama_server(
|
|
692
|
+
configured_bin, sys_platform=plat, env=environ, home=user_home
|
|
693
|
+
)
|
|
694
|
+
|
|
695
|
+
editor = str(ui_sec.get("editor") or "").strip()
|
|
696
|
+
color_setting = "never" if no_color else str(ui_sec.get("color") or "auto").strip().lower()
|
|
697
|
+
|
|
698
|
+
return AppConfig(
|
|
699
|
+
config_file=cfg_file,
|
|
700
|
+
models_ini=models_ini,
|
|
701
|
+
hf_cache=hf_cache,
|
|
702
|
+
skills_dir=skills_dir,
|
|
703
|
+
state_dir=state_dir,
|
|
704
|
+
log_dir=log_dir,
|
|
705
|
+
host=host,
|
|
706
|
+
port=port,
|
|
707
|
+
models_max=models_max,
|
|
708
|
+
extra_args=extra_args,
|
|
709
|
+
backend=backend,
|
|
710
|
+
api_root=api_root,
|
|
711
|
+
api_key=api_key,
|
|
712
|
+
profile=active_profile,
|
|
713
|
+
server_binary=server_binary,
|
|
714
|
+
editor=editor,
|
|
715
|
+
color=color_setting,
|
|
716
|
+
hf_token=resolve_hf_token(env=environ, home=user_home),
|
|
717
|
+
sys_platform=plat,
|
|
718
|
+
)
|