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/http_client.py ADDED
@@ -0,0 +1,187 @@
1
+ """Zero-dependency HTTP client helpers for Hugging Face and llama-server APIs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import json
7
+ import urllib.error
8
+ import urllib.request
9
+ from collections.abc import Callable, Iterator
10
+ from typing import Any
11
+ from urllib.parse import urlparse
12
+
13
+ from llmctl import __version__
14
+
15
+
16
+ class HttpError(Exception):
17
+ """Raised when an HTTP request fails or returns a non-2xx status."""
18
+
19
+ def __init__(
20
+ self,
21
+ message: str,
22
+ *,
23
+ url: str,
24
+ status: int | None = None,
25
+ body: str = "",
26
+ ) -> None:
27
+ super().__init__(message)
28
+ self.url = url
29
+ self.status = status
30
+ self.body = body
31
+
32
+
33
+ def validate_http_url(url: str) -> str:
34
+ """Ensure *url* uses http or https before opening it with urllib."""
35
+ parsed = urlparse(url)
36
+ if parsed.scheme not in {"http", "https"} or not parsed.netloc:
37
+ raise ValueError(f"URL HTTP inválida: {url!r}")
38
+ return url
39
+
40
+
41
+ def default_headers(
42
+ token: str | None = None, *, extra: dict[str, str] | None = None
43
+ ) -> dict[str, str]:
44
+ headers = {"User-Agent": f"llmctl/{__version__}"}
45
+ if token:
46
+ headers["Authorization"] = f"Bearer {token}"
47
+ if extra:
48
+ headers.update(extra)
49
+ return headers
50
+
51
+
52
+ def request_json(
53
+ url: str,
54
+ *,
55
+ method: str = "GET",
56
+ payload: Any | None = None,
57
+ headers: dict[str, str] | None = None,
58
+ token: str | None = None,
59
+ timeout: float | None = 30.0,
60
+ ) -> Any:
61
+ """Send an HTTP request and parse the JSON response."""
62
+ safe_url = validate_http_url(url)
63
+ req_headers = default_headers(token=token, extra=headers)
64
+ data: bytes | None = None
65
+ if payload is not None:
66
+ data = json.dumps(payload).encode("utf-8")
67
+ req_headers.setdefault("Content-Type", "application/json")
68
+
69
+ req = urllib.request.Request(safe_url, data=data, headers=req_headers, method=method)
70
+ try:
71
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
72
+ raw = resp.read().decode("utf-8", errors="replace")
73
+ return json.loads(raw) if raw.strip() else {}
74
+ except urllib.error.HTTPError as exc:
75
+ body = ""
76
+ with contextlib.suppress(Exception):
77
+ body = exc.read().decode("utf-8", errors="replace")
78
+ raise HttpError(
79
+ f"HTTP {exc.code}: {body or exc.reason}",
80
+ url=safe_url,
81
+ status=exc.code,
82
+ body=body,
83
+ ) from exc
84
+ except urllib.error.URLError as exc:
85
+ raise HttpError(f"Error de conexión con {safe_url}: {exc.reason}", url=safe_url) from exc
86
+ except TimeoutError as exc:
87
+ raise HttpError(f"Timeout consultando {safe_url}", url=safe_url) from exc
88
+ except json.JSONDecodeError as exc:
89
+ raise HttpError(f"Respuesta JSON inválida desde {safe_url}: {exc}", url=safe_url) from exc
90
+
91
+
92
+ def download_bytes(
93
+ url: str,
94
+ *,
95
+ headers: dict[str, str] | None = None,
96
+ token: str | None = None,
97
+ timeout: float = 60.0,
98
+ on_progress: Callable[[int, int | None], None] | None = None,
99
+ ) -> bytes:
100
+ """Download raw bytes from an HTTP(S) endpoint, optionally reporting chunk progress."""
101
+ safe_url = validate_http_url(url)
102
+ req = urllib.request.Request(safe_url, headers=default_headers(token=token, extra=headers))
103
+ try:
104
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
105
+ if on_progress is None:
106
+ return resp.read()
107
+ total_hdr = resp.headers.get("Content-Length") if hasattr(resp, "headers") else None
108
+ total = int(total_hdr) if total_hdr and total_hdr.isdigit() else None
109
+ chunks: list[bytes] = []
110
+ downloaded = 0
111
+ while True:
112
+ block = resp.read(65536)
113
+ if not block:
114
+ break
115
+ chunks.append(block)
116
+ downloaded += len(block)
117
+ on_progress(downloaded, total)
118
+ return b"".join(chunks)
119
+ except urllib.error.HTTPError as exc:
120
+ body = ""
121
+ with contextlib.suppress(Exception):
122
+ body = exc.read().decode("utf-8", errors="replace")
123
+ raise HttpError(
124
+ f"HTTP {exc.code}: {body or exc.reason}",
125
+ url=safe_url,
126
+ status=exc.code,
127
+ body=body,
128
+ ) from exc
129
+ except urllib.error.URLError as exc:
130
+ raise HttpError(f"Error descargando {safe_url}: {exc.reason}", url=safe_url) from exc
131
+
132
+
133
+ def stream_sse_json(
134
+ url: str,
135
+ *,
136
+ payload: Any,
137
+ headers: dict[str, str] | None = None,
138
+ token: str | None = None,
139
+ timeout: float | None = 300.0,
140
+ ) -> Iterator[dict[str, Any]]:
141
+ """POST JSON payload and yield parsed Server-Sent Events (`data: {...}`) chunks."""
142
+ safe_url = validate_http_url(url)
143
+ req_headers = default_headers(token=token, extra=headers)
144
+ req_headers.setdefault("Content-Type", "application/json")
145
+ req_headers.setdefault("Accept", "text/event-stream")
146
+ data = json.dumps(payload).encode("utf-8")
147
+ req = urllib.request.Request(safe_url, data=data, headers=req_headers, method="POST")
148
+
149
+ try:
150
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
151
+ for raw_line in resp:
152
+ line = raw_line.decode("utf-8", errors="replace").strip()
153
+ if not line or not line.startswith("data:"):
154
+ continue
155
+ body = line[5:].strip()
156
+ if body == "[DONE]":
157
+ break
158
+ try:
159
+ parsed = json.loads(body)
160
+ except json.JSONDecodeError:
161
+ continue
162
+ if isinstance(parsed, dict):
163
+ yield parsed
164
+ except urllib.error.HTTPError as exc:
165
+ body = ""
166
+ with contextlib.suppress(Exception):
167
+ body = exc.read().decode("utf-8", errors="replace")
168
+ raise HttpError(
169
+ f"HTTP {exc.code}: {body or exc.reason}",
170
+ url=safe_url,
171
+ status=exc.code,
172
+ body=body,
173
+ ) from exc
174
+ except urllib.error.URLError as exc:
175
+ raise HttpError(f"Error de conexión con {safe_url}: {exc.reason}", url=safe_url) from exc
176
+ except TimeoutError as exc:
177
+ raise HttpError(f"Timeout consultando {safe_url}", url=safe_url) from exc
178
+
179
+
180
+ def check_json_endpoint(
181
+ url: str, *, token: str | None = None, timeout: float = 2.5
182
+ ) -> tuple[bool, Any]:
183
+ """Probe a JSON endpoint, returning (reachable, data_or_error_message)."""
184
+ try:
185
+ return True, request_json(url, token=token, timeout=timeout)
186
+ except (HttpError, ValueError) as exc:
187
+ return False, str(exc)
llmctl/presets.py ADDED
@@ -0,0 +1,288 @@
1
+ """Atomic parser and editor for llama-server router models.ini files."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import os
7
+ import re
8
+ import tempfile
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+
12
+ SECTION_RE = re.compile(r"^\[([^\]]+)\]\s*$")
13
+
14
+ DEFAULT_INI_CONTENT = """[*]
15
+ # Configuración global del router llama-server
16
+ """
17
+
18
+
19
+ @dataclass
20
+ class Preset:
21
+ """Single model preset section from models.ini."""
22
+
23
+ name: str
24
+ hf_repo: str = ""
25
+ hf_file: str = ""
26
+ model_path: str = ""
27
+ mmproj: str = ""
28
+ options: dict[str, str] = field(default_factory=dict)
29
+ raw_lines: list[str] = field(default_factory=list)
30
+
31
+ @property
32
+ def repo_id(self) -> str:
33
+ """Return repo id without optional :quant suffix."""
34
+ return self.hf_repo.split(":", 1)[0].strip()
35
+
36
+ @property
37
+ def mmproj_url(self) -> str:
38
+ return self.options.get("mmproj-url", "")
39
+
40
+ @property
41
+ def has_vision_config(self) -> bool:
42
+ return bool(self.mmproj or self.mmproj_url)
43
+
44
+ def to_dict(self) -> dict[str, object]:
45
+ return {
46
+ "name": self.name,
47
+ "hf_repo": self.hf_repo,
48
+ "hf_file": self.hf_file,
49
+ "model_path": self.model_path,
50
+ "mmproj": self.mmproj,
51
+ "mmproj_url": self.mmproj_url,
52
+ "options": dict(self.options),
53
+ }
54
+
55
+
56
+ def atomic_write_text(path: Path, content: str) -> None:
57
+ """Write *content* atomically via a temporary file in the same directory."""
58
+ path.parent.mkdir(parents=True, exist_ok=True)
59
+ fd, tmp_name = tempfile.mkstemp(
60
+ prefix=f".{path.name}.",
61
+ suffix=".tmp",
62
+ dir=str(path.parent),
63
+ )
64
+ tmp_path = Path(tmp_name)
65
+ try:
66
+ with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as fh:
67
+ fh.write(content)
68
+ fh.flush()
69
+ os.fsync(fh.fileno())
70
+ os.replace(tmp_path, path)
71
+ except Exception:
72
+ with contextlib.suppress(OSError):
73
+ tmp_path.unlink(missing_ok=True)
74
+ raise
75
+
76
+
77
+ def ensure_ini(ini_path: Path) -> Path:
78
+ """Create models.ini with a global [*] section if it does not exist."""
79
+ if not ini_path.exists():
80
+ atomic_write_text(ini_path, DEFAULT_INI_CONTENT)
81
+ return ini_path
82
+
83
+
84
+ def parse_sections(text: str) -> list[tuple[str | None, list[str]]]:
85
+ """Parse INI content preserving comments, blank lines, and ordering."""
86
+ sections: list[tuple[str | None, list[str]]] = []
87
+ current_name: str | None = None
88
+ current_lines: list[str] = []
89
+
90
+ for line in text.splitlines(keepends=True):
91
+ match = SECTION_RE.match(line.strip())
92
+ if match:
93
+ if current_name is not None or current_lines:
94
+ sections.append((current_name, current_lines))
95
+ current_name = match.group(1).strip()
96
+ current_lines = [line]
97
+ else:
98
+ current_lines.append(line)
99
+
100
+ if current_name is not None or current_lines:
101
+ sections.append((current_name, current_lines))
102
+ return sections
103
+
104
+
105
+ def _section_to_preset(name: str, lines: list[str]) -> Preset:
106
+ options: dict[str, str] = {}
107
+ for line in lines[1:]:
108
+ stripped = line.strip()
109
+ if not stripped or stripped.startswith(("#", ";")) or "=" not in stripped:
110
+ continue
111
+ key, val = stripped.split("=", 1)
112
+ options[key.strip()] = val.strip()
113
+ return Preset(
114
+ name=name,
115
+ hf_repo=options.get("hf-repo", ""),
116
+ hf_file=options.get("hf-file", ""),
117
+ model_path=options.get("model", ""),
118
+ mmproj=options.get("mmproj", ""),
119
+ options=options,
120
+ raw_lines=list(lines),
121
+ )
122
+
123
+
124
+ def list_presets(ini_path: Path) -> list[Preset]:
125
+ """Return all non-global model presets configured in *ini_path*."""
126
+ if not ini_path.is_file():
127
+ return []
128
+ text = ini_path.read_text(encoding="utf-8", errors="replace")
129
+ presets: list[Preset] = []
130
+ for name, lines in parse_sections(text):
131
+ if name and name != "*":
132
+ presets.append(_section_to_preset(name, lines))
133
+ return presets
134
+
135
+
136
+ def get_preset(ini_path: Path, alias: str) -> Preset | None:
137
+ """Return a single preset by alias, or None if not found."""
138
+ for preset in list_presets(ini_path):
139
+ if preset.name == alias:
140
+ return preset
141
+ return None
142
+
143
+
144
+ def add_preset(
145
+ ini_path: Path,
146
+ name: str,
147
+ hf_repo: str = "",
148
+ *,
149
+ model_path: str | None = None,
150
+ hf_file: str | None = None,
151
+ cpu_moe: bool = False,
152
+ n_cpu_moe: int | None = None,
153
+ extra_options: dict[str, str] | None = None,
154
+ ) -> Preset:
155
+ """Append a new preset (Hugging Face or local GGUF) to *ini_path* atomically."""
156
+ clean_name = name.strip()
157
+ if not clean_name or clean_name == "*" or "[" in clean_name or "]" in clean_name:
158
+ raise ValueError(f"Alias inválido: {name!r}")
159
+ if not hf_repo.strip() and not (model_path and model_path.strip()):
160
+ raise ValueError("Se requiere 'hf_repo' o 'model_path' para crear el preset.")
161
+
162
+ ensure_ini(ini_path)
163
+ existing_text = ini_path.read_text(encoding="utf-8", errors="replace")
164
+ sections = parse_sections(existing_text)
165
+ if any(sec_name == clean_name for sec_name, _ in sections):
166
+ raise ValueError(f"El preset [{clean_name}] ya existe en {ini_path}.")
167
+
168
+ block_lines = [f"[{clean_name}]\n"]
169
+ if model_path and model_path.strip():
170
+ block_lines.append(f"model = {model_path.strip()}\n")
171
+ if hf_repo.strip():
172
+ block_lines.append(f"hf-repo = {hf_repo.strip()}\n")
173
+ if hf_file:
174
+ block_lines.append(f"hf-file = {hf_file.strip()}\n")
175
+ if n_cpu_moe is not None:
176
+ block_lines.append(f"n-cpu-moe = {n_cpu_moe}\n")
177
+ elif cpu_moe:
178
+ block_lines.append("cpu-moe = true\n")
179
+ if extra_options:
180
+ for key, value in extra_options.items():
181
+ block_lines.append(f"{key} = {value}\n")
182
+
183
+ prefix = existing_text.rstrip("\n")
184
+ new_text = f"{prefix}\n\n{''.join(block_lines)}" if prefix else "".join(block_lines)
185
+ atomic_write_text(ini_path, new_text)
186
+ return _section_to_preset(clean_name, block_lines)
187
+
188
+
189
+ def remove_preset(ini_path: Path, alias: str) -> Preset:
190
+ """Remove *alias* from *ini_path* atomically. Raises KeyError if not found."""
191
+ if not ini_path.is_file():
192
+ raise FileNotFoundError(f"No existe {ini_path}")
193
+
194
+ text = ini_path.read_text(encoding="utf-8", errors="replace")
195
+ sections = parse_sections(text)
196
+
197
+ removed: Preset | None = None
198
+ kept: list[tuple[str | None, list[str]]] = []
199
+ for name, lines in sections:
200
+ if name == alias and removed is None:
201
+ removed = _section_to_preset(name, lines)
202
+ else:
203
+ kept.append((name, lines))
204
+
205
+ if removed is None:
206
+ raise KeyError(f"No existe el alias [{alias}] en {ini_path}")
207
+
208
+ rebuilt = "".join("".join(lines) for _, lines in kept).rstrip()
209
+ atomic_write_text(ini_path, f"{rebuilt}\n" if rebuilt else "")
210
+ return removed
211
+
212
+
213
+ def set_preset_options(
214
+ ini_path: Path,
215
+ alias: str,
216
+ updates: dict[str, str | None],
217
+ ) -> Preset:
218
+ """Atomically set or unset keys in an existing preset section, preserving comments."""
219
+ if not ini_path.is_file():
220
+ raise FileNotFoundError(f"No existe {ini_path}")
221
+
222
+ text = ini_path.read_text(encoding="utf-8", errors="replace")
223
+ sections = parse_sections(text)
224
+
225
+ updated_preset: Preset | None = None
226
+ new_sections: list[tuple[str | None, list[str]]] = []
227
+
228
+ for name, lines in sections:
229
+ if name != alias:
230
+ new_sections.append((name, lines))
231
+ continue
232
+
233
+ remaining = dict(updates)
234
+ rebuilt_lines: list[str] = [lines[0]]
235
+ trailing_blanks: list[str] = []
236
+
237
+ body = lines[1:]
238
+ while body and not body[-1].strip():
239
+ trailing_blanks.insert(0, body.pop())
240
+
241
+ for line in body:
242
+ stripped = line.strip()
243
+ if not stripped or stripped.startswith(("#", ";")) or "=" not in stripped:
244
+ rebuilt_lines.append(line)
245
+ continue
246
+ key = stripped.split("=", 1)[0].strip()
247
+ if key in remaining:
248
+ new_val = remaining.pop(key)
249
+ if new_val is not None:
250
+ rebuilt_lines.append(f"{key} = {new_val}\n")
251
+ # None => unset (drop line)
252
+ else:
253
+ rebuilt_lines.append(line)
254
+
255
+ for key, new_val in remaining.items():
256
+ if new_val is not None:
257
+ rebuilt_lines.append(f"{key} = {new_val}\n")
258
+
259
+ rebuilt_lines.extend(trailing_blanks)
260
+ updated_preset = _section_to_preset(name, rebuilt_lines)
261
+ new_sections.append((name, rebuilt_lines))
262
+
263
+ if updated_preset is None:
264
+ raise KeyError(f"No existe el alias [{alias}] en {ini_path}")
265
+
266
+ rebuilt = "".join("".join(lines) for _, lines in new_sections).rstrip()
267
+ atomic_write_text(ini_path, f"{rebuilt}\n" if rebuilt else "")
268
+ return updated_preset
269
+
270
+
271
+ def repo_cache_dirname(hf_repo: str) -> str:
272
+ """Convert an hf-repo spec (e.g. 'org/model:Q4_K_M') into its HF cache directory name."""
273
+ repo_id = hf_repo.split(":", 1)[0].strip()
274
+ if not repo_id:
275
+ return ""
276
+ return f"models--{repo_id.replace('/', '--')}".lower()
277
+
278
+
279
+ def active_repo_dirnames(ini_path: Path, *, exclude_alias: str | None = None) -> set[str]:
280
+ """Return lowercase HF cache directory names referenced by presets in *ini_path*."""
281
+ active: set[str] = set()
282
+ for preset in list_presets(ini_path):
283
+ if exclude_alias is not None and preset.name == exclude_alias:
284
+ continue
285
+ dirname = repo_cache_dirname(preset.hf_repo)
286
+ if dirname:
287
+ active.add(dirname)
288
+ return active