ollama2cpp 0.1.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.
ollama2cpp/commands.py ADDED
@@ -0,0 +1,648 @@
1
+ """The inspection and maintenance commands: list, info, status, stop, doctor, update and config.
2
+
3
+ No CLI parsing lives here (see ``__main__``): every ``run_*`` function prints through ``ui`` and returns the process
4
+ exit code; user-facing failures are :class:`~ollama2cpp.workflow.WorkflowError` (shown as one error line by the CLI).
5
+ The optimizer command lives in :mod:`ollama2cpp.optimize_cmd`.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+ import json
12
+ import logging
13
+ import shutil
14
+ import sys
15
+ import tempfile
16
+ from collections.abc import Callable, Sequence
17
+ from pathlib import Path
18
+ from typing import Any, Literal
19
+
20
+ import typer
21
+
22
+ from ollama2cpp import config, constants, gguf, hardware, llamacpp, ollama, proc, selector, server, ui, workflow
23
+ from ollama2cpp.config import Config, Profile
24
+ from ollama2cpp.constants import DEFAULT_CTX
25
+ from ollama2cpp.hardware import Device
26
+ from ollama2cpp.ollama import OllamaModel
27
+ from ollama2cpp.selector import Candidate
28
+ from ollama2cpp.workflow import WorkflowError
29
+
30
+ __all__ = [
31
+ "SETTABLE_KEYS",
32
+ "describe_profile",
33
+ "find_server",
34
+ "load_config",
35
+ "models_root",
36
+ "pick_device",
37
+ "profiles_for",
38
+ "run_config",
39
+ "run_doctor",
40
+ "run_info",
41
+ "run_list",
42
+ "run_status",
43
+ "run_stop",
44
+ "run_update",
45
+ "server_endpoint",
46
+ ]
47
+
48
+ logger = logging.getLogger(__name__)
49
+
50
+ _GIB = 1024**3
51
+ LOW_FREE_FRACTION = 0.5 # free VRAM below this share of the total means another process is holding it
52
+ UPDATE_TAIL_LINES = 12
53
+ SETTABLE_KEYS = ("host", "port", "device", "ollama_path", "default_model", "llama_server")
54
+ _OLLAMA_MEDIA = "application/vnd.ollama.image."
55
+ _UNSET_WORDS = frozenset({"", "none"})
56
+ _MAX_PORT = 65535
57
+ _UP_TO_DATE_MARKERS = ("no available upgrade", "no newer package")
58
+ _NO_CHAT_HINT = "No chat model is installed; pull one first, e.g. `ollama pull llama3.2`."
59
+
60
+ ConfigState = Literal["ok", "missing", "corrupt"]
61
+
62
+
63
+ # --- shared helpers ------------------------------------------------------------------------------------------------
64
+
65
+
66
+ def load_config(*, assume_yes: bool = False) -> Config:
67
+ """Load the saved configuration, running the first-run setup when there is none.
68
+
69
+ Args:
70
+ assume_yes: Answer yes to the first-run installation question.
71
+
72
+ Only the commands that need a working setup (``optimize``) use this; the inspection commands use
73
+ :func:`peek_config` so they never install anything or write a configuration.
74
+
75
+ Returns:
76
+ Config: The saved configuration (never an unsaved per-run copy).
77
+ """
78
+ cfg = workflow.load_saved_config()
79
+ return cfg if cfg is not None else workflow.ensure_config(workflow.ServeOptions(assume_yes=assume_yes))
80
+
81
+
82
+ def peek_config() -> tuple[Config | None, ConfigState]:
83
+ """Read the saved configuration without side effects (no first run, no ``.bak`` rename of a corrupt file).
84
+
85
+ Returns:
86
+ tuple[Config | None, ConfigState]: The configuration and ``"ok"``, or ``None`` with ``"missing"`` (no file)
87
+ or ``"corrupt"`` (unreadable or invalid).
88
+ """
89
+ path = config.config_file()
90
+ if not path.is_file():
91
+ return None, "missing"
92
+ with tempfile.TemporaryDirectory(prefix="o2c-peek-") as tmp:
93
+ try:
94
+ shutil.copyfile(path, Path(tmp) / constants.CONFIG_FILENAME)
95
+ except OSError:
96
+ return None, "corrupt"
97
+ try:
98
+ cfg = config.load(Path(tmp))
99
+ except OSError:
100
+ return None, "corrupt"
101
+ return (cfg, "ok") if cfg is not None else (None, "corrupt")
102
+
103
+
104
+ def models_root(cfg: Config | None) -> Path:
105
+ """Return the Ollama models directory: the configured one while it holds ``manifests/``, else discovery.
106
+
107
+ Args:
108
+ cfg: The configuration, or None.
109
+
110
+ Returns:
111
+ Path: The models directory.
112
+
113
+ Raises:
114
+ WorkflowError: When no Ollama models directory can be found.
115
+ """
116
+ if cfg is not None and cfg.ollama_path and (Path(cfg.ollama_path) / "manifests").is_dir():
117
+ return Path(cfg.ollama_path)
118
+ found = ollama.find_ollama_path()
119
+ if found is None:
120
+ raise WorkflowError(
121
+ "Could not find the Ollama models directory. Set OLLAMA_MODELS or run "
122
+ "`ollama2cpp config --set ollama_path=<folder with manifests and blobs>`."
123
+ )
124
+ return found
125
+
126
+
127
+ def server_endpoint(cfg: Config | None) -> tuple[str, int]:
128
+ """Return the ``(host, port)`` to probe for our own server: the one in its pid record, else the configured one.
129
+
130
+ A server started with ``serve --port 9000`` listens there whatever the configuration says.
131
+
132
+ Args:
133
+ cfg: The configuration, or None.
134
+
135
+ Returns:
136
+ tuple[str, int]: Address and port.
137
+ """
138
+ record = server.read_record(constants.home())
139
+ if record is not None:
140
+ return record.host, record.port
141
+ return (cfg.host, cfg.port) if cfg else (constants.DEFAULT_HOST, constants.DEFAULT_PORT)
142
+
143
+
144
+ def find_server(cfg: Config | None) -> Path | None:
145
+ """Locate ``llama-server`` (configured path first)."""
146
+ return llamacpp.find_binary("llama-server", cfg.llama_server if cfg else None)
147
+
148
+
149
+ def pick_device(cfg: Config | None, binary: Path | None) -> Device | None:
150
+ """Detect the GPUs and choose the one to run on (None for CPU-only)."""
151
+ return hardware.best_device(hardware.detect_devices(binary), cfg.device if cfg else None)
152
+
153
+
154
+ def profiles_for(cfg: Config, digest: str | None) -> list[tuple[str, Profile]]:
155
+ """Return every saved profile of the model with blob ``digest`` as ``(requested ctx, profile)``, by ctx."""
156
+ if digest is None:
157
+ return []
158
+ prefix = f"{digest}:"
159
+ found = [(key.removeprefix(prefix), p) for key, p in cfg.profiles.items() if key.startswith(prefix)]
160
+ return sorted(found, key=lambda item: (len(item[0]), item[0]))
161
+
162
+
163
+ def describe_profile(profile: Profile) -> str:
164
+ """Summarise a profile in one line."""
165
+ if profile.measured and profile.tg_tps is not None:
166
+ speed = f"tg {profile.tg_tps:.1f} t/s" + (f", pp {profile.pp_tps:.1f} t/s" if profile.pp_tps else "")
167
+ return f"ctx {profile.ctx}, {speed} (measured)"
168
+ return f"ctx {profile.ctx}, heuristic settings (unmeasured)"
169
+
170
+
171
+ def _layer_size(size: int) -> str:
172
+ for unit, label in ((_GIB, "GiB"), (1024**2, "MiB"), (1024, "KiB")):
173
+ if size >= unit:
174
+ return f"{size / unit:.1f} {label}"
175
+ return f"{size} B"
176
+
177
+
178
+ def _gib(size: int) -> str:
179
+ return f"{size / _GIB:.2f} GiB" if size else "-"
180
+
181
+
182
+ def _free_text(device: Device) -> str:
183
+ free = f"{device.free_mib}" if device.free_mib else "?"
184
+ return f"{device.name}: {free} MiB free of {device.total_mib} MiB"
185
+
186
+
187
+ def _is_low(device: Device) -> bool:
188
+ return 0 < device.free_mib < device.total_mib * LOW_FREE_FRACTION
189
+
190
+
191
+ def _low_vram_warning() -> str:
192
+ return "something else is holding VRAM (e.g. Ollama) - `optimize` may refuse; see --unload-ollama"
193
+
194
+
195
+ def _interactive() -> bool:
196
+ return sys.stdin.isatty()
197
+
198
+
199
+ # --- list ----------------------------------------------------------------------------------------------------------
200
+
201
+
202
+ def _optimized(cfg: Config, model: OllamaModel) -> str:
203
+ found = [p for _, p in profiles_for(cfg, model.digest)]
204
+ if not found:
205
+ return "no"
206
+ return "yes" if any(p.measured for p in found) else "seed"
207
+
208
+
209
+ def _list_row(cand: Candidate, cfg: Config, device: Device | None) -> dict[str, Any]:
210
+ """Build the JSON-friendly record of one model (``None`` marks a field that does not apply)."""
211
+ info, chat = cand.gguf, cand.kind == "chat"
212
+ return {
213
+ "name": cand.model.name,
214
+ "size_gib": round(cand.model.size / _GIB, 2),
215
+ "quant": gguf.file_type_name(info.file_type) if info else None,
216
+ "arch": info.architecture if info else None,
217
+ "ctx": info.context_length if info else None,
218
+ "kind": cand.kind,
219
+ "need_mib": cand.need_mib if info else None,
220
+ "fits_vram": cand.need_mib <= device.total_mib if chat and device else None,
221
+ "optimized": _optimized(cfg, cand.model) if chat else None,
222
+ "reason": cand.reason,
223
+ }
224
+
225
+
226
+ def _table_cells(row: dict[str, Any]) -> list[str]:
227
+ chat = row["kind"] == "chat"
228
+ fits = "?" if chat and row["fits_vram"] is None else {True: "yes", False: "no"}.get(row["fits_vram"], "-")
229
+ shown = {k: "-" if row[k] is None else str(row[k]) for k in ("quant", "arch", "ctx")}
230
+ return [
231
+ row["name"],
232
+ f"{row['size_gib']:.1f}" if row["size_gib"] else "-",
233
+ shown["quant"],
234
+ shown["arch"],
235
+ shown["ctx"],
236
+ row["kind"],
237
+ fits,
238
+ row["optimized"] or "-",
239
+ row["reason"],
240
+ ]
241
+
242
+
243
+ def run_list(*, as_json: bool = False) -> int:
244
+ """List the installed Ollama models with their classification (never aborts on one bad model).
245
+
246
+ Args:
247
+ as_json: Print a JSON array instead of a table.
248
+
249
+ Returns:
250
+ int: The exit code.
251
+ """
252
+ with ui.use_stderr() if as_json else contextlib.nullcontext(): # stdout carries only the JSON
253
+ saved, _ = peek_config() # never a first run: no installation and no writes
254
+ cfg = saved or Config()
255
+ root = models_root(saved)
256
+ device = pick_device(saved, find_server(saved)) # without llama-server the fit shows "?"
257
+ rows = [_list_row(c, cfg, device) for c in selector.classify_all(ollama.list_models(root), DEFAULT_CTX)]
258
+ hint = None if any(r["kind"] == "chat" for r in rows) else _NO_CHAT_HINT
259
+ if as_json and hint:
260
+ ui.show_notice("info", hint)
261
+ if as_json:
262
+ typer.echo(json.dumps(rows, indent=2))
263
+ return 0
264
+ if not rows:
265
+ ui.show_notice("warn", f"No Ollama models found in {root}. {hint}")
266
+ return 0
267
+ columns = ["Name", "Size GiB", "Quant", "Arch", "Ctx", "Kind", "Fits VRAM", "Optimized", "Note"]
268
+ ui.show_table(f"Ollama models in {root}", columns, [_table_cells(r) for r in rows])
269
+ if hint:
270
+ ui.show_notice("info", hint)
271
+ return 0
272
+
273
+
274
+ # --- info ----------------------------------------------------------------------------------------------------------
275
+
276
+
277
+ def _vram_lines(cand: Candidate, profiles: Sequence[tuple[str, Profile]], device: Device | None) -> list[str]:
278
+ """Describe the memory need at the default context and at each saved profile context."""
279
+ if cand.gguf is None:
280
+ return []
281
+ ctxs = [DEFAULT_CTX, *sorted({p.ctx for _, p in profiles} - {DEFAULT_CTX})]
282
+ lines = []
283
+ for ctx in ctxs:
284
+ need = selector.estimate_need_mib(cand.model, cand.gguf, ctx)
285
+ verdict = ""
286
+ if device is not None:
287
+ verdict = f" ({'fits' if need <= device.total_mib else 'does not fit'} {device.total_mib} MiB of VRAM)"
288
+ lines.append(f"VRAM at ctx {ctx}: about {need} MiB{verdict}")
289
+ return lines
290
+
291
+
292
+ def _info_lines(cand: Candidate, device: Device | None, profiles: Sequence[tuple[str, Profile]]) -> list[str]:
293
+ model, info = cand.model, cand.gguf
294
+ lines = [
295
+ f"Model : {model.name}",
296
+ f"Manifest : {model.manifest_path}",
297
+ f"Size : {_gib(model.size)}",
298
+ ]
299
+ if info is None:
300
+ lines.append(f"GGUF : unreadable ({cand.reason})")
301
+ else:
302
+ lines += [
303
+ f"Kind : {cand.kind}" + (f" ({cand.reason})" if cand.reason else ""),
304
+ f"Architecture : {info.architecture}",
305
+ f"Layers : {info.block_count}",
306
+ f"Heads : {info.head_count} (KV heads {info.head_count_kv})",
307
+ f"Trained ctx : {info.context_length}",
308
+ f"File type : {gguf.file_type_name(info.file_type)}",
309
+ ]
310
+ lines += _vram_lines(cand, profiles, device)
311
+ if not profiles:
312
+ lines.append("Profiles : none saved (run `ollama2cpp optimize`)")
313
+ for requested, profile in profiles:
314
+ lines.append(f"Profile @ {requested}: {describe_profile(profile)}")
315
+ lines.append(f" args: {' '.join(profile.args)}")
316
+ return lines
317
+
318
+
319
+ def run_info(name: str) -> int:
320
+ """Show the GGUF details, layers, memory need and saved profiles of one model.
321
+
322
+ Args:
323
+ name: The model name as typed.
324
+
325
+ Returns:
326
+ int: The exit code.
327
+ """
328
+ saved, _ = peek_config() # never a first run: no installation and no writes
329
+ root = models_root(saved)
330
+ model = ollama.resolve_model(root, name)
331
+ cand = selector.classify(model, DEFAULT_CTX)
332
+ device = pick_device(saved, find_server(saved))
333
+ ui.panel(model.name, "\n".join(_info_lines(cand, device, profiles_for(saved or Config(), model.digest))))
334
+ blobs = root / "blobs"
335
+ layers = [
336
+ [
337
+ layer.media_type.removeprefix(_OLLAMA_MEDIA),
338
+ _layer_size(layer.size),
339
+ layer.digest[:19],
340
+ "yes" if (blobs / layer.digest.replace(":", "-")).is_file() else "MISSING",
341
+ ]
342
+ for layer in model.layers
343
+ ]
344
+ ui.show_table("Layers", ["Type", "Size", "Digest", "On disk"], layers)
345
+ return 0
346
+
347
+
348
+ # --- status --------------------------------------------------------------------------------------------------------
349
+
350
+
351
+ def _server_line(host: str, port: int) -> str:
352
+ state, alias = server.describe_running(host, port, constants.home())
353
+ if state == "none":
354
+ return f"not running ({host}:{port})"
355
+ if state == "foreign":
356
+ return f"port {port} on {host} is held by another process (not ollama2cpp){f': {alias}' if alias else ''}"
357
+ ready = "ready" if server.is_ready(host, port) else "still loading"
358
+ return f"running (ours): {alias or 'unknown model'} at http://{host}:{port} ({ready})"
359
+
360
+
361
+ def _config_line(state: ConfigState) -> str:
362
+ detail = {"ok": "ok", "missing": "not found - run `ollama2cpp serve` to set up", "corrupt": "unreadable or invalid"}
363
+ return f"{config.config_file()} ({detail[state]})"
364
+
365
+
366
+ def _default_profile_line(cfg: Config) -> str:
367
+ if not cfg.default_model:
368
+ return "no default model saved"
369
+ try:
370
+ model = ollama.resolve_model(models_root(cfg), cfg.default_model)
371
+ except (WorkflowError, ollama.ModelNotFoundError):
372
+ return f"{cfg.default_model} (not installed)"
373
+ profiles = profiles_for(cfg, model.digest)
374
+ summary = "; ".join(f"@{req}: {describe_profile(p)}" for req, p in profiles) or "no profile saved"
375
+ return f"{model.name} - {summary}"
376
+
377
+
378
+ def run_status() -> int:
379
+ """Show the server state, configuration, GPU memory and the default model's saved profile (needs no config).
380
+
381
+ Returns:
382
+ int: The exit code.
383
+ """
384
+ cfg, state = peek_config()
385
+ host, port = server_endpoint(cfg)
386
+ devices = hardware.detect_devices(find_server(cfg))
387
+ lines = [f"Server : {_server_line(host, port)}", f"Config : {_config_line(state)}"]
388
+ lines += [f"GPU : {_free_text(d)}" for d in devices] or ["GPU : none detected (CPU only)"]
389
+ if cfg is not None:
390
+ lines.append(f"Default model: {_default_profile_line(cfg)}")
391
+ ui.panel("ollama2cpp status", "\n".join(lines))
392
+ if any(_is_low(d) for d in devices):
393
+ ui.show_notice("warn", f"Less than half of the VRAM is free: {_low_vram_warning()}.")
394
+ return 0
395
+
396
+
397
+ # --- stop ----------------------------------------------------------------------------------------------------------
398
+
399
+
400
+ def run_stop() -> int:
401
+ """Stop the server started by ollama2cpp; a foreign process on the port is never touched.
402
+
403
+ Returns:
404
+ int: The exit code (0 also when there was nothing to stop).
405
+ """
406
+ if server.stop(constants.home()):
407
+ ui.show_notice("ok", "Stopped the ollama2cpp server.")
408
+ return 0
409
+ cfg, _ = peek_config()
410
+ host = cfg.host if cfg else constants.DEFAULT_HOST
411
+ port = cfg.port if cfg else constants.DEFAULT_PORT
412
+ if server.describe_running(host, port, constants.home())[0] == "foreign":
413
+ ui.show_notice(
414
+ "warn", f"Port {port} on {host} is held by a process ollama2cpp did not start; it was left alone."
415
+ )
416
+ else:
417
+ ui.show_notice("info", "No ollama2cpp server is running.")
418
+ return 0
419
+
420
+
421
+ # --- doctor --------------------------------------------------------------------------------------------------------
422
+
423
+ Check = tuple[Literal["ok", "warn", "fail"], str, str] # level, detail, fix hint
424
+
425
+
426
+ def _check_server(cfg: Config | None) -> Check:
427
+ binary = find_server(cfg)
428
+ if binary is None:
429
+ hint = "run `ollama2cpp serve` (installs llama.cpp) or `winget install --id ggml.llamacpp -e`"
430
+ return "fail", "llama-server was not found", hint
431
+ backends = sorted({d.id.rstrip("0123456789") for d in hardware.detect_devices(binary)})
432
+ return "ok", f"{binary} ({llamacpp.version(binary)}, backend: {', '.join(backends) or 'CPU'})", ""
433
+
434
+
435
+ def _check_bench(cfg: Config | None) -> Check:
436
+ binary = llamacpp.find_binary("llama-bench", cfg.llama_bench if cfg else None)
437
+ if binary is None:
438
+ return "warn", "llama-bench was not found (only `optimize --quick` works)", "run `ollama2cpp update`"
439
+ return "ok", str(binary), ""
440
+
441
+
442
+ def _check_ollama(cfg: Config | None) -> Check:
443
+ try:
444
+ root = models_root(cfg)
445
+ except WorkflowError:
446
+ hint = "set OLLAMA_MODELS or `ollama2cpp config --set ollama_path=...`"
447
+ return "fail", "Ollama models directory not found", hint
448
+ count = len(ollama.list_models(root))
449
+ if count == 0:
450
+ return "warn", f"{root} (no models)", "pull one, e.g. `ollama pull llama3.2`"
451
+ return "ok", f"{root} ({count} models)", ""
452
+
453
+
454
+ def _check_gpu(cfg: Config | None) -> Check:
455
+ devices = hardware.detect_devices(find_server(cfg))
456
+ if not devices:
457
+ hint = "install GPU drivers or a CUDA/Vulkan llama.cpp build"
458
+ return "warn", "no GPU detected - inference runs on the CPU", hint
459
+ return "ok", "; ".join(f"{d.name} ({d.total_mib} MiB)" for d in devices), ""
460
+
461
+
462
+ def _check_vram(cfg: Config | None) -> Check:
463
+ devices = hardware.detect_devices(find_server(cfg))
464
+ if not devices:
465
+ return "ok", "no GPU, nothing to check", ""
466
+ low = [d for d in devices if _is_low(d)]
467
+ if low:
468
+ return "warn", "; ".join(_free_text(d) for d in low), "close other GPU users or use `optimize --unload-ollama`"
469
+ return "ok", "; ".join(_free_text(d) for d in devices), ""
470
+
471
+
472
+ def _check_config(state: ConfigState) -> Check:
473
+ if state == "corrupt":
474
+ hint = "`ollama2cpp config --reset` or re-run `serve`"
475
+ return "warn", f"{config.config_file()} is unreadable or invalid", hint
476
+ if state == "missing":
477
+ return "warn", "not configured yet", "run `ollama2cpp serve` to set up"
478
+ return "ok", str(config.config_file()), ""
479
+
480
+
481
+ def _safely(name: str, check: Callable[[], Check]) -> tuple[str, Check]:
482
+ """Run one check; a crash becomes a ``fail`` row instead of aborting the doctor."""
483
+ try:
484
+ return name, check()
485
+ except Exception as exc:
486
+ logger.debug("Doctor check %s crashed", name, exc_info=True)
487
+ return name, ("fail", f"the check crashed: {exc}", "re-run with --verbose and report it")
488
+
489
+
490
+ def run_doctor() -> int:
491
+ """Run the health checks (needs no config, never raises) and print them with fix hints.
492
+
493
+ Returns:
494
+ int: 1 when any check failed, else 0.
495
+ """
496
+ cfg, state = peek_config()
497
+ checks: list[tuple[str, Callable[[], Check]]] = [
498
+ ("llama-server", lambda: _check_server(cfg)),
499
+ ("llama-bench", lambda: _check_bench(cfg)),
500
+ ("Ollama models", lambda: _check_ollama(cfg)),
501
+ ("GPU", lambda: _check_gpu(cfg)),
502
+ ("Free VRAM", lambda: _check_vram(cfg)),
503
+ ("Config", lambda: _check_config(state)),
504
+ ]
505
+ results = [_safely(name, check) for name, check in checks]
506
+ ui.show_table(
507
+ "ollama2cpp doctor",
508
+ ["Check", "Status", "Detail", "Fix"],
509
+ [[name, ui.status_text(level), detail, fix] for name, (level, detail, fix) in results],
510
+ )
511
+ return 1 if any(level == "fail" for _, (level, _, _) in results) else 0
512
+
513
+
514
+ # --- update --------------------------------------------------------------------------------------------------------
515
+
516
+
517
+ def _tail(text: str, count: int = UPDATE_TAIL_LINES) -> str:
518
+ return "\n".join([line for line in text.splitlines() if line.strip()][-count:])
519
+
520
+
521
+ def _refresh_paths() -> str:
522
+ """Record the (possibly relocated) binaries in the saved configuration; return the new ``llama-server`` version."""
523
+ saved = workflow.load_saved_config()
524
+ binary = llamacpp.find_binary("llama-server", saved.llama_server if saved else None)
525
+ if binary is None:
526
+ return "unknown"
527
+ if saved is not None:
528
+ bench = llamacpp.find_binary("llama-bench", saved.llama_bench)
529
+ found = (str(binary), str(bench) if bench else saved.llama_bench)
530
+ if found != (saved.llama_server, saved.llama_bench):
531
+ saved.llama_server, saved.llama_bench = found
532
+ config.save(saved)
533
+ return llamacpp.version(binary)
534
+
535
+
536
+ def run_update() -> int:
537
+ """Upgrade llama.cpp with winget and show the new version.
538
+
539
+ Returns:
540
+ int: The exit code.
541
+
542
+ Raises:
543
+ WorkflowError: When winget is missing or the upgrade failed.
544
+ """
545
+ ui.show_notice("info", "Upgrading llama.cpp with winget.")
546
+ result = llamacpp.update()
547
+ output = f"{result.stdout}\n{result.stderr}"
548
+ tail = _tail(output)
549
+ if tail:
550
+ ui.console.print(tail, markup=False, highlight=False)
551
+ if result.returncode == proc.RC_NOT_FOUND:
552
+ raise WorkflowError(f"winget is not available. {llamacpp.manual_instructions()}")
553
+ if result.returncode != 0 and not any(m in output.lower() for m in _UP_TO_DATE_MARKERS):
554
+ raise WorkflowError(f"winget upgrade failed (exit code {result.returncode}). {llamacpp.manual_instructions()}")
555
+ ui.show_notice("ok", f"llama.cpp is up to date (llama-server {_refresh_paths()}).")
556
+ return 0
557
+
558
+
559
+ # --- config --------------------------------------------------------------------------------------------------------
560
+
561
+
562
+ def _existing(raw: str, *, directory: bool, key: str) -> str:
563
+ path = Path(raw).expanduser()
564
+ if not (path.is_dir() if directory else path.is_file()):
565
+ raise WorkflowError(f"{key}: {raw!r} is not an existing {'directory' if directory else 'file'}")
566
+ return str(path.resolve())
567
+
568
+
569
+ def _coerce(key: str, raw: str) -> str | int | None:
570
+ """Validate ``raw`` for ``key`` and return the value to store."""
571
+ if key == "port":
572
+ if not raw.isdigit() or not 1 <= int(raw) <= _MAX_PORT:
573
+ raise WorkflowError(f"port: {raw!r} is not a port number (1-{_MAX_PORT})")
574
+ return int(raw)
575
+ if key in {"device", "default_model"} and raw.strip().lower() in _UNSET_WORDS:
576
+ return None
577
+ if key == "host":
578
+ if not raw.strip():
579
+ raise WorkflowError("host: the address cannot be empty")
580
+ return raw.strip()
581
+ if key == "default_model":
582
+ return ollama.normalize_name(raw)
583
+ if key == "device":
584
+ return raw.strip()
585
+ return _existing(raw, directory=key == "ollama_path", key=key)
586
+
587
+
588
+ def _parse_assignments(pairs: Sequence[str]) -> dict[str, str | int | None]:
589
+ values: dict[str, str | int | None] = {}
590
+ for pair in pairs:
591
+ key, sep, raw = pair.partition("=")
592
+ key = key.strip()
593
+ if not sep:
594
+ raise WorkflowError(f"Expected key=value, got {pair!r}")
595
+ if key not in SETTABLE_KEYS:
596
+ raise WorkflowError(f"Unknown setting {key!r}. Settable keys: {', '.join(SETTABLE_KEYS)}")
597
+ values[key] = _coerce(key, raw)
598
+ return values
599
+
600
+
601
+ def _reset(*, assume_yes: bool) -> int:
602
+ path = config.config_file()
603
+ if not path.is_file():
604
+ ui.show_notice("info", f"There is no configuration to reset ({path}).")
605
+ return 0
606
+ if not assume_yes:
607
+ if not _interactive():
608
+ raise WorkflowError("Refusing to delete the configuration without --yes (stdin is not a terminal).")
609
+ if not ui.confirm(f"Delete {path}?", default=False):
610
+ ui.show_notice("info", "Configuration kept.")
611
+ return 0
612
+ path.unlink()
613
+ ui.show_notice("ok", f"Deleted {path}; the next `ollama2cpp serve` runs the first-run setup again.")
614
+ return 0
615
+
616
+
617
+ def run_config(*, set_values: Sequence[str] = (), reset: bool = False, assume_yes: bool = False) -> int:
618
+ """Show the configuration, change settable keys, or delete it.
619
+
620
+ Args:
621
+ set_values: ``key=value`` assignments (validated all together; nothing is written when one is invalid).
622
+ reset: Delete the configuration file.
623
+ assume_yes: Skip the confirmation of ``reset``.
624
+
625
+ Returns:
626
+ int: The exit code.
627
+
628
+ Raises:
629
+ WorkflowError: For an invalid assignment or a refused reset.
630
+ """
631
+ if reset and set_values:
632
+ raise WorkflowError("Use either --set or --reset, not both.")
633
+ if reset:
634
+ return _reset(assume_yes=assume_yes)
635
+ values = _parse_assignments(set_values) # validated before any write
636
+ if values:
637
+ cfg = workflow.load_saved_config() or Config() # a missing file is created; nothing is installed or probed
638
+ for key, value in values.items():
639
+ setattr(cfg, key, value)
640
+ config.save(cfg)
641
+ for key, value in values.items():
642
+ ui.show_notice("ok", f"{key} = {value}")
643
+ elif peek_config()[1] == "missing":
644
+ ui.show_notice("info", f"{config.config_file()}: not configured yet - run `ollama2cpp` once to set up.")
645
+ return 0
646
+ ui.show_notice("info", f"Config file: {config.config_file()}")
647
+ typer.echo(config.config_file().read_text(encoding="utf-8").rstrip())
648
+ return 0