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/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""llmctl — Cross-platform CLI for llama-server router and GGUF models."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
__version__ = version("llmctl-cli")
|
|
9
|
+
except PackageNotFoundError: # pragma: no cover
|
|
10
|
+
__version__ = "0.4.1"
|
|
11
|
+
|
|
12
|
+
__all__ = ["__version__"]
|
llmctl/__main__.py
ADDED
llmctl/bench.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"""Comparative model benchmark (`llmctl bench`) measuring TTFT and tokens/s."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import statistics
|
|
6
|
+
import time
|
|
7
|
+
from dataclasses import asdict, dataclass
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from llmctl.config import AppConfig
|
|
11
|
+
from llmctl.hardware import detect_hardware
|
|
12
|
+
from llmctl.http_client import HttpError, stream_sse_json
|
|
13
|
+
from llmctl.ui import Console
|
|
14
|
+
|
|
15
|
+
DEFAULT_BENCH_PROMPT = (
|
|
16
|
+
"Escribe una función en Python que implemente búsqueda binaria y explica brevemente "
|
|
17
|
+
"su complejidad temporal."
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class BenchResult:
|
|
23
|
+
"""Aggregated benchmark metrics for a single model alias."""
|
|
24
|
+
|
|
25
|
+
alias: str
|
|
26
|
+
ok: bool
|
|
27
|
+
runs: int
|
|
28
|
+
ttft_s: float
|
|
29
|
+
elapsed_s: float
|
|
30
|
+
prompt_tps: float
|
|
31
|
+
gen_tps: float
|
|
32
|
+
tokens_generated: int
|
|
33
|
+
vram_used_gb: float | None = None
|
|
34
|
+
error: str = ""
|
|
35
|
+
|
|
36
|
+
def to_dict(self) -> dict[str, object]:
|
|
37
|
+
return asdict(self)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _run_single_bench(
|
|
41
|
+
alias: str,
|
|
42
|
+
config: AppConfig,
|
|
43
|
+
*,
|
|
44
|
+
prompt: str,
|
|
45
|
+
max_tokens: int,
|
|
46
|
+
) -> tuple[float, float, float, float, int]:
|
|
47
|
+
"""Return (ttft_s, elapsed_s, prompt_tps, gen_tps, generated_tokens)."""
|
|
48
|
+
payload: dict[str, Any] = {
|
|
49
|
+
"model": alias,
|
|
50
|
+
"messages": [{"role": "user", "content": prompt}],
|
|
51
|
+
"max_tokens": max_tokens,
|
|
52
|
+
"temperature": 0.1,
|
|
53
|
+
"stream": True,
|
|
54
|
+
}
|
|
55
|
+
t0 = time.monotonic()
|
|
56
|
+
ttft: float | None = None
|
|
57
|
+
gen_chunks = 0
|
|
58
|
+
prompt_tps = 0.0
|
|
59
|
+
gen_tps = 0.0
|
|
60
|
+
predicted_n = 0
|
|
61
|
+
|
|
62
|
+
for chunk in stream_sse_json(
|
|
63
|
+
config.chat_completions_url,
|
|
64
|
+
payload=payload,
|
|
65
|
+
token=config.api_key,
|
|
66
|
+
timeout=300.0,
|
|
67
|
+
):
|
|
68
|
+
timings = chunk.get("timings")
|
|
69
|
+
if isinstance(timings, dict):
|
|
70
|
+
prompt_tps = float(timings.get("prompt_per_second") or prompt_tps)
|
|
71
|
+
gen_tps = float(timings.get("predicted_per_second") or gen_tps)
|
|
72
|
+
predicted_n = int(timings.get("predicted_n") or predicted_n)
|
|
73
|
+
|
|
74
|
+
choices = chunk.get("choices")
|
|
75
|
+
if isinstance(choices, list) and choices:
|
|
76
|
+
delta = choices[0].get("delta")
|
|
77
|
+
if isinstance(delta, dict) and (delta.get("content") or delta.get("reasoning_content")):
|
|
78
|
+
if ttft is None:
|
|
79
|
+
ttft = time.monotonic() - t0
|
|
80
|
+
gen_chunks += 1
|
|
81
|
+
|
|
82
|
+
elapsed = max(0.001, time.monotonic() - t0)
|
|
83
|
+
final_ttft = elapsed if ttft is None else ttft
|
|
84
|
+
tokens = predicted_n if predicted_n > 0 else gen_chunks
|
|
85
|
+
if gen_tps <= 0 and tokens > 0:
|
|
86
|
+
gen_window = max(0.001, elapsed - final_ttft)
|
|
87
|
+
gen_tps = tokens / gen_window
|
|
88
|
+
return final_ttft, elapsed, prompt_tps, gen_tps, tokens
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def benchmark_alias(
|
|
92
|
+
alias: str,
|
|
93
|
+
config: AppConfig,
|
|
94
|
+
*,
|
|
95
|
+
runs: int = 1,
|
|
96
|
+
max_tokens: int = 128,
|
|
97
|
+
prompt: str = DEFAULT_BENCH_PROMPT,
|
|
98
|
+
) -> BenchResult:
|
|
99
|
+
"""Run *runs* streaming iterations for *alias* and return median metrics."""
|
|
100
|
+
ttfts: list[float] = []
|
|
101
|
+
elapseds: list[float] = []
|
|
102
|
+
prompt_rates: list[float] = []
|
|
103
|
+
gen_rates: list[float] = []
|
|
104
|
+
token_counts: list[int] = []
|
|
105
|
+
|
|
106
|
+
for _ in range(max(1, runs)):
|
|
107
|
+
try:
|
|
108
|
+
ttft, elapsed, p_tps, g_tps, n_tok = _run_single_bench(
|
|
109
|
+
alias, config, prompt=prompt, max_tokens=max_tokens
|
|
110
|
+
)
|
|
111
|
+
except HttpError as exc:
|
|
112
|
+
return BenchResult(
|
|
113
|
+
alias=alias,
|
|
114
|
+
ok=False,
|
|
115
|
+
runs=runs,
|
|
116
|
+
ttft_s=0.0,
|
|
117
|
+
elapsed_s=0.0,
|
|
118
|
+
prompt_tps=0.0,
|
|
119
|
+
gen_tps=0.0,
|
|
120
|
+
tokens_generated=0,
|
|
121
|
+
error=str(exc),
|
|
122
|
+
)
|
|
123
|
+
ttfts.append(ttft)
|
|
124
|
+
elapseds.append(elapsed)
|
|
125
|
+
prompt_rates.append(p_tps)
|
|
126
|
+
gen_rates.append(g_tps)
|
|
127
|
+
token_counts.append(n_tok)
|
|
128
|
+
|
|
129
|
+
hw = detect_hardware(sys_platform=config.sys_platform)
|
|
130
|
+
return BenchResult(
|
|
131
|
+
alias=alias,
|
|
132
|
+
ok=True,
|
|
133
|
+
runs=len(ttfts),
|
|
134
|
+
ttft_s=round(statistics.median(ttfts), 3),
|
|
135
|
+
elapsed_s=round(statistics.median(elapseds), 3),
|
|
136
|
+
prompt_tps=round(statistics.median(prompt_rates), 2),
|
|
137
|
+
gen_tps=round(statistics.median(gen_rates), 2),
|
|
138
|
+
tokens_generated=int(statistics.median(token_counts)),
|
|
139
|
+
vram_used_gb=hw.vram_used_gb,
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def run_benchmark(
|
|
144
|
+
aliases: list[str],
|
|
145
|
+
config: AppConfig,
|
|
146
|
+
console: Console,
|
|
147
|
+
*,
|
|
148
|
+
runs: int = 1,
|
|
149
|
+
max_tokens: int = 128,
|
|
150
|
+
prompt: str = DEFAULT_BENCH_PROMPT,
|
|
151
|
+
) -> int:
|
|
152
|
+
"""Benchmark one or more aliases and print a comparison table or JSON."""
|
|
153
|
+
results: list[BenchResult] = []
|
|
154
|
+
for alias in aliases:
|
|
155
|
+
if not console.json_mode:
|
|
156
|
+
console.info(f"Midendo [{alias}] ({runs} ejecución/es, max_tokens={max_tokens})...")
|
|
157
|
+
results.append(
|
|
158
|
+
benchmark_alias(alias, config, runs=runs, max_tokens=max_tokens, prompt=prompt)
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
all_ok = all(r.ok for r in results)
|
|
162
|
+
if console.json_mode:
|
|
163
|
+
console.emit_json(
|
|
164
|
+
{
|
|
165
|
+
"ok": all_ok,
|
|
166
|
+
"runs": runs,
|
|
167
|
+
"max_tokens": max_tokens,
|
|
168
|
+
"results": [r.to_dict() for r in results],
|
|
169
|
+
}
|
|
170
|
+
)
|
|
171
|
+
return 0 if all_ok else 1
|
|
172
|
+
|
|
173
|
+
console.line("")
|
|
174
|
+
console.header("Comparativa de rendimiento (mediana)")
|
|
175
|
+
rows: list[list[str]] = []
|
|
176
|
+
for r in results:
|
|
177
|
+
if not r.ok:
|
|
178
|
+
rows.append([r.alias, "ERROR", "-", "-", "-", r.error[:40]])
|
|
179
|
+
continue
|
|
180
|
+
vram_str = f"{r.vram_used_gb:.2f} GiB" if r.vram_used_gb is not None else "N/A"
|
|
181
|
+
rows.append(
|
|
182
|
+
[
|
|
183
|
+
r.alias,
|
|
184
|
+
f"{r.ttft_s:.2f}s",
|
|
185
|
+
f"{r.prompt_tps:.1f} tok/s",
|
|
186
|
+
f"{r.gen_tps:.1f} tok/s",
|
|
187
|
+
f"{r.elapsed_s:.2f}s",
|
|
188
|
+
vram_str,
|
|
189
|
+
]
|
|
190
|
+
)
|
|
191
|
+
console.print_table(["ALIAS", "TTFT", "PROMPT", "GEN", "TOTAL", "VRAM"], rows)
|
|
192
|
+
return 0 if all_ok else 1
|
llmctl/cache.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Hugging Face Hub cache inspection, orphan detection, and safe cleanup."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import shutil
|
|
7
|
+
from collections.abc import Iterable
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from llmctl.presets import active_repo_dirnames, repo_cache_dirname
|
|
12
|
+
|
|
13
|
+
GIB = 1024**3
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class CachedModel:
|
|
18
|
+
"""A cached Hugging Face repository folder."""
|
|
19
|
+
|
|
20
|
+
name: str
|
|
21
|
+
path: Path
|
|
22
|
+
size_bytes: int
|
|
23
|
+
|
|
24
|
+
@property
|
|
25
|
+
def size_gb(self) -> float:
|
|
26
|
+
return self.size_bytes / GIB
|
|
27
|
+
|
|
28
|
+
def to_dict(self) -> dict[str, object]:
|
|
29
|
+
return {
|
|
30
|
+
"name": self.name,
|
|
31
|
+
"path": str(self.path),
|
|
32
|
+
"size_bytes": self.size_bytes,
|
|
33
|
+
"size_gb": round(self.size_gb, 3),
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def dir_size_bytes(path: Path) -> int:
|
|
38
|
+
"""Compute total disk size under *path*, ignoring symlinks to avoid double-counting."""
|
|
39
|
+
if not path.exists():
|
|
40
|
+
return 0
|
|
41
|
+
if path.is_file() and not path.is_symlink():
|
|
42
|
+
try:
|
|
43
|
+
return path.stat().st_size
|
|
44
|
+
except OSError:
|
|
45
|
+
return 0
|
|
46
|
+
|
|
47
|
+
total = 0
|
|
48
|
+
for root, _, files in os.walk(path, followlinks=False):
|
|
49
|
+
for filename in files:
|
|
50
|
+
fp = Path(root) / filename
|
|
51
|
+
try:
|
|
52
|
+
if not fp.is_symlink():
|
|
53
|
+
total += fp.stat().st_size
|
|
54
|
+
except OSError:
|
|
55
|
+
continue
|
|
56
|
+
return total
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def list_cached_models(cache_dir: Path) -> list[CachedModel]:
|
|
60
|
+
"""List all `models--*` directories in *cache_dir*."""
|
|
61
|
+
if not cache_dir.is_dir():
|
|
62
|
+
return []
|
|
63
|
+
return [
|
|
64
|
+
CachedModel(name=child.name, path=child, size_bytes=dir_size_bytes(child))
|
|
65
|
+
for child in sorted(cache_dir.iterdir(), key=lambda p: p.name.lower())
|
|
66
|
+
if child.is_dir() and child.name.startswith("models--")
|
|
67
|
+
]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def find_orphan_models(ini_path: Path, cache_dir: Path) -> list[CachedModel]:
|
|
71
|
+
"""Return cached HF model directories not referenced by any preset in *ini_path*."""
|
|
72
|
+
active = active_repo_dirnames(ini_path)
|
|
73
|
+
return [m for m in list_cached_models(cache_dir) if m.name.lower() not in active]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def find_repo_cache_matches(hf_repo: str, cache_dir: Path) -> list[CachedModel]:
|
|
77
|
+
"""Return cached HF model directories matching *hf_repo*."""
|
|
78
|
+
target = repo_cache_dirname(hf_repo)
|
|
79
|
+
if not target:
|
|
80
|
+
return []
|
|
81
|
+
return [m for m in list_cached_models(cache_dir) if m.name.lower() == target]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def is_repo_shared(ini_path: Path, hf_repo: str, *, exclude_alias: str) -> bool:
|
|
85
|
+
"""Return True if another preset besides *exclude_alias* still references *hf_repo*."""
|
|
86
|
+
target = repo_cache_dirname(hf_repo)
|
|
87
|
+
if not target:
|
|
88
|
+
return False
|
|
89
|
+
return target in active_repo_dirnames(ini_path, exclude_alias=exclude_alias)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def delete_cached_models(models: Iterable[CachedModel]) -> int:
|
|
93
|
+
"""Delete each cached model directory and return total freed bytes."""
|
|
94
|
+
freed = 0
|
|
95
|
+
for item in models:
|
|
96
|
+
if item.path.exists():
|
|
97
|
+
shutil.rmtree(item.path)
|
|
98
|
+
freed += item.size_bytes
|
|
99
|
+
return freed
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def format_bytes(num_bytes: int) -> str:
|
|
103
|
+
"""Human-readable byte formatter (B, KiB, MiB, GiB, TiB)."""
|
|
104
|
+
value = float(max(0, num_bytes))
|
|
105
|
+
for unit in ("B", "KiB", "MiB", "GiB", "TiB"):
|
|
106
|
+
if value < 1024.0 or unit == "TiB":
|
|
107
|
+
return f"{value:.2f} {unit}" if unit != "B" else f"{int(value)} B"
|
|
108
|
+
value /= 1024.0
|
|
109
|
+
return f"{num_bytes} B"
|
llmctl/chat.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""Interactive and piped terminal chat client with SSE streaming for llama-server."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import sys
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from llmctl.config import AppConfig
|
|
9
|
+
from llmctl.http_client import HttpError, request_json, stream_sse_json
|
|
10
|
+
from llmctl.ui import Console
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _send_turn(
|
|
14
|
+
alias: str,
|
|
15
|
+
messages: list[dict[str, str]],
|
|
16
|
+
config: AppConfig,
|
|
17
|
+
console: Console,
|
|
18
|
+
*,
|
|
19
|
+
temperature: float = 0.7,
|
|
20
|
+
max_tokens: int | None = None,
|
|
21
|
+
stream: bool = True,
|
|
22
|
+
) -> tuple[str, str] | None:
|
|
23
|
+
"""Send one chat turn and print streaming (or complete) output; return (content, reasoning)."""
|
|
24
|
+
payload: dict[str, Any] = {
|
|
25
|
+
"model": alias,
|
|
26
|
+
"messages": messages,
|
|
27
|
+
"temperature": temperature,
|
|
28
|
+
"stream": stream and (not console.json_mode),
|
|
29
|
+
}
|
|
30
|
+
if max_tokens is not None:
|
|
31
|
+
payload["max_tokens"] = max_tokens
|
|
32
|
+
|
|
33
|
+
if not payload["stream"]:
|
|
34
|
+
try:
|
|
35
|
+
data = request_json(
|
|
36
|
+
config.chat_completions_url,
|
|
37
|
+
method="POST",
|
|
38
|
+
payload=payload,
|
|
39
|
+
token=config.api_key,
|
|
40
|
+
timeout=300.0,
|
|
41
|
+
)
|
|
42
|
+
except HttpError as exc:
|
|
43
|
+
console.error(str(exc))
|
|
44
|
+
return None
|
|
45
|
+
choices = data.get("choices") if isinstance(data, dict) else None
|
|
46
|
+
msg = choices[0].get("message", {}) if isinstance(choices, list) and choices else {}
|
|
47
|
+
content = str(msg.get("content") or "")
|
|
48
|
+
reasoning = str(msg.get("reasoning_content") or "")
|
|
49
|
+
if console.json_mode:
|
|
50
|
+
console.emit_json(
|
|
51
|
+
{
|
|
52
|
+
"model": alias,
|
|
53
|
+
"content": content,
|
|
54
|
+
"reasoning_content": reasoning,
|
|
55
|
+
"timings": data.get("timings", {}) if isinstance(data, dict) else {},
|
|
56
|
+
}
|
|
57
|
+
)
|
|
58
|
+
else:
|
|
59
|
+
if reasoning.strip():
|
|
60
|
+
console.line(console.dim(f"[Thinking]\n{reasoning.strip()}\n"))
|
|
61
|
+
console.line(content)
|
|
62
|
+
return content, reasoning
|
|
63
|
+
|
|
64
|
+
content_parts: list[str] = []
|
|
65
|
+
reasoning_parts: list[str] = []
|
|
66
|
+
in_thinking = False
|
|
67
|
+
try:
|
|
68
|
+
for chunk in stream_sse_json(
|
|
69
|
+
config.chat_completions_url,
|
|
70
|
+
payload=payload,
|
|
71
|
+
token=config.api_key,
|
|
72
|
+
timeout=300.0,
|
|
73
|
+
):
|
|
74
|
+
choices = chunk.get("choices")
|
|
75
|
+
if not isinstance(choices, list) or not choices:
|
|
76
|
+
continue
|
|
77
|
+
delta = choices[0].get("delta")
|
|
78
|
+
if not isinstance(delta, dict):
|
|
79
|
+
continue
|
|
80
|
+
|
|
81
|
+
r_tok = delta.get("reasoning_content")
|
|
82
|
+
if isinstance(r_tok, str) and r_tok:
|
|
83
|
+
if not in_thinking:
|
|
84
|
+
console.stdout.write(console.dim("[Thinking] "))
|
|
85
|
+
in_thinking = True
|
|
86
|
+
reasoning_parts.append(r_tok)
|
|
87
|
+
console.stdout.write(console.dim(r_tok))
|
|
88
|
+
console.stdout.flush()
|
|
89
|
+
|
|
90
|
+
c_tok = delta.get("content")
|
|
91
|
+
if isinstance(c_tok, str) and c_tok:
|
|
92
|
+
if in_thinking:
|
|
93
|
+
console.stdout.write("\n\n")
|
|
94
|
+
in_thinking = False
|
|
95
|
+
content_parts.append(c_tok)
|
|
96
|
+
console.stdout.write(c_tok)
|
|
97
|
+
console.stdout.flush()
|
|
98
|
+
except HttpError as exc:
|
|
99
|
+
console.error(str(exc))
|
|
100
|
+
return None
|
|
101
|
+
except KeyboardInterrupt:
|
|
102
|
+
console.stdout.write("\n")
|
|
103
|
+
console.stdout.flush()
|
|
104
|
+
return "".join(content_parts), "".join(reasoning_parts)
|
|
105
|
+
|
|
106
|
+
console.stdout.write("\n")
|
|
107
|
+
console.stdout.flush()
|
|
108
|
+
return "".join(content_parts), "".join(reasoning_parts)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def run_chat(
|
|
112
|
+
alias: str,
|
|
113
|
+
config: AppConfig,
|
|
114
|
+
console: Console,
|
|
115
|
+
*,
|
|
116
|
+
prompt: str = "",
|
|
117
|
+
system_prompt: str = "",
|
|
118
|
+
temperature: float = 0.7,
|
|
119
|
+
max_tokens: int | None = None,
|
|
120
|
+
stream: bool = True,
|
|
121
|
+
stdin_text: str | None = None,
|
|
122
|
+
) -> int:
|
|
123
|
+
"""Run one-shot (prompt/pipe) or interactive multi-turn chat against *alias*."""
|
|
124
|
+
piped = stdin_text
|
|
125
|
+
if piped is None and not console.is_interactive():
|
|
126
|
+
try:
|
|
127
|
+
piped = sys.stdin.read()
|
|
128
|
+
except OSError:
|
|
129
|
+
piped = ""
|
|
130
|
+
|
|
131
|
+
messages: list[dict[str, str]] = []
|
|
132
|
+
if system_prompt.strip():
|
|
133
|
+
messages.append({"role": "system", "content": system_prompt.strip()})
|
|
134
|
+
|
|
135
|
+
# One-shot mode: prompt argument and/or piped stdin
|
|
136
|
+
if prompt.strip() or (piped is not None and piped.strip()):
|
|
137
|
+
parts: list[str] = []
|
|
138
|
+
if prompt.strip():
|
|
139
|
+
parts.append(prompt.strip())
|
|
140
|
+
if piped and piped.strip():
|
|
141
|
+
parts.append(f"```\n{piped.rstrip()}\n```")
|
|
142
|
+
messages.append({"role": "user", "content": "\n\n".join(parts)})
|
|
143
|
+
result = _send_turn(
|
|
144
|
+
alias,
|
|
145
|
+
messages,
|
|
146
|
+
config,
|
|
147
|
+
console,
|
|
148
|
+
temperature=temperature,
|
|
149
|
+
max_tokens=max_tokens,
|
|
150
|
+
stream=stream,
|
|
151
|
+
)
|
|
152
|
+
return 0 if result is not None else 1
|
|
153
|
+
|
|
154
|
+
if not console.is_interactive():
|
|
155
|
+
console.error("Proporciona un prompt o entrada por pipe cuando no haya TTY.")
|
|
156
|
+
return 1
|
|
157
|
+
|
|
158
|
+
console.header(f"Chat con [{alias}] ({config.api_root})")
|
|
159
|
+
console.info("Comandos: /clear (reiniciar historial), /system <texto>, /exit")
|
|
160
|
+
|
|
161
|
+
while True:
|
|
162
|
+
try:
|
|
163
|
+
user_input = input("\n> ").strip()
|
|
164
|
+
except (EOFError, KeyboardInterrupt):
|
|
165
|
+
console.line("")
|
|
166
|
+
return 0
|
|
167
|
+
|
|
168
|
+
if not user_input:
|
|
169
|
+
continue
|
|
170
|
+
if user_input in {"/exit", "/quit", ":q"}:
|
|
171
|
+
return 0
|
|
172
|
+
if user_input == "/clear":
|
|
173
|
+
messages = [m for m in messages if m["role"] == "system"]
|
|
174
|
+
console.info("Historial limpiado.")
|
|
175
|
+
continue
|
|
176
|
+
if user_input.startswith("/system "):
|
|
177
|
+
new_sys = user_input[len("/system ") :].strip()
|
|
178
|
+
messages = [m for m in messages if m["role"] != "system"]
|
|
179
|
+
if new_sys:
|
|
180
|
+
messages.insert(0, {"role": "system", "content": new_sys})
|
|
181
|
+
console.info("Prompt de sistema actualizado.")
|
|
182
|
+
continue
|
|
183
|
+
|
|
184
|
+
messages.append({"role": "user", "content": user_input})
|
|
185
|
+
result = _send_turn(
|
|
186
|
+
alias,
|
|
187
|
+
messages,
|
|
188
|
+
config,
|
|
189
|
+
console,
|
|
190
|
+
temperature=temperature,
|
|
191
|
+
max_tokens=max_tokens,
|
|
192
|
+
stream=stream,
|
|
193
|
+
)
|
|
194
|
+
if result is None:
|
|
195
|
+
messages.pop()
|
|
196
|
+
continue
|
|
197
|
+
content, _ = result
|
|
198
|
+
if content:
|
|
199
|
+
messages.append({"role": "assistant", "content": content})
|