crispllm 1.1.0__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.
- crispllm/__init__.py +9 -0
- crispllm/cli.py +588 -0
- crispllm/config.py +629 -0
- crispllm/memory/__init__.py +21 -0
- crispllm/memory/consolidator.py +452 -0
- crispllm/memory/extractor.py +321 -0
- crispllm/memory/store.py +775 -0
- crispllm/privacy/__init__.py +23 -0
- crispllm/privacy/redactor.py +351 -0
- crispllm/privacy/stream_restorer.py +83 -0
- crispllm/proxy/__init__.py +0 -0
- crispllm/proxy/app.py +1166 -0
- crispllm/proxy/auth.py +122 -0
- crispllm/proxy/budgeter.py +164 -0
- crispllm/proxy/classifier.py +128 -0
- crispllm/proxy/mcp_server.py +413 -0
- crispllm/proxy/middleware.py +570 -0
- crispllm/proxy/router.py +237 -0
- crispllm/proxy/speculative.py +489 -0
- crispllm/proxy/streaming.py +236 -0
- crispllm/proxy/sysinfo.py +250 -0
- crispllm/proxy/telemetry.py +323 -0
- crispllm/proxy/unloader.py +114 -0
- crispllm/proxy/watchdog.py +105 -0
- crispllm/slicer/__init__.py +34 -0
- crispllm/slicer/cache.py +579 -0
- crispllm/slicer/pagerank.py +294 -0
- crispllm/slicer/repomap.py +778 -0
- crispllm/slicer/symbols.py +419 -0
- crispllm/slicer/tags.py +431 -0
- crispllm-1.1.0.dist-info/METADATA +317 -0
- crispllm-1.1.0.dist-info/RECORD +34 -0
- crispllm-1.1.0.dist-info/WHEEL +4 -0
- crispllm-1.1.0.dist-info/entry_points.txt +3 -0
crispllm/__init__.py
ADDED
crispllm/cli.py
ADDED
|
@@ -0,0 +1,588 @@
|
|
|
1
|
+
"""CrispLLM CLI - console entrypoint.
|
|
2
|
+
|
|
3
|
+
Supports: crispllm serve, crispllm init, crispllm status, crispllm stats, crispllm slice, crispllm memory, crispllm unload, crispllm doctor.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import sys
|
|
10
|
+
import time
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
import click
|
|
14
|
+
|
|
15
|
+
from crispllm import __version__
|
|
16
|
+
from crispllm.config import CrispLLMConfig, CrispLLMConfig, default_toml_content, load_config
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@click.group()
|
|
20
|
+
@click.version_option(__version__, "--version", "-v", package_name="crispllm")
|
|
21
|
+
def cli() -> None:
|
|
22
|
+
"""CrispLLM - Lightweight unified memory & context proxy."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@cli.command()
|
|
26
|
+
@click.option("--host", default=None, help="Bind host (overrides config).")
|
|
27
|
+
@click.option("--port", default=None, type=int, help="Bind port (overrides config).")
|
|
28
|
+
@click.option("--config", "config_path", default=None, type=click.Path(exists=True, path_type=Path))
|
|
29
|
+
def serve(host: str | None, port: int | None, config_path: Path | None) -> None:
|
|
30
|
+
"""Start the CrispLLM proxy server."""
|
|
31
|
+
cfg = load_config(config_path)
|
|
32
|
+
if host is not None:
|
|
33
|
+
cfg.host = host
|
|
34
|
+
if port is not None:
|
|
35
|
+
cfg.port = port
|
|
36
|
+
|
|
37
|
+
import uvicorn
|
|
38
|
+
|
|
39
|
+
from crispllm.proxy.app import create_app
|
|
40
|
+
|
|
41
|
+
app = create_app(cfg)
|
|
42
|
+
click.echo(f"CrispLLM proxy -> {cfg.upstream_base_url} (model: {cfg.model})")
|
|
43
|
+
click.echo(f"Listening on http://{cfg.host}:{cfg.port}")
|
|
44
|
+
click.echo(f"MCP endpoint: http://{cfg.host}:{cfg.port}/mcp")
|
|
45
|
+
uvicorn.run(app, host=cfg.host, port=cfg.port, log_level="info")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@cli.command()
|
|
49
|
+
@click.option(
|
|
50
|
+
"--preset",
|
|
51
|
+
type=click.Choice(["hybrid", "local", "nvidia", "gemini"], case_sensitive=False),
|
|
52
|
+
default="hybrid",
|
|
53
|
+
show_default=True,
|
|
54
|
+
help="Configuration preset (hybrid, local, nvidia, gemini).",
|
|
55
|
+
)
|
|
56
|
+
@click.option(
|
|
57
|
+
"--output",
|
|
58
|
+
"-o",
|
|
59
|
+
"--path",
|
|
60
|
+
"output",
|
|
61
|
+
default=Path("crispllm.toml"),
|
|
62
|
+
type=click.Path(path_type=Path),
|
|
63
|
+
show_default=True,
|
|
64
|
+
help="Output configuration file path.",
|
|
65
|
+
)
|
|
66
|
+
@click.option(
|
|
67
|
+
"--force",
|
|
68
|
+
"-f",
|
|
69
|
+
is_flag=True,
|
|
70
|
+
default=False,
|
|
71
|
+
help="Overwrite existing configuration file.",
|
|
72
|
+
)
|
|
73
|
+
def init(preset: str, output: Path, force: bool) -> None:
|
|
74
|
+
"""Generate an crispllm.toml configuration file."""
|
|
75
|
+
if output.exists() and not force:
|
|
76
|
+
click.echo(
|
|
77
|
+
f"Config file already exists at {output}. Use --force to overwrite.",
|
|
78
|
+
err=True,
|
|
79
|
+
)
|
|
80
|
+
sys.exit(1)
|
|
81
|
+
|
|
82
|
+
content = default_toml_content(preset)
|
|
83
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
84
|
+
output.write_text(content, encoding="utf-8", newline="\n")
|
|
85
|
+
click.echo(f"Created {output} (preset: {preset})")
|
|
86
|
+
click.echo("Start CrispLLM with:")
|
|
87
|
+
preset_lower = preset.lower()
|
|
88
|
+
env_set = "$env:" if sys.platform == "win32" else "export "
|
|
89
|
+
if preset_lower == "nvidia":
|
|
90
|
+
click.echo(f' {env_set}NVIDIA_API_KEY="<your-key>"')
|
|
91
|
+
elif preset_lower == "gemini":
|
|
92
|
+
click.echo(f' {env_set}GEMINI_API_KEY="<your-key>"')
|
|
93
|
+
elif preset_lower == "hybrid":
|
|
94
|
+
click.echo(f' {env_set}NVIDIA_API_KEY="<your-key>" (optional for cloud fallback)')
|
|
95
|
+
click.echo(" crispllm serve")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@cli.command()
|
|
99
|
+
@click.option(
|
|
100
|
+
"--days",
|
|
101
|
+
default=None,
|
|
102
|
+
type=int,
|
|
103
|
+
help="Filter telemetry events to the past N days.",
|
|
104
|
+
)
|
|
105
|
+
@click.option(
|
|
106
|
+
"--json",
|
|
107
|
+
"as_json",
|
|
108
|
+
is_flag=True,
|
|
109
|
+
default=False,
|
|
110
|
+
help="Output telemetry summary as formatted JSON.",
|
|
111
|
+
)
|
|
112
|
+
@click.option(
|
|
113
|
+
"--reset",
|
|
114
|
+
is_flag=True,
|
|
115
|
+
default=False,
|
|
116
|
+
help="Reset recorded request telemetry.",
|
|
117
|
+
)
|
|
118
|
+
@click.option(
|
|
119
|
+
"--config",
|
|
120
|
+
"config_path",
|
|
121
|
+
default=None,
|
|
122
|
+
type=click.Path(exists=True, path_type=Path),
|
|
123
|
+
help="Path to crispllm.toml configuration file.",
|
|
124
|
+
)
|
|
125
|
+
def stats(
|
|
126
|
+
days: int | None,
|
|
127
|
+
as_json: bool,
|
|
128
|
+
reset: bool,
|
|
129
|
+
config_path: Path | None,
|
|
130
|
+
) -> None:
|
|
131
|
+
"""Show or reset persistent request telemetry."""
|
|
132
|
+
cfg = load_config(config_path)
|
|
133
|
+
from crispllm.proxy.telemetry import TelemetryStore
|
|
134
|
+
|
|
135
|
+
with TelemetryStore(cfg.memory.db_path) as store:
|
|
136
|
+
if reset:
|
|
137
|
+
count = store.reset()
|
|
138
|
+
click.echo(f"Cleared {count} telemetry events.")
|
|
139
|
+
return
|
|
140
|
+
|
|
141
|
+
summary = store.summary(days=days)
|
|
142
|
+
|
|
143
|
+
if as_json:
|
|
144
|
+
click.echo(json.dumps(summary, indent=2))
|
|
145
|
+
return
|
|
146
|
+
|
|
147
|
+
window_str = f"past {days} days" if days is not None else "all time"
|
|
148
|
+
click.echo(f"CrispLLM Telemetry Summary ({window_str})")
|
|
149
|
+
click.echo("=" * 44)
|
|
150
|
+
click.echo("Requests:")
|
|
151
|
+
click.echo(f" Total: {summary['total_requests']}")
|
|
152
|
+
click.echo(f" Local: {summary['local_requests']}")
|
|
153
|
+
click.echo(f" Cloud: {summary['cloud_requests']}")
|
|
154
|
+
click.echo(f" Local Offload: {summary['local_offload_pct']:.2f}%")
|
|
155
|
+
click.echo(f" Fallbacks: {summary['fallback_escalations']}")
|
|
156
|
+
click.echo("")
|
|
157
|
+
click.echo("Context Savings:")
|
|
158
|
+
click.echo(f" Raw Tokens: {summary['total_tokens_raw']:,}")
|
|
159
|
+
click.echo(f" Sent Tokens: {summary['total_tokens_sent']:,}")
|
|
160
|
+
click.echo(f" Saved Tokens: {summary['total_tokens_saved']:,}")
|
|
161
|
+
click.echo(f" Token Reduction: {summary['token_reduction_pct']:.2f}%")
|
|
162
|
+
click.echo(f" Compacted Turns: {summary['total_compacted_turns']}")
|
|
163
|
+
click.echo("")
|
|
164
|
+
click.echo("Privacy:")
|
|
165
|
+
click.echo(f" Secrets Redacted: {summary['total_secrets_redacted']}")
|
|
166
|
+
click.echo("")
|
|
167
|
+
click.echo("Latency:")
|
|
168
|
+
click.echo(f" Mean Latency: {summary['mean_latency_ms']:.2f} ms")
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
@cli.command()
|
|
172
|
+
@click.option("--config", "config_path", default=None, type=click.Path(exists=True, path_type=Path))
|
|
173
|
+
def status(config_path: Path | None) -> None:
|
|
174
|
+
"""Show CrispLLM proxy status."""
|
|
175
|
+
cfg = load_config(config_path)
|
|
176
|
+
|
|
177
|
+
import httpx
|
|
178
|
+
|
|
179
|
+
url = f"http://{cfg.host}:{cfg.port}/health"
|
|
180
|
+
try:
|
|
181
|
+
resp = httpx.get(url, timeout=3.0)
|
|
182
|
+
data = resp.json()
|
|
183
|
+
click.echo(f"Status: {data.get('status', 'unknown')}")
|
|
184
|
+
click.echo(f"Upstream: {data.get('upstream_base_url', 'N/A')}")
|
|
185
|
+
click.echo(f"Model: {data.get('model', 'N/A')}")
|
|
186
|
+
click.echo(f"RSS: {data.get('rss_mb', 'N/A')} MB")
|
|
187
|
+
memory_enabled = data.get("memory_enabled", False)
|
|
188
|
+
facts_count = data.get("facts_count", 0)
|
|
189
|
+
click.echo(f"Memory: {'enabled' if memory_enabled else 'disabled'} ({facts_count} facts)")
|
|
190
|
+
privacy_enabled = data.get("privacy_enabled", False)
|
|
191
|
+
secrets_redacted = data.get("secrets_redacted_total", 0)
|
|
192
|
+
click.echo(f"Privacy: {'enabled' if privacy_enabled else 'disabled'} ({secrets_redacted} redacted)")
|
|
193
|
+
auth_enabled = data.get("auth_enabled", False)
|
|
194
|
+
click.echo(f"Auth: {'enabled' if auth_enabled else 'disabled (localhost only)'}")
|
|
195
|
+
local_reqs = data.get("local_requests", 0)
|
|
196
|
+
cloud_reqs = data.get("cloud_requests", 0)
|
|
197
|
+
fallbacks = data.get("fallback_escalations", 0)
|
|
198
|
+
click.echo(f"Routing: local={local_reqs}, cloud={cloud_reqs}, fallbacks={fallbacks}")
|
|
199
|
+
if "system_memory" in data and isinstance(data["system_memory"], dict):
|
|
200
|
+
sm = data["system_memory"]
|
|
201
|
+
avail = sm.get("available_mb")
|
|
202
|
+
total = sm.get("total_mb")
|
|
203
|
+
pressure = sm.get("pressure", "unknown")
|
|
204
|
+
if avail is not None and total is not None:
|
|
205
|
+
click.echo(f"System RAM: {avail:.1f} MB free / {total:.1f} MB ({pressure})")
|
|
206
|
+
else:
|
|
207
|
+
click.echo(f"System RAM: pressure={pressure}")
|
|
208
|
+
if "resources" in data and isinstance(data["resources"], dict):
|
|
209
|
+
res = data["resources"]
|
|
210
|
+
backend = res.get("local_backend", "auto")
|
|
211
|
+
max_c = res.get("effective_max_ctx", "N/A")
|
|
212
|
+
esc_t = res.get("effective_escalate_tokens", "N/A")
|
|
213
|
+
click.echo(f"Context Budget: backend={backend}, max_ctx={max_c}, escalate_at={esc_t} tok")
|
|
214
|
+
if "task_tiers" in data and isinstance(data["task_tiers"], dict):
|
|
215
|
+
tt = data["task_tiers"]
|
|
216
|
+
click.echo(f"Task Tiers: fast={tt.get('fast', 0)}, balanced={tt.get('balanced', 0)}, deep={tt.get('deep', 0)}")
|
|
217
|
+
if "prefix_cache" in data and isinstance(data["prefix_cache"], dict):
|
|
218
|
+
pc = data["prefix_cache"]
|
|
219
|
+
click.echo(f"Prefix Cache: hits={pc.get('hits', 0)}, misses={pc.get('misses', 0)}, hit_rate={pc.get('hit_rate_pct', 0.0):.1f}%")
|
|
220
|
+
if "speculative" in data and isinstance(data["speculative"], dict):
|
|
221
|
+
sp = data["speculative"]
|
|
222
|
+
c_inj = sp.get("cloud_injected", 0)
|
|
223
|
+
c_ret = sp.get("cloud_fallback_retries", 0)
|
|
224
|
+
c_acc = sp.get("cloud_accepted_tokens", 0)
|
|
225
|
+
c_tot = c_acc + sp.get("cloud_rejected_tokens", 0)
|
|
226
|
+
c_pct = sp.get("cloud_acceptance_pct")
|
|
227
|
+
pct_str = f"{c_pct:.1f}%" if c_pct is not None else "N/A"
|
|
228
|
+
click.echo(f"Speculative: cloud_injected={c_inj}, retries={c_ret}, accepted={c_acc}/{c_tot} ({pct_str})")
|
|
229
|
+
except httpx.ConnectError:
|
|
230
|
+
click.echo(f"CrispLLM not running at {url}", err=True)
|
|
231
|
+
sys.exit(1)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
@cli.command()
|
|
235
|
+
@click.option("--model", default=None, help="Model name to unload (defaults to configured model).")
|
|
236
|
+
@click.option("--config", "config_path", default=None, type=click.Path(exists=True, path_type=Path), help="Path to crispllm.toml configuration file.")
|
|
237
|
+
def unload(model: str | None, config_path: Path | None) -> None:
|
|
238
|
+
"""Manually unload idle local model weights to free RAM/VRAM."""
|
|
239
|
+
cfg = load_config(config_path)
|
|
240
|
+
target_model = model or cfg.model
|
|
241
|
+
backend = cfg.resources.local_backend
|
|
242
|
+
if backend == "auto":
|
|
243
|
+
from crispllm.proxy.budgeter import detect_local_backend
|
|
244
|
+
|
|
245
|
+
backend = detect_local_backend(cfg.upstream_base_url, cfg.resources.local_backend)
|
|
246
|
+
|
|
247
|
+
if backend != "ollama":
|
|
248
|
+
click.echo(f"Idle unload only supported for Ollama backends (detected: {backend}).")
|
|
249
|
+
return
|
|
250
|
+
|
|
251
|
+
import httpx
|
|
252
|
+
from crispllm.proxy.unloader import get_ollama_generate_url
|
|
253
|
+
|
|
254
|
+
url = get_ollama_generate_url(cfg.upstream_base_url)
|
|
255
|
+
try:
|
|
256
|
+
resp = httpx.post(url, json={"model": target_model, "keep_alive": 0}, timeout=5.0)
|
|
257
|
+
if resp.status_code == 200:
|
|
258
|
+
click.echo(f"Unloaded model '{target_model}' via Ollama API ({url}).")
|
|
259
|
+
else:
|
|
260
|
+
click.echo(f"Failed to unload '{target_model}': HTTP {resp.status_code}", err=True)
|
|
261
|
+
sys.exit(1)
|
|
262
|
+
except httpx.ConnectError:
|
|
263
|
+
click.echo(f"Ollama server not reachable at {url}", err=True)
|
|
264
|
+
sys.exit(1)
|
|
265
|
+
except Exception as exc:
|
|
266
|
+
click.echo(f"Unload error: {exc}", err=True)
|
|
267
|
+
sys.exit(1)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
@cli.command()
|
|
271
|
+
@click.argument("path", type=click.Path(exists=True, file_okay=False, path_type=Path))
|
|
272
|
+
@click.option("--tokens", default=1024, show_default=True,
|
|
273
|
+
help="Maximum tokens in the output repo map.")
|
|
274
|
+
@click.option("--query", default="", show_default=False,
|
|
275
|
+
help="Natural language query to boost relevant definitions.")
|
|
276
|
+
@click.option("--focus", "focus_files", multiple=True, metavar="FILE",
|
|
277
|
+
help="Relative paths to focus files (may be repeated).")
|
|
278
|
+
@click.option("--symbol", default=None,
|
|
279
|
+
help="Target symbol name or qualified name for 1-hop AST call-graph slice.")
|
|
280
|
+
@click.option("--model", default="cl100k_base", show_default=True,
|
|
281
|
+
help="tiktoken encoding for token counting.")
|
|
282
|
+
def slice(
|
|
283
|
+
path: Path,
|
|
284
|
+
tokens: int,
|
|
285
|
+
query: str,
|
|
286
|
+
focus_files: tuple[str, ...],
|
|
287
|
+
symbol: str | None,
|
|
288
|
+
model: str,
|
|
289
|
+
) -> None:
|
|
290
|
+
"""Slice a repository into a compact, ranked AST repo map.
|
|
291
|
+
|
|
292
|
+
PATH Root of the repository (or sub-directory) to slice.
|
|
293
|
+
|
|
294
|
+
Prints the repo map to stdout.
|
|
295
|
+
Prints token counts, compression %, and latency to stderr.
|
|
296
|
+
|
|
297
|
+
Example:
|
|
298
|
+
crispllm slice . --tokens 2048 --query "authentication" --focus src/auth.py
|
|
299
|
+
"""
|
|
300
|
+
from crispllm.slicer.repomap import RepoMap, count_tokens
|
|
301
|
+
|
|
302
|
+
t0 = time.perf_counter()
|
|
303
|
+
|
|
304
|
+
rm = RepoMap(repo_path=path, max_tokens=tokens, model_name=model)
|
|
305
|
+
try:
|
|
306
|
+
if symbol:
|
|
307
|
+
res = rm.slice_symbol(symbol=symbol, token_budget=tokens)
|
|
308
|
+
elapsed_ms = (time.perf_counter() - t0) * 1000
|
|
309
|
+
click.echo(res.content)
|
|
310
|
+
click.echo(
|
|
311
|
+
f"\n[CrispLLM slice-symbol] symbol='{symbol}' found={res.found} "
|
|
312
|
+
f"file={res.target_file} callees={res.callee_count} callers={res.caller_count} "
|
|
313
|
+
f"sliced={res.sliced_tokens:,} tok raw={res.raw_tokens:,} tok fallback={res.fallback_used} "
|
|
314
|
+
f"latency={elapsed_ms:.0f}ms",
|
|
315
|
+
err=True,
|
|
316
|
+
)
|
|
317
|
+
return
|
|
318
|
+
|
|
319
|
+
raw_tokens = rm.raw_token_count()
|
|
320
|
+
repo_map = rm.get_repo_map(
|
|
321
|
+
focus_files=list(focus_files) or None,
|
|
322
|
+
mentioned_symbols=None,
|
|
323
|
+
query=query,
|
|
324
|
+
)
|
|
325
|
+
finally:
|
|
326
|
+
rm.close()
|
|
327
|
+
|
|
328
|
+
elapsed_ms = (time.perf_counter() - t0) * 1000
|
|
329
|
+
sliced_tokens = count_tokens(repo_map, model)
|
|
330
|
+
compression_pct = (
|
|
331
|
+
(raw_tokens - sliced_tokens) / raw_tokens * 100.0
|
|
332
|
+
if raw_tokens > 0 else 0.0
|
|
333
|
+
)
|
|
334
|
+
|
|
335
|
+
click.echo(repo_map, nl=False)
|
|
336
|
+
|
|
337
|
+
click.echo(
|
|
338
|
+
f"\n[CrispLLM slice] raw={raw_tokens:,} tok sliced={sliced_tokens:,} tok "
|
|
339
|
+
f"compression={compression_pct:.1f}% latency={elapsed_ms:.0f}ms",
|
|
340
|
+
err=True,
|
|
341
|
+
)
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
@cli.group()
|
|
345
|
+
def memory() -> None:
|
|
346
|
+
"""Manage CrispLLM SQLite tiered memory store."""
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
@memory.command("list")
|
|
350
|
+
@click.option("--kind", default=None, help="Filter facts by kind (constraint, constant, signature, note).")
|
|
351
|
+
@click.option("--tier", default=None, type=click.Choice(["core", "episodic", "archival"], case_sensitive=False), help="Filter facts by tier.")
|
|
352
|
+
@click.option("--include-superseded", is_flag=True, default=False, help="Include superseded facts.")
|
|
353
|
+
@click.option("--limit", default=50, type=int, help="Max facts to return.")
|
|
354
|
+
@click.option("--config", "config_path", default=None, type=click.Path(exists=True, path_type=Path))
|
|
355
|
+
def memory_list(
|
|
356
|
+
kind: str | None,
|
|
357
|
+
tier: str | None,
|
|
358
|
+
include_superseded: bool,
|
|
359
|
+
limit: int,
|
|
360
|
+
config_path: Path | None,
|
|
361
|
+
) -> None:
|
|
362
|
+
"""List stored facts in CrispLLM memory."""
|
|
363
|
+
from crispllm.memory.store import MemoryStore
|
|
364
|
+
|
|
365
|
+
cfg = load_config(config_path)
|
|
366
|
+
with MemoryStore(cfg.memory.db_path) as store:
|
|
367
|
+
facts = store.list_facts(
|
|
368
|
+
kind=kind,
|
|
369
|
+
tier=tier.lower() if tier else None,
|
|
370
|
+
include_archival=True if (tier and tier.lower() == "archival") else False,
|
|
371
|
+
include_superseded=include_superseded,
|
|
372
|
+
limit=limit,
|
|
373
|
+
)
|
|
374
|
+
if not facts:
|
|
375
|
+
click.echo("No facts stored.")
|
|
376
|
+
return
|
|
377
|
+
|
|
378
|
+
click.echo(f"Stored facts ({len(facts)}):")
|
|
379
|
+
for f in facts:
|
|
380
|
+
pin_badge = "[PINNED] " if f.pinned else ""
|
|
381
|
+
click.echo(f" #{f.id} [{f.kind}] [{f.tier}/{f.status}] {pin_badge}{f.key} = {f.value}")
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
@memory.command("search")
|
|
385
|
+
@click.argument("query")
|
|
386
|
+
@click.option("--all", "all_facts", is_flag=True, default=False, help="Include archival and superseded facts.")
|
|
387
|
+
@click.option("--limit", default=10, type=int, help="Max results.")
|
|
388
|
+
@click.option("--config", "config_path", default=None, type=click.Path(exists=True, path_type=Path))
|
|
389
|
+
def memory_search(query: str, all_facts: bool, limit: int, config_path: Path | None) -> None:
|
|
390
|
+
"""Search CrispLLM memory using BM25 FTS5 ranking."""
|
|
391
|
+
from crispllm.memory.store import MemoryStore
|
|
392
|
+
|
|
393
|
+
cfg = load_config(config_path)
|
|
394
|
+
with MemoryStore(cfg.memory.db_path) as store:
|
|
395
|
+
facts = store.search_facts(
|
|
396
|
+
query,
|
|
397
|
+
include_archival=all_facts,
|
|
398
|
+
include_superseded=all_facts,
|
|
399
|
+
limit=limit,
|
|
400
|
+
)
|
|
401
|
+
if not facts:
|
|
402
|
+
click.echo("No matches found.")
|
|
403
|
+
return
|
|
404
|
+
|
|
405
|
+
click.echo(f"Search results for '{query}' ({len(facts)}):")
|
|
406
|
+
for f in facts:
|
|
407
|
+
pin_badge = "[PINNED] " if f.pinned else ""
|
|
408
|
+
click.echo(f" #{f.id} [{f.kind}] [{f.tier}/{f.status}] {pin_badge}{f.key} = {f.value}")
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
@memory.command("consolidate")
|
|
412
|
+
@click.option("--dry-run", is_flag=True, default=False, help="Calculate consolidation changes without applying them.")
|
|
413
|
+
@click.option("--config", "config_path", default=None, type=click.Path(exists=True, path_type=Path))
|
|
414
|
+
def memory_consolidate(dry_run: bool, config_path: Path | None) -> None:
|
|
415
|
+
"""Run an immediate memory consolidation sweep."""
|
|
416
|
+
from crispllm.memory.consolidator import MemoryConsolidator
|
|
417
|
+
from crispllm.memory.store import MemoryStore
|
|
418
|
+
|
|
419
|
+
cfg = load_config(config_path)
|
|
420
|
+
with MemoryStore(cfg.memory.db_path) as store:
|
|
421
|
+
consolidator = MemoryConsolidator(store=store, config=cfg)
|
|
422
|
+
report = consolidator.consolidate_once(dry_run=dry_run)
|
|
423
|
+
prefix = "[DRY-RUN] " if report.dry_run else ""
|
|
424
|
+
click.echo(f"{prefix}Consolidation complete (mode: {report.mode}):")
|
|
425
|
+
click.echo(f" Merged: {report.merged}")
|
|
426
|
+
click.echo(f" Superseded: {report.superseded}")
|
|
427
|
+
click.echo(f" Promoted: {report.promoted}")
|
|
428
|
+
click.echo(f" Demoted: {report.demoted}")
|
|
429
|
+
click.echo(f" Created: {report.created}")
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
@memory.command("history")
|
|
433
|
+
@click.argument("key")
|
|
434
|
+
@click.option("--session", default=None, help="Filter by session ID.")
|
|
435
|
+
@click.option("--config", "config_path", default=None, type=click.Path(exists=True, path_type=Path))
|
|
436
|
+
def memory_history(key: str, session: str | None, config_path: Path | None) -> None:
|
|
437
|
+
"""Display the versioned supersession timeline of a memory key."""
|
|
438
|
+
from crispllm.memory.store import MemoryStore
|
|
439
|
+
|
|
440
|
+
cfg = load_config(config_path)
|
|
441
|
+
with MemoryStore(cfg.memory.db_path) as store:
|
|
442
|
+
history = store.get_fact_history(key, session_id=session)
|
|
443
|
+
if not history:
|
|
444
|
+
click.echo(f"No history found for '{key}'.")
|
|
445
|
+
return
|
|
446
|
+
|
|
447
|
+
click.echo(f"History for '{key}' ({len(history)} versions):")
|
|
448
|
+
for f in history:
|
|
449
|
+
superseded_info = f" (superseded_by: #{f.superseded_by})" if f.superseded_by else ""
|
|
450
|
+
click.echo(f" #{f.id} [{f.kind}] [{f.tier}/{f.status}] {f.key} = {f.value}{superseded_info}")
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
@memory.command("clear")
|
|
454
|
+
@click.option("--session", default=None, help="Clear facts for a specific session ID only.")
|
|
455
|
+
@click.option("--config", "config_path", default=None, type=click.Path(exists=True, path_type=Path))
|
|
456
|
+
def memory_clear(session: str | None, config_path: Path | None) -> None:
|
|
457
|
+
"""Clear facts from CrispLLM memory."""
|
|
458
|
+
from crispllm.memory.store import MemoryStore
|
|
459
|
+
|
|
460
|
+
cfg = load_config(config_path)
|
|
461
|
+
with MemoryStore(cfg.memory.db_path) as store:
|
|
462
|
+
if session:
|
|
463
|
+
count = store.clear_session(session)
|
|
464
|
+
click.echo(f"Cleared {count} facts for session '{session}'.")
|
|
465
|
+
else:
|
|
466
|
+
count = store.clear_all()
|
|
467
|
+
click.echo(f"Cleared all {count} facts from memory.")
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
@cli.command("llama-cmd")
|
|
471
|
+
@click.option("--model", default=None, help="Main GGUF model path.")
|
|
472
|
+
@click.option("--draft-model", default=None, help="Draft GGUF model path.")
|
|
473
|
+
@click.option("--mode", default=None, help="Speculative preset mode (ngram-simple, ngram-mod, draft, hybrid, none).")
|
|
474
|
+
@click.option("--profile", default="auto", help="Hardware profile (auto, t1-cpu, t2-gpu, t2-arc, t3-rtx).")
|
|
475
|
+
@click.option("--binary", default=None, help="Path to llama-server binary.")
|
|
476
|
+
@click.option("--device", default=None, help="Target device (cpu, vulkan, cuda, mps).")
|
|
477
|
+
@click.option("--ctx-size", default=None, type=int, help="Main model context window (default: profile cap).")
|
|
478
|
+
@click.option("--port", default=8081, type=int, help="Listen port (default: 8081).")
|
|
479
|
+
@click.option("--config", "config_path", default=None, type=click.Path(exists=True, path_type=Path), help="Path to crispllm.toml configuration file.")
|
|
480
|
+
def llama_cmd(
|
|
481
|
+
model: str | None,
|
|
482
|
+
draft_model: str | None,
|
|
483
|
+
mode: str | None,
|
|
484
|
+
profile: str,
|
|
485
|
+
binary: str | None,
|
|
486
|
+
device: str | None,
|
|
487
|
+
ctx_size: int | None,
|
|
488
|
+
port: int,
|
|
489
|
+
config_path: Path | None,
|
|
490
|
+
) -> None:
|
|
491
|
+
"""Generate ready-to-run llama-server command with speculative decoding presets."""
|
|
492
|
+
from crispllm.proxy.speculative import build_llama_server_command
|
|
493
|
+
from crispllm.proxy.watchdog import RamPressureWatchdog
|
|
494
|
+
|
|
495
|
+
cfg = load_config(config_path)
|
|
496
|
+
model_path = model or cfg.model
|
|
497
|
+
spec_mode = mode or cfg.speculative.local_mode
|
|
498
|
+
draft_path = draft_model or cfg.speculative.draft_model_path
|
|
499
|
+
watchdog = RamPressureWatchdog(cfg.resources)
|
|
500
|
+
|
|
501
|
+
preset = build_llama_server_command(
|
|
502
|
+
model_path=model_path,
|
|
503
|
+
draft_model_path=draft_path,
|
|
504
|
+
mode=spec_mode,
|
|
505
|
+
profile=profile,
|
|
506
|
+
binary=binary,
|
|
507
|
+
device=device,
|
|
508
|
+
ctx_size=ctx_size,
|
|
509
|
+
port=port,
|
|
510
|
+
config=cfg.speculative,
|
|
511
|
+
watchdog=watchdog,
|
|
512
|
+
max_ctx_cap=cfg.resources.max_local_ctx,
|
|
513
|
+
)
|
|
514
|
+
|
|
515
|
+
cmd_str = preset.render_shell_command()
|
|
516
|
+
click.echo("llama-server Speculative Configuration:")
|
|
517
|
+
click.echo(f" Profile: {preset.profile}")
|
|
518
|
+
click.echo(f" Mode: {preset.effective_mode}")
|
|
519
|
+
click.echo(f" Extra RAM: {preset.estimated_extra_ram_mb} MB")
|
|
520
|
+
if preset.downgrade_reason:
|
|
521
|
+
click.echo(f" Downgrade: {preset.downgrade_reason}")
|
|
522
|
+
click.echo("")
|
|
523
|
+
click.echo("Command:")
|
|
524
|
+
click.echo(f" {cmd_str}")
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
@cli.command("doctor")
|
|
528
|
+
@click.option("--config", "config_path", default=None, type=click.Path(path_type=Path), help="Path to crispllm.toml configuration file.")
|
|
529
|
+
def doctor(config_path: Path | None) -> None:
|
|
530
|
+
"""Check system environment, Tree-sitter parsers, SQLite FTS5 support, and hardware specs."""
|
|
531
|
+
import platform
|
|
532
|
+
import sqlite3
|
|
533
|
+
|
|
534
|
+
from crispllm.proxy.sysinfo import get_process_rss_mb, get_system_memory_info
|
|
535
|
+
|
|
536
|
+
click.echo(f"CrispLLM Doctor v{__version__}")
|
|
537
|
+
click.echo("=" * 40)
|
|
538
|
+
|
|
539
|
+
py_ver = sys.version.split()[0]
|
|
540
|
+
os_info = f"{platform.system()} {platform.release()} ({platform.machine()})"
|
|
541
|
+
click.echo(f"[OK] Python {py_ver} ({sys.executable})")
|
|
542
|
+
click.echo(f"[OK] OS: {os_info}")
|
|
543
|
+
|
|
544
|
+
mem = get_system_memory_info()
|
|
545
|
+
if mem:
|
|
546
|
+
click.echo(f"[OK] System RAM: {mem.available_mb:.0f} MB available / {mem.total_mb:.0f} MB total ({mem.used_percent:.1f}% used) [{mem.source}]")
|
|
547
|
+
else:
|
|
548
|
+
click.echo("[WARN] System RAM: Unable to determine memory metrics")
|
|
549
|
+
|
|
550
|
+
rss = get_process_rss_mb()
|
|
551
|
+
click.echo(f"[OK] Process RSS: {rss:.1f} MB")
|
|
552
|
+
|
|
553
|
+
try:
|
|
554
|
+
con = sqlite3.connect(":memory:")
|
|
555
|
+
con.execute("CREATE VIRTUAL TABLE _test_fts USING fts5(content);")
|
|
556
|
+
con.execute("INSERT INTO _test_fts VALUES ('crispllm test');")
|
|
557
|
+
rows = con.execute("SELECT * FROM _test_fts WHERE _test_fts MATCH 'crispllm';").fetchall()
|
|
558
|
+
con.close()
|
|
559
|
+
if rows:
|
|
560
|
+
click.echo(f"[OK] SQLite FTS5: available (SQLite {sqlite3.sqlite_version})")
|
|
561
|
+
else:
|
|
562
|
+
click.echo("[WARN] SQLite FTS5: query returned no rows")
|
|
563
|
+
except Exception as exc:
|
|
564
|
+
click.echo(f"[FAIL] SQLite FTS5: {exc}")
|
|
565
|
+
|
|
566
|
+
try:
|
|
567
|
+
from tree_sitter_language_pack import get_parser
|
|
568
|
+
|
|
569
|
+
parsers = []
|
|
570
|
+
for lang in ("python", "javascript", "typescript", "rust", "go"):
|
|
571
|
+
if get_parser(lang) is not None:
|
|
572
|
+
parsers.append(lang)
|
|
573
|
+
click.echo(f"[OK] Tree-sitter languages: {', '.join(parsers)}")
|
|
574
|
+
except Exception as exc:
|
|
575
|
+
click.echo(f"[WARN] Tree-sitter language pack: {exc}")
|
|
576
|
+
|
|
577
|
+
resolved_cfg = config_path or Path("crispllm.toml")
|
|
578
|
+
if resolved_cfg.exists():
|
|
579
|
+
try:
|
|
580
|
+
load_config(resolved_cfg)
|
|
581
|
+
click.echo(f"[OK] Config: {resolved_cfg} (valid)")
|
|
582
|
+
except Exception as exc:
|
|
583
|
+
click.echo(f"[FAIL] Config {resolved_cfg}: {exc}")
|
|
584
|
+
else:
|
|
585
|
+
click.echo(f"[INFO] Config: {resolved_cfg} not found (using defaults)")
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
main = cli
|