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/tester.py ADDED
@@ -0,0 +1,408 @@
1
+ """Model capability detection and live benchmark/smoke test runner."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import struct
7
+ import time
8
+ import zlib
9
+ from dataclasses import asdict, dataclass
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from llmctl.config import AppConfig
14
+ from llmctl.hardware import detect_hardware
15
+ from llmctl.http_client import HttpError, request_json
16
+ from llmctl.presets import get_preset
17
+ from llmctl.ui import Console
18
+
19
+ ALL_TEST_MODES = ("text", "vision", "tools", "embed", "fim")
20
+
21
+
22
+ @dataclass
23
+ class TestCaseResult:
24
+ """Outcome of a single capability probe against llama-server."""
25
+
26
+ mode: str
27
+ ok: bool
28
+ status: str
29
+ elapsed_s: float
30
+ gen_tps: float = 0.0
31
+ prompt_tps: float = 0.0
32
+ detail: str = ""
33
+
34
+ def to_dict(self) -> dict[str, object]:
35
+ return asdict(self)
36
+
37
+
38
+ def make_red_png_b64(size: int = 16) -> str:
39
+ """Generate a tiny solid-red PNG encoded as base64 using only stdlib zlib/struct."""
40
+
41
+ def chunk(tag: bytes, data: bytes) -> bytes:
42
+ crc = zlib.crc32(tag + data) & 0xFFFFFFFF
43
+ return struct.pack("!I", len(data)) + tag + data + struct.pack("!I", crc)
44
+
45
+ raw = b"".join(b"\x00" + b"\xff\x00\x00" * size for _ in range(size))
46
+ ihdr = struct.pack("!IIBBBBB", size, size, 8, 2, 0, 0, 0)
47
+ png = (
48
+ b"\x89PNG\r\n\x1a\n"
49
+ + chunk(b"IHDR", ihdr)
50
+ + chunk(b"IDAT", zlib.compress(raw))
51
+ + chunk(b"IEND", b"")
52
+ )
53
+ return base64.b64encode(png).decode("ascii")
54
+
55
+
56
+ def detect_test_suite(
57
+ alias: str,
58
+ ini_path: Path,
59
+ *,
60
+ hf_token: str | None = None,
61
+ ) -> tuple[list[str], list[str], str | None]:
62
+ """Infer relevant test modes from models.ini + optional Hugging Face metadata."""
63
+ preset = get_preset(ini_path, alias)
64
+ if preset is None:
65
+ return ["text"], [], None
66
+
67
+ hf_repo = preset.repo_id
68
+ has_vision = preset.has_vision_config
69
+ has_tools = False
70
+ has_embed = False
71
+ has_reasoning = False
72
+ has_chat = True
73
+ warning: str | None = None
74
+
75
+ if hf_repo:
76
+ try:
77
+ meta = request_json(
78
+ f"https://huggingface.co/api/models/{hf_repo}",
79
+ token=hf_token,
80
+ timeout=15.0,
81
+ )
82
+ tree = request_json(
83
+ f"https://huggingface.co/api/models/{hf_repo}/tree/main",
84
+ token=hf_token,
85
+ timeout=15.0,
86
+ )
87
+ if isinstance(meta, dict):
88
+ pipeline = str(meta.get("pipeline_tag") or "").lower()
89
+ raw_tags = [str(t).lower() for t in meta.get("tags", [])]
90
+ blob = " ".join([*raw_tags, pipeline, hf_repo.lower()])
91
+
92
+ if pipeline == "feature-extraction" or any(
93
+ k in blob for k in ("embed", "bge-", "e5-", "nomic-embed")
94
+ ):
95
+ has_embed = True
96
+ if (
97
+ pipeline == "feature-extraction"
98
+ and "text-generation" not in blob
99
+ and "conversational" not in blob
100
+ ):
101
+ has_chat = False
102
+ if (
103
+ (
104
+ isinstance(tree, list)
105
+ and any("mmproj" in str(f.get("path", "")).lower() for f in tree)
106
+ )
107
+ or pipeline == "image-text-to-text"
108
+ or any(k in blob for k in ("vision", "multimodal", "-vl-", "vlm"))
109
+ ):
110
+ has_vision = True
111
+ if any(
112
+ k in blob for k in ("tool", "function-calling", "function_calling", "agent")
113
+ ):
114
+ has_tools = True
115
+ if any(k in blob for k in ("thinking", "reasoning", "deepseek-r1", "qwq")):
116
+ has_reasoning = True
117
+ except HttpError as exc:
118
+ warning = f"No se pudieron leer metadatos de HF ({exc}); ejecutando test local."
119
+
120
+ suite: list[str] = []
121
+ detected: list[str] = []
122
+
123
+ if has_embed:
124
+ detected.append("Embeddings")
125
+ suite.append("embed")
126
+ if has_reasoning:
127
+ detected.append("Razonamiento/Thinking")
128
+ if "text" not in suite:
129
+ suite.append("text")
130
+ elif has_chat:
131
+ detected.append("Chat/Texto")
132
+ if "text" not in suite:
133
+ suite.append("text")
134
+ if has_vision:
135
+ detected.append("Visión")
136
+ if "vision" not in suite:
137
+ suite.append("vision")
138
+ if has_tools:
139
+ detected.append("Tools")
140
+ if "tools" not in suite:
141
+ suite.append("tools")
142
+
143
+ return (suite or ["text"]), detected, warning
144
+
145
+
146
+ def _build_payload(alias: str, config: AppConfig, test_mode: str) -> tuple[str, dict[str, Any]]:
147
+ if test_mode == "embed":
148
+ return config.embeddings_url, {
149
+ "model": alias,
150
+ "input": "Prueba de embeddings en llama-server",
151
+ }
152
+ if test_mode == "fim":
153
+ return config.infill_url, {
154
+ "model": alias,
155
+ "input_prefix": "def suma(a: int, b: int) -> int:\n ",
156
+ "input_suffix": "\n return res",
157
+ "n_predict": 32,
158
+ "temperature": 0.1,
159
+ }
160
+ if test_mode == "vision":
161
+ img_b64 = make_red_png_b64()
162
+ return config.chat_completions_url, {
163
+ "model": alias,
164
+ "max_tokens": 128,
165
+ "temperature": 0.1,
166
+ "messages": [
167
+ {
168
+ "role": "user",
169
+ "content": [
170
+ {
171
+ "type": "text",
172
+ "text": "¿De qué color es esta imagen? Responde en una palabra.",
173
+ },
174
+ {
175
+ "type": "image_url",
176
+ "image_url": {"url": f"data:image/png;base64,{img_b64}"},
177
+ },
178
+ ],
179
+ }
180
+ ],
181
+ }
182
+ if test_mode == "tools":
183
+ return config.chat_completions_url, {
184
+ "model": alias,
185
+ "max_tokens": 128,
186
+ "temperature": 0.1,
187
+ "messages": [{"role": "user", "content": "¿Qué tiempo hace en Madrid?"}],
188
+ "tools": [
189
+ {
190
+ "type": "function",
191
+ "function": {
192
+ "name": "get_weather",
193
+ "description": "Obtiene el tiempo actual de una ciudad",
194
+ "parameters": {
195
+ "type": "object",
196
+ "properties": {"city": {"type": "string"}},
197
+ "required": ["city"],
198
+ },
199
+ },
200
+ }
201
+ ],
202
+ "tool_choice": "auto",
203
+ }
204
+
205
+ return config.chat_completions_url, {
206
+ "model": alias,
207
+ "max_tokens": 128,
208
+ "temperature": 0.1,
209
+ "messages": [{"role": "user", "content": "Responde en una sola frase corta: ¿funciona?"}],
210
+ }
211
+
212
+
213
+ def run_single_test(
214
+ alias: str,
215
+ config: AppConfig,
216
+ test_mode: str,
217
+ *,
218
+ timeout: float = 300.0,
219
+ ) -> TestCaseResult:
220
+ """Execute one test mode against llama-server and return structured metrics."""
221
+ target_url, body = _build_payload(alias, config, test_mode)
222
+ t0 = time.monotonic()
223
+ try:
224
+ data = request_json(
225
+ target_url,
226
+ method="POST",
227
+ payload=body,
228
+ token=config.api_key,
229
+ timeout=timeout,
230
+ )
231
+ except HttpError as exc:
232
+ return TestCaseResult(
233
+ mode=test_mode,
234
+ ok=False,
235
+ status="ERROR",
236
+ elapsed_s=round(time.monotonic() - t0, 3),
237
+ detail=str(exc),
238
+ )
239
+
240
+ elapsed = round(time.monotonic() - t0, 3)
241
+ timings = data.get("timings", {}) if isinstance(data, dict) else {}
242
+ gen_tps = float(timings.get("predicted_per_second", 0.0) or 0.0)
243
+ prompt_tps = float(timings.get("prompt_per_second", 0.0) or 0.0)
244
+
245
+ if test_mode == "embed":
246
+ emb_list = data.get("data") if isinstance(data, dict) else None
247
+ vec = emb_list[0].get("embedding") if isinstance(emb_list, list) and emb_list else None
248
+ if isinstance(vec, list) and vec:
249
+ sample = [round(float(x), 4) for x in vec[:4]]
250
+ return TestCaseResult(
251
+ mode="embed",
252
+ ok=True,
253
+ status=f"OK ({len(vec)}d)",
254
+ elapsed_s=elapsed,
255
+ detail=f"Vector {len(vec)}d | Muestra: {sample}",
256
+ )
257
+ return TestCaseResult(
258
+ mode="embed",
259
+ ok=False,
260
+ status="ERROR",
261
+ elapsed_s=elapsed,
262
+ detail="Respuesta sin vector de embeddings válido.",
263
+ )
264
+
265
+ if test_mode == "fim":
266
+ content_out = str(data.get("content") or "").strip() if isinstance(data, dict) else ""
267
+ if not content_out and isinstance(data, dict) and data.get("choices"):
268
+ ch0 = data["choices"][0]
269
+ content_out = str(
270
+ ch0.get("text") or ch0.get("message", {}).get("content") or ""
271
+ ).strip()
272
+ if content_out:
273
+ return TestCaseResult(
274
+ mode="fim",
275
+ ok=True,
276
+ status="OK",
277
+ elapsed_s=elapsed,
278
+ gen_tps=round(gen_tps, 2),
279
+ prompt_tps=round(prompt_tps, 2),
280
+ detail=content_out,
281
+ )
282
+ return TestCaseResult(
283
+ mode="fim",
284
+ ok=False,
285
+ status="VACÍO",
286
+ elapsed_s=elapsed,
287
+ detail="/infill respondió vacío.",
288
+ )
289
+
290
+ choices = data.get("choices") if isinstance(data, dict) else None
291
+ msg_obj = choices[0].get("message", {}) if isinstance(choices, list) and choices else {}
292
+ text = str(msg_obj.get("content") or "").strip()
293
+ reasoning = str(msg_obj.get("reasoning_content") or "").strip()
294
+ tool_calls = msg_obj.get("tool_calls") or []
295
+
296
+ if test_mode == "tools":
297
+ if isinstance(tool_calls, list) and tool_calls:
298
+ calls_desc = ", ".join(
299
+ f"{tc.get('function', {}).get('name')}({tc.get('function', {}).get('arguments')})"
300
+ for tc in tool_calls
301
+ if isinstance(tc, dict)
302
+ )
303
+ return TestCaseResult(
304
+ mode="tools",
305
+ ok=True,
306
+ status="OK",
307
+ elapsed_s=elapsed,
308
+ gen_tps=round(gen_tps, 2),
309
+ prompt_tps=round(prompt_tps, 2),
310
+ detail=f"Tool calls: {calls_desc}",
311
+ )
312
+ return TestCaseResult(
313
+ mode="tools",
314
+ ok=False,
315
+ status="SIN TOOL_CALLS",
316
+ elapsed_s=elapsed,
317
+ gen_tps=round(gen_tps, 2),
318
+ prompt_tps=round(prompt_tps, 2),
319
+ detail=text or reasoning or "Sin invocaciones de herramientas.",
320
+ )
321
+
322
+ status = "OK (Thinking)" if (test_mode == "text" and reasoning) else "OK"
323
+ preview = text or (f"[Thinking] {reasoning}" if reasoning else "(vacío)")
324
+ return TestCaseResult(
325
+ mode=test_mode,
326
+ ok=bool(text or reasoning),
327
+ status=status if (text or reasoning) else "VACÍO",
328
+ elapsed_s=elapsed,
329
+ gen_tps=round(gen_tps, 2),
330
+ prompt_tps=round(prompt_tps, 2),
331
+ detail=preview,
332
+ )
333
+
334
+
335
+ def run_test_suite(
336
+ alias: str,
337
+ config: AppConfig,
338
+ console: Console,
339
+ *,
340
+ mode: str = "auto",
341
+ ) -> int:
342
+ """Run one or more capability tests for *alias* and display results."""
343
+ detected: list[str] = []
344
+ warning: str | None = None
345
+ if mode == "auto":
346
+ suite, detected, warning = detect_test_suite(
347
+ alias, config.models_ini, hf_token=config.hf_token
348
+ )
349
+ elif mode == "all":
350
+ suite = list(ALL_TEST_MODES)
351
+ else:
352
+ suite = [mode]
353
+
354
+ if not console.json_mode:
355
+ if warning:
356
+ console.warn(warning)
357
+ if mode == "auto":
358
+ caps_str = ", ".join(detected) if detected else "Estándar"
359
+ console.line(f"Capacidades detectadas para [{alias}]: {caps_str}")
360
+ console.line(f"Tests a ejecutar: {', '.join(suite)}")
361
+
362
+ results: list[TestCaseResult] = []
363
+ for test_mode in suite:
364
+ res = run_single_test(alias, config, test_mode)
365
+ results.append(res)
366
+ if not console.json_mode:
367
+ console.line(f"\n=== [{alias}] Test: {test_mode.upper()} ===")
368
+ if res.ok:
369
+ console.ok(f"{res.status}: {res.detail}")
370
+ else:
371
+ console.error(f"{res.status}: {res.detail}")
372
+ if test_mode != "embed":
373
+ console.line(
374
+ f"Tiempo: {res.elapsed_s:.2f}s | Gen: {res.gen_tps:.1f} tok/s | "
375
+ f"Prompt: {res.prompt_tps:.1f} tok/s"
376
+ )
377
+ else:
378
+ console.line(f"Tiempo: {res.elapsed_s:.2f}s")
379
+
380
+ hw = detect_hardware(sys_platform=config.sys_platform)
381
+ vram_summary = (
382
+ f"{hw.vram_used_gb:.2f} / {hw.vram_total_gb:.2f} GiB"
383
+ if hw.vram_used_gb is not None
384
+ else (
385
+ f"{hw.vram_total_gb:.2f} GiB ({'unificada' if hw.unified_memory else 'total'})"
386
+ if hw.vram_total_gb > 0
387
+ else "N/A"
388
+ )
389
+ )
390
+ all_ok = all(r.ok for r in results)
391
+
392
+ if console.json_mode:
393
+ console.emit_json(
394
+ {
395
+ "alias": alias,
396
+ "mode": mode,
397
+ "detected_capabilities": detected,
398
+ "ok": all_ok,
399
+ "results": [r.to_dict() for r in results],
400
+ "vram": vram_summary,
401
+ }
402
+ )
403
+ else:
404
+ console.line(f"\n--- Resumen [{alias}] ---")
405
+ console.line(" | ".join(f"{r.mode}: {r.status}" for r in results))
406
+ console.line(f"VRAM actual: {vram_summary}")
407
+
408
+ return 0 if all_ok else 1
llmctl/ui.py ADDED
@@ -0,0 +1,194 @@
1
+ """Terminal UI helpers: portable ANSI colors, JSON output, prompts, and editors."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import shlex
8
+ import shutil
9
+ import subprocess
10
+ import sys
11
+ from collections.abc import Sequence
12
+ from pathlib import Path
13
+ from typing import Any, TextIO
14
+
15
+
16
+ def _enable_windows_ansi() -> bool:
17
+ """Best-effort enable ANSI virtual terminal processing on Windows consoles."""
18
+ if sys.platform != "win32":
19
+ return True
20
+ try:
21
+ import ctypes
22
+
23
+ windll = getattr(ctypes, "windll", None)
24
+ if windll is None:
25
+ return False
26
+ kernel32 = windll.kernel32
27
+ handle = kernel32.GetStdHandle(-11) # STD_OUTPUT_HANDLE
28
+ mode = ctypes.c_uint32()
29
+ if not kernel32.GetConsoleMode(handle, ctypes.byref(mode)):
30
+ return False
31
+ enable_vt = 0x0004
32
+ return bool(kernel32.SetConsoleMode(handle, mode.value | enable_vt))
33
+ except Exception:
34
+ return False
35
+
36
+
37
+ def _should_use_color(color_mode: str, stream: TextIO) -> bool:
38
+ if color_mode == "never" or os.environ.get("NO_COLOR") is not None:
39
+ return False
40
+ if color_mode == "always" or os.environ.get("FORCE_COLOR"):
41
+ return _enable_windows_ansi()
42
+ if not hasattr(stream, "isatty") or not stream.isatty():
43
+ return False
44
+ return _enable_windows_ansi()
45
+
46
+
47
+ class Console:
48
+ """Zero-dependency terminal presenter with JSON, color, and TTY-safe prompts."""
49
+
50
+ def __init__(
51
+ self,
52
+ *,
53
+ json_mode: bool = False,
54
+ color_mode: str = "auto",
55
+ assume_yes: bool = False,
56
+ stdout: TextIO | None = None,
57
+ stderr: TextIO | None = None,
58
+ ) -> None:
59
+ self.json_mode = json_mode
60
+ self.assume_yes = assume_yes
61
+ self.stdout = sys.stdout if stdout is None else stdout
62
+ self.stderr = sys.stderr if stderr is None else stderr
63
+ self.use_color = (not json_mode) and _should_use_color(color_mode, self.stdout)
64
+
65
+ def _style(self, text: str, code: str) -> str:
66
+ if not self.use_color:
67
+ return text
68
+ return f"\033[{code}m{text}\033[0m"
69
+
70
+ def bold(self, text: str) -> str:
71
+ return self._style(text, "1")
72
+
73
+ def dim(self, text: str) -> str:
74
+ return self._style(text, "2")
75
+
76
+ def green(self, text: str) -> str:
77
+ return self._style(text, "32")
78
+
79
+ def yellow(self, text: str) -> str:
80
+ return self._style(text, "33")
81
+
82
+ def red(self, text: str) -> str:
83
+ return self._style(text, "31")
84
+
85
+ def cyan(self, text: str) -> str:
86
+ return self._style(text, "36")
87
+
88
+ def line(self, text: str = "") -> None:
89
+ print(text, file=self.stdout)
90
+
91
+ def header(self, title: str) -> None:
92
+ self.line(self.bold(f"=== {title} ==="))
93
+
94
+ def ok(self, message: str) -> None:
95
+ self.line(f" {self.green('[OK]')} {message}")
96
+
97
+ def info(self, message: str) -> None:
98
+ self.line(f" {self.cyan('[INFO]')} {message}")
99
+
100
+ def warn(self, message: str) -> None:
101
+ self.line(f" {self.yellow('[AVISO]')} {message}")
102
+
103
+ def error(self, message: str) -> None:
104
+ prefix = self.red("[ERROR]") if self.use_color else "[ERROR]"
105
+ print(f"{prefix} {message}", file=self.stderr)
106
+
107
+ def emit_json(self, data: Any) -> None:
108
+ print(json.dumps(data, ensure_ascii=False, indent=2), file=self.stdout)
109
+
110
+ def print_table(self, headers: Sequence[str], rows: Sequence[Sequence[str]]) -> None:
111
+ if not rows:
112
+ return
113
+ widths = [len(h) for h in headers]
114
+ for row in rows:
115
+ for idx, cell in enumerate(row):
116
+ if idx < len(widths):
117
+ widths[idx] = max(widths[idx], len(cell))
118
+ fmt = " ".join(f"{{:<{w}}}" for w in widths)
119
+ self.line(self.bold(fmt.format(*headers)))
120
+ self.line(self.dim(" ".join("-" * w for w in widths)))
121
+ for row in rows:
122
+ padded = [row[i] if i < len(row) else "" for i in range(len(headers))]
123
+ self.line(fmt.format(*padded))
124
+
125
+ def is_interactive(self) -> bool:
126
+ return hasattr(sys.stdin, "isatty") and sys.stdin.isatty()
127
+
128
+ def confirm(self, question: str, *, default: bool = False) -> bool:
129
+ if self.assume_yes:
130
+ return True
131
+ if not self.is_interactive():
132
+ self.error("No hay terminal interactiva para confirmar la operación. Usa '--yes'.")
133
+ return False
134
+ suffix = "[S/n]" if default else "[s/N]"
135
+ try:
136
+ answer = input(f"{question} {suffix}: ").strip().lower()
137
+ except EOFError:
138
+ return default
139
+ if not answer:
140
+ return default
141
+ return answer in {"s", "si", "sí", "y", "yes"}
142
+
143
+ def prompt(self, question: str, *, default: str = "") -> str:
144
+ suffix = f" [{default}]" if default else ""
145
+ try:
146
+ value = input(f"{question}{suffix}: ").strip()
147
+ except EOFError:
148
+ return default
149
+ return value or default
150
+
151
+
152
+ def resolve_editor(configured: str = "", *, sys_platform: str | None = None) -> list[str] | None:
153
+ """Resolve an interactive text editor command across Linux, macOS, and Windows."""
154
+ plat = sys.platform if sys_platform is None else sys_platform
155
+ candidates = [
156
+ configured.strip(),
157
+ os.environ.get("VISUAL", "").strip(),
158
+ os.environ.get("EDITOR", "").strip(),
159
+ ]
160
+ for raw in candidates:
161
+ if not raw:
162
+ continue
163
+ parts = shlex.split(raw, posix=(plat != "win32"))
164
+ if parts and shutil.which(parts[0]):
165
+ return parts
166
+
167
+ fallbacks = (
168
+ [["notepad"], ["code", "--wait"]]
169
+ if plat == "win32"
170
+ else ([["nano"], ["vi"], ["open", "-t"]] if plat == "darwin" else [["nano"], ["vi"]])
171
+ )
172
+ for cmd in fallbacks:
173
+ if shutil.which(cmd[0]):
174
+ return cmd
175
+ return None
176
+
177
+
178
+ def open_in_editor(
179
+ path: Path,
180
+ *,
181
+ configured_editor: str = "",
182
+ console: Console | None = None,
183
+ sys_platform: str | None = None,
184
+ ) -> int:
185
+ """Open *path* in the resolved editor, or print its contents if none is available."""
186
+ cmd = resolve_editor(configured_editor, sys_platform=sys_platform)
187
+ if not cmd:
188
+ if console:
189
+ console.warn(f"No hay editor interactivo disponible. Archivo: {path}")
190
+ if path.is_file():
191
+ console.line(path.read_text(encoding="utf-8", errors="replace"))
192
+ return 0
193
+ result = subprocess.run([*cmd, str(path)], check=False)
194
+ return result.returncode