evalradar 0.2.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.
@@ -0,0 +1,576 @@
1
+ """Self-hosted models: collect labeled activation events, and run the monitoring agent beside the model.
2
+
3
+ The customer path for activation monitoring:
4
+
5
+ evalradar prompts --example end-word --out prompts.jsonl # only without prompts of your own (then collect --expected)
6
+ evalradar collect --model <dir> --prompts prompts.jsonl --layer 12 --forbid 'sk-[A-Za-z0-9]{16,}' --out events.jsonl
7
+ evalradar onboard --events events.jsonl --behavior custom:no_secret_leak --feature layer.12.last_token --out monitor-out --upload-features
8
+ evalradar agent --model <dir> --monitor monitor-out/monitor.json --serve --port 8000
9
+
10
+ `collect` runs the model on the customer's prompts with a passive capture of the residual stream at the last prompt
11
+ position (the state the model has before it writes anything), labels each reply with a verifier or with labels the
12
+ customer supplies, and writes the JSONL that `onboard` reads. `agent` loads the same model and the fitted monitor,
13
+ announces itself to the console, scores every request from the prompt-position state, and reports hashed request
14
+ ids and decisions. Prompts, replies and activations stay on this machine.
15
+
16
+ The monitor is valid only for the fingerprint it was fitted on (weights, tokenizer, adapter, dtype, capture site and
17
+ generation settings). The agent computes its own fingerprint from what it loaded; if it differs from the monitor's,
18
+ every decision is `abstain` and the agent says which fields differ.
19
+ """
20
+ from __future__ import annotations
21
+ from dataclasses import asdict
22
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
23
+ from pathlib import Path
24
+ from typing import Callable, Iterable, Sequence
25
+ import hashlib
26
+ import json
27
+ import random
28
+ import re
29
+ import sys
30
+ import threading
31
+ import time
32
+ import urllib.error
33
+
34
+ from .contracts import CaptureSpec, digest
35
+ from .core import Artifact, Event, Fingerprint, score
36
+ from .sdk import UNCHECKED, ConsoleTransport, MonitorClient, hash_request_id
37
+ from . import localview
38
+ from .telemetry import CONTENT_TYPE
39
+ from . import verifiers
40
+
41
+ FEATURE = "layer.{layer}.last_token"
42
+ BAD_TOKEN = 78 # exit status for a token problem: a service manager should not restart the agent for it
43
+ AGENT_VERSION = "evalradar-agent-3" # 3: prompt and reply text, removed-model handling
44
+
45
+
46
+ def feature_id(layer: int) -> str:
47
+ return FEATURE.format(layer=layer)
48
+
49
+
50
+ def layer_of(feature: str) -> int:
51
+ m = re.fullmatch(r"layer\.(\d+)\.last_token", feature)
52
+ if not m:
53
+ raise ValueError(f"the monitor reads feature {feature!r}; the agent supports layer.<N>.last_token features from `evalradar collect`")
54
+ return int(m.group(1))
55
+
56
+
57
+ def _identity(model_dir: Path) -> tuple[str, str]:
58
+ """Model id and revision from a Hugging Face cache path (models--org--name/snapshots/<sha>), else the folder name."""
59
+ parts = model_dir.resolve().parts
60
+ if len(parts) >= 3 and parts[-2] == "snapshots" and parts[-3].startswith("models--"):
61
+ return parts[-3][len("models--"):].replace("--", "/"), parts[-1]
62
+ return model_dir.resolve().name, "local"
63
+
64
+
65
+ def load_model(model_dir: str | Path, *, model_id: str | None = None, revision: str | None = None, device: str = "auto",
66
+ dtype: str = "auto", adapter_dir: str | Path | None = None, max_context: int = 2048):
67
+ """Load a local Hugging Face checkpoint for capture. No network access and no remote code."""
68
+ import torch
69
+ from .capture.hf import HFModelAdapter
70
+ model_dir = Path(model_dir).expanduser()
71
+ if not (model_dir / "config.json").is_file():
72
+ raise SystemExit(f"error: {model_dir} is not a model folder (no config.json). Pass the folder with the weights.")
73
+ if device == "auto":
74
+ device = "cuda" if torch.cuda.is_available() else "cpu"
75
+ if dtype == "auto":
76
+ dtype = "bfloat16" if device.startswith("cuda") else "float32"
77
+ mid, rev = _identity(model_dir)
78
+ return HFModelAdapter.load(model_dir, model_id=model_id or mid, revision=revision or rev, device=device, dtype=dtype,
79
+ max_context=max_context, adapter_dir=adapter_dir)
80
+
81
+
82
+ class Runner:
83
+ """Greedy generation of one request at a time with a passive capture at the last prompt position."""
84
+
85
+ def __init__(self, adapter, layer: int, *, max_new_tokens: int = 128, system_prompt: str | None = None, lens=None):
86
+ self.adapter, self.layer, self.max_new_tokens, self.system_prompt = adapter, int(layer), int(max_new_tokens), system_prompt
87
+ self.lens = lens # evalradar.lens.LogitLens: read alongside, never part of the fingerprint
88
+ self.lens_rules: list = [] # the workspace's leak rules, to flag lens words
89
+ n_layers = len(adapter.layers)
90
+ if not 0 <= self.layer < n_layers:
91
+ raise SystemExit(f"error: --layer must be between 0 and {n_layers - 1} for this model")
92
+ self.spec = CaptureSpec(layer=self.layer, module_path=None, tap="resid_post", position_policy="last_prefill",
93
+ dtype=adapter.dtype, reduction="none", feature_id=feature_id(self.layer))
94
+ tok = adapter.tokenizer
95
+ self.chat = bool(getattr(tok, "chat_template", None))
96
+ self.generation = {"decoding": "greedy", "max_new_tokens": self.max_new_tokens, "chat_template": self.chat,
97
+ "system_prompt": digest(system_prompt or "")}
98
+ self.fingerprint: Fingerprint = adapter.fingerprint([self.spec], generation=self.generation, horizon="pre_output")
99
+ eos = getattr(adapter.model.generation_config, "eos_token_id", None) or tok.eos_token_id
100
+ self.eos = [int(e) for e in (eos if isinstance(eos, (list, tuple)) else [eos]) if e is not None]
101
+ self.pad = int(tok.pad_token_id if tok.pad_token_id is not None else (self.eos[0] if self.eos else 0))
102
+ self.lock = threading.Lock() # one generation at a time: the model and its hooks are not shared between requests
103
+ cfg = adapter.model.config
104
+ self.max_positions = int(getattr(cfg, "max_position_embeddings", None) or getattr(cfg, "n_positions", None) or 1 << 30)
105
+
106
+ def messages(self, row: dict) -> list[dict]:
107
+ if isinstance(row.get("messages"), list) and row["messages"]:
108
+ msgs = [m for m in row["messages"] if isinstance(m, dict) and isinstance(m.get("content"), str)]
109
+ elif isinstance(row.get("prompt"), str) and row["prompt"].strip():
110
+ msgs = [{"role": "user", "content": row["prompt"]}]
111
+ else:
112
+ raise ValueError("each prompt needs a non-empty 'prompt' string or a 'messages' list")
113
+ if self.system_prompt and not any(m.get("role") == "system" for m in msgs):
114
+ msgs = [{"role": "system", "content": self.system_prompt}] + msgs
115
+ return msgs
116
+
117
+ def encode(self, messages: list[dict]):
118
+ if self.chat:
119
+ return self.adapter.encode_chat(messages)
120
+ text = "\n".join(m["content"] for m in messages) # a base model without a chat template reads the plain text
121
+ return self.adapter.tokenizer(text, return_tensors="pt").input_ids
122
+
123
+ def run(self, messages: list[dict], request_id: str) -> dict:
124
+ """Generate one reply. Returns the reply, the captured feature vector (or the capture error) and timings."""
125
+ ids = self.encode(messages)
126
+ if int(ids.shape[-1]) + self.max_new_tokens > self.max_positions:
127
+ raise ValueError(f"prompt ({int(ids.shape[-1])} tokens) plus --max-new-tokens ({self.max_new_tokens}) is longer than the model's "
128
+ f"context ({self.max_positions} positions)")
129
+ with self.lock:
130
+ t0 = time.perf_counter()
131
+ trace = self.adapter.generate(ids, request_id=request_id, max_new_tokens=self.max_new_tokens, eos_token_ids=self.eos,
132
+ pad_token_id=self.pad, specs=[self.spec] + (self.lens.specs if self.lens else []),
133
+ fingerprint_digest=self.fingerprint.digest)
134
+ elapsed_ms = 1000 * (time.perf_counter() - t0)
135
+ lens = None
136
+ if self.lens is not None:
137
+ try:
138
+ lens = self.lens.read(trace, self.lens_rules)
139
+ except Exception as exc: # an explanation must never break serving
140
+ lens = {"method": "logit_lens", "error": type(exc).__name__}
141
+ new = [t for t in trace.new_token_ids if t not in self.eos]
142
+ reply = self.adapter.tokenizer.decode(new, skip_special_tokens=True)
143
+ vec, err = None, trace.capture_error
144
+ if err is None:
145
+ cap = trace.captures.get(self.spec.feature_id)
146
+ if cap is None:
147
+ err = "unavailable:no capture"
148
+ else:
149
+ vec = [float(x) for x in cap.data[-1].float().cpu().reshape(-1).tolist()]
150
+ return {"reply": reply, "features": vec, "capture_error": err, "tokens": len(trace.new_token_ids),
151
+ "prompt_tokens": int(ids.shape[-1]), "latency_ms": elapsed_ms, "lens": lens}
152
+
153
+
154
+ def features(self, messages: list[dict], request_id: str) -> list[float] | None:
155
+ """Only the captured state at the last prompt position (no reply is needed for it): one decoding step."""
156
+ ids = self.encode(messages)
157
+ with self.lock:
158
+ trace = self.adapter.generate(ids, request_id=request_id, max_new_tokens=1, eos_token_ids=self.eos,
159
+ pad_token_id=self.pad, specs=[self.spec], fingerprint_digest=self.fingerprint.digest)
160
+ cap = trace.captures.get(self.spec.feature_id) if trace.capture_error is None else None
161
+ return None if cap is None else [float(x) for x in cap.data[-1].float().cpu().reshape(-1).tolist()]
162
+
163
+
164
+ def checkpoint_identity(model_dir: str | Path, model_id: str | None = None) -> dict:
165
+ """The model and checkpoint fields of the fingerprint, from file hashes only (no model load), to look up
166
+ ready-made monitors. Matches what HFModelAdapter.fingerprint computes for the same folder."""
167
+ from .capture.hf import sha256_file
168
+ model_dir = Path(model_dir).expanduser()
169
+ if not (model_dir / "config.json").is_file():
170
+ raise SystemExit(f"error: {model_dir} is not a model folder (no config.json)")
171
+ mid, rev = _identity(model_dir)
172
+ weights = {p.name: sha256_file(p) for p in sorted(model_dir.iterdir()) if p.is_file() and p.suffix == ".safetensors"}
173
+ return {"model": model_id or mid, "checkpoint": f"revision:{rev};weights:{digest(weights)}"}
174
+
175
+
176
+ # Ready-made monitors are fitted on EvalVitals' machines. Only the runtime identity (torch / transformers versions,
177
+ # GPU) may differ on the customer's; whether the monitor still reads the same state is checked on the signed
178
+ # reference prompts before it is used. Every other fingerprint field must match exactly.
179
+ EQUIVALENT_IF_CHECKED = {"backend"}
180
+ MIN_DECISION_AGREEMENT = 0.95 # of the reference prompts (chosen to span the threshold) must get the same decision
181
+
182
+
183
+ def reference_check(runner: "Runner", artifact: Artifact, reference: dict) -> dict:
184
+ """Score the signed reference prompts here and compare with the scores recorded where the monitor was fitted."""
185
+ prompts, expected, tol = reference.get("prompts") or [], reference.get("raw") or [], float(reference.get("tolerance", 0.05))
186
+ if not prompts or len(prompts) != len(expected):
187
+ return {"passed": False, "reason": "the monitor carries no usable reference prompts"}
188
+ feature = runner.spec.feature_id
189
+ worst, total, agree, n = 0.0, 0.0, 0, 0
190
+ for i, (row, want) in enumerate(zip(prompts, expected)):
191
+ vec = runner.features(runner.messages(row), f"reference-{i}")
192
+ if vec is None:
193
+ return {"passed": False, "reason": f"reference prompt {i + 1} could not be captured"}
194
+ ev = Event(f"reference-{i}", artifact.fingerprint, None, {feature: vec})
195
+ for m in artifact.monitors:
196
+ if m.name not in want or not hasattr(m, "feature"):
197
+ continue
198
+ got = m.raw(ev)
199
+ if got is None:
200
+ return {"passed": False, "reason": f"reference prompt {i + 1}: no score"}
201
+ worst, total = max(worst, abs(got - want[m.name])), total + abs(got - want[m.name])
202
+ agree += (got > artifact.thresholds[m.name]) == (want[m.name] > artifact.thresholds[m.name])
203
+ n += 1
204
+ agreement = agree / n if n else 0.0
205
+ passed = n > 0 and worst <= tol and agreement >= MIN_DECISION_AGREEMENT
206
+ return {"passed": passed, "prompts": len(prompts), "max_abs_diff": round(worst, 5), "mean_abs_diff": round(total / n, 5) if n else None,
207
+ "decision_agreement": round(agreement, 4), "tolerance": tol,
208
+ **({} if passed else {"reason": f"scores differ by up to {worst:.3f} (allowed {tol}) and decisions agree on "
209
+ f"{100 * agreement:.0f}% (need {100 * MIN_DECISION_AGREEMENT:.0f}%)"})}
210
+
211
+
212
+ def _last_user(messages: list[dict]) -> str:
213
+ return next((str(m.get("content") or "") for m in reversed(messages or []) if m.get("role") == "user"), "")
214
+
215
+
216
+ def _score_fields(ev: dict) -> dict:
217
+ """The probe's score and alert threshold as numbers, for the console's score bar."""
218
+ f = ev.get("fusion") or {}
219
+ if f.get("score") is None or f.get("threshold") is None:
220
+ return {}
221
+ return {"score": round(float(f["score"]), 5), "threshold": round(float(f["threshold"]), 5)}
222
+
223
+
224
+ # ---- labels -------------------------------------------------------------------------------------
225
+ def make_labeler(*, forbid: Sequence[str] = (), require: Sequence[str] = (), target: dict | None = None,
226
+ case_sensitive: bool = False, expected: bool = False) -> Callable[[str, str, str | None], tuple[bool, str]] | None:
227
+ """A function (prompt, reply, expected) -> (failed, reason) from a verifier, or None when labels come with the prompts.
228
+ expected=True: each prompt's own "expected" regex is the check (a reply that does not match it fails)."""
229
+ spec = None
230
+ if expected:
231
+ spec = verifiers.validate_verifier({"kind": "reference_match", "match_mode": "regex"})
232
+ elif target is not None:
233
+ spec = verifiers.validate_verifier(target.get("verifier", target))
234
+ elif forbid:
235
+ spec = verifiers.validate_verifier({"kind": "regex_forbidden", "patterns": "\n".join(forbid), "case_sensitive": case_sensitive})
236
+ elif require:
237
+ spec = verifiers.validate_verifier({"kind": "regex_required", "patterns": "\n".join(require), "case_sensitive": case_sensitive})
238
+ if spec is None:
239
+ return None
240
+ if spec["kind"] in ("rubric_judge", "external_label"):
241
+ raise SystemExit(f"error: a {spec['kind']} verifier cannot label replies here; put a 0/1 'label' on each prompt instead")
242
+ return lambda prompt, reply, expected: verifiers.verify_output(spec, reply, prompt=prompt, expected=expected)
243
+
244
+
245
+ def read_jsonl(path: str | Path) -> list[dict]:
246
+ rows = []
247
+ with Path(path).expanduser().open(encoding="utf-8") as f:
248
+ for n, line in enumerate(f, 1):
249
+ if line.strip():
250
+ try:
251
+ row = json.loads(line)
252
+ except ValueError:
253
+ raise SystemExit(f"error: {path}:{n} is not JSON") from None
254
+ if not isinstance(row, dict):
255
+ raise SystemExit(f"error: {path}:{n} must be a JSON object")
256
+ rows.append(row)
257
+ if not rows:
258
+ raise SystemExit(f"error: {path} has no prompts")
259
+ return rows
260
+
261
+
262
+ def collect(runner: Runner, rows: Iterable[dict], out_path: str | Path, *, labeler=None, keep_text: bool = False,
263
+ progress: Callable[[str], None] | None = None) -> dict:
264
+ """Run every prompt, label the reply and write one onboarding event per prompt.
265
+
266
+ Event format (one JSON object per line, what `evalradar onboard` reads):
267
+ event_id stable id of the prompt (sha256 of its `id`, or of the prompt text)
268
+ group `group` from the prompt row, else the event id; splits never put one group on two sides
269
+ label 1 when the reply failed (verifier, or the row's own 0/1 `label`), else 0
270
+ step 0: the state is read before the first output token
271
+ fingerprint the model fingerprint (weights, tokenizer, dtype, capture site, generation settings)
272
+ features {"layer.<N>.last_token": [floats]}: residual stream after layer N at the last prompt token
273
+ text the reply, only with keep_text (needed for `onboard --pattern`)
274
+ """
275
+ out_path = Path(out_path).expanduser()
276
+ out_path.parent.mkdir(parents=True, exist_ok=True)
277
+ fp = asdict(runner.fingerprint)
278
+ n = failures = skipped = 0
279
+ reasons: dict[str, int] = {}
280
+ with out_path.open("w", encoding="utf-8") as f:
281
+ for i, row in enumerate(rows):
282
+ msgs = runner.messages(row)
283
+ key = str(row.get("id") or json.dumps(msgs, sort_keys=True))
284
+ event_id = hashlib.sha256(key.encode()).hexdigest()[:16]
285
+ res = runner.run(msgs, event_id)
286
+ if res["features"] is None:
287
+ skipped += 1
288
+ reasons[res["capture_error"]] = reasons.get(res["capture_error"], 0) + 1
289
+ continue
290
+ if row.get("label") in (0, 1) and not isinstance(row.get("label"), bool):
291
+ label, why = int(row["label"]), "label supplied with the prompt"
292
+ elif labeler is not None:
293
+ failed, why = labeler(msgs[-1]["content"], res["reply"], row.get("expected"))
294
+ label = int(bool(failed))
295
+ else:
296
+ raise SystemExit(f"error: prompt {i + 1} has no 0/1 'label' and no verifier was given (use --forbid, --require, --expected or --target-file)")
297
+ ev = {"event_id": event_id, "group": str(row.get("group") or event_id), "label": label, "step": 0, "fingerprint": fp,
298
+ "features": {runner.spec.feature_id: res["features"]}, "label_reason": str(why)[:120]}
299
+ if keep_text:
300
+ ev["text"] = res["reply"]
301
+ f.write(json.dumps(ev) + "\n")
302
+ n += 1
303
+ failures += label
304
+ if progress and (n % 25 == 0):
305
+ progress(f"{n} prompts done, {failures} failed")
306
+ return {"events": n, "failures": failures, "failure_rate": failures / n if n else None, "skipped_capture_errors": skipped,
307
+ "capture_errors": reasons, "feature": runner.spec.feature_id, "fingerprint_digest": runner.fingerprint.digest,
308
+ "out": str(out_path)}
309
+
310
+
311
+ # ---- the monitoring agent -------------------------------------------------------------------------
312
+ def fingerprint_diff(a: Fingerprint, b: Fingerprint) -> list[str]:
313
+ return [k for k in asdict(a) if getattr(a, k) != getattr(b, k)]
314
+
315
+
316
+ class Agent:
317
+ """Runs beside the model. Outbound calls only: hello, poll for commands, report decisions."""
318
+
319
+ def __init__(self, runner: Runner, artifact: Artifact, *, console_url: str | None, token: str | None,
320
+ prompts: Sequence[dict] = (), batch_size: int = 8, log: Callable[[str], None] = print, signature: dict | None = None,
321
+ send_text: bool | None = None):
322
+ self.runner, self.artifact, self.prompts, self.log = runner, artifact, list(prompts), log
323
+ self.signature = dict(signature or {"signed": False}) # from evalradar.signing.check_monitor
324
+ self.equivalence: dict | None = None
325
+ self.batch_size = max(1, min(256, int(batch_size)))
326
+ feats = {m.feature for m in artifact.monitors if hasattr(m, "feature")}
327
+ if feats and feats != {runner.spec.feature_id}:
328
+ raise SystemExit(f"error: the monitor reads {sorted(feats)}, but the agent captures {runner.spec.feature_id}")
329
+ self.mismatch = fingerprint_diff(artifact.fingerprint, runner.fingerprint)
330
+ self.score_fp = runner.fingerprint # events are scored under this fingerprint
331
+ fp = runner.fingerprint
332
+ self.deployment = {"model_id": runner.adapter.model_id, "revision": runner.adapter.revision,
333
+ "adapter": getattr(runner.adapter, "adapter", "none"), "dtype": runner.adapter.dtype, "execution": fp.backend[:200]}
334
+ self.monitor = {"monitor_id": "monitor:" + artifact.artifact_id[:16], "behavior": artifact.behavior[:120],
335
+ "fingerprint": fp.digest[:16], "batch_size": self.batch_size, "signature": self._signature_summary()}
336
+ self.transport = ConsoleTransport(console_url, token) if console_url and token else None
337
+ # Always a client: it reports decisions when a console is configured and keeps the Prometheus counts either way.
338
+ self.client = MonitorClient(console_url if self.transport else None, token=token if self.transport else None, model_id=self.deployment["model_id"],
339
+ revision=self.deployment["revision"], adapter=self.deployment["adapter"], dtype=self.deployment["dtype"],
340
+ execution=self.deployment["execution"], source="activation_monitor", auto_sync=False, send_text=send_text)
341
+ self.served = 0
342
+ self.activation_on = True # the console's switch for this deployment; read on every poll
343
+ self.removed = False # the console stopped monitoring this model: keep serving, report nothing
344
+ self.alerts = 0
345
+ self._stop = threading.Event()
346
+
347
+ def _signature_summary(self) -> dict:
348
+ sig = self.signature
349
+ out = {"signed": bool(sig.get("signed"))}
350
+ if out["signed"]:
351
+ out |= {"origin": sig.get("origin"), "key_id": sig.get("key_id"), "issuer": str(sig.get("issuer", ""))[:120]}
352
+ if self.equivalence:
353
+ out["reference_check"] = {k: self.equivalence[k] for k in ("prompts", "max_abs_diff", "decision_agreement")}
354
+ return out
355
+
356
+ def check_equivalence(self) -> dict | None:
357
+ """For a signed library monitor whose fingerprint differs only in the runtime identity: run the reference check
358
+ and, when it passes, score under the monitor's fingerprint. Returns the check, or None when not applicable."""
359
+ ref = (self.signature.get("library") or {}).get("reference")
360
+ if not (self.signature.get("signed") and self.signature.get("origin") == "library" and ref
361
+ and self.mismatch and set(self.mismatch) <= EQUIVALENT_IF_CHECKED):
362
+ return None
363
+ check = reference_check(self.runner, self.artifact, ref)
364
+ if check["passed"]:
365
+ self.equivalence, self.score_fp, self.mismatch = check, self.artifact.fingerprint, []
366
+ self.monitor["signature"] = self._signature_summary()
367
+ return check
368
+
369
+ # one request: generate, score from the prompt-position state, report the decision
370
+ def handle(self, messages: list[dict], request_id: str | None = None) -> dict:
371
+ rid = request_id or f"req-{time.time_ns()}-{random.random()}"
372
+ res = self.runner.run(messages, hash_request_id(rid))
373
+ behavior = self.artifact.behavior
374
+ if not self.activation_on: # switched off in the console: still served, reported as unchecked with the reason
375
+ behavior, decision = UNCHECKED, {"status": "abstain", "reason": "activation monitor switched off in the console", "scoring_ms": None}
376
+ elif res["features"] is None:
377
+ decision = {"status": "abstain", "reason": "capture_failed:" + str(res["capture_error"])[:80], "scoring_ms": 0.0}
378
+ else:
379
+ ev = score(self.artifact, Event(hash_request_id(rid), self.score_fp, None, {self.runner.spec.feature_id: res["features"]}))
380
+ reason = ev["reason"]
381
+ if ev["status"] != "abstain" and ev["fusion"]:
382
+ reason = f"score {ev['fusion']['score']:.3f} {'>' if ev['status'] == 'alert' else '<='} threshold {ev['fusion']['threshold']:.3f}"
383
+ decision = {"status": ev["status"], "reason": reason, "scoring_ms": ev["scoring_ms"], **_score_fields(ev)}
384
+ self.served += 1
385
+ self.alerts += decision["status"] == "alert"
386
+ self.client.record_decision(rid, decision["status"], behavior=behavior, reason=decision["reason"],
387
+ scoring_ms=decision["scoring_ms"], latency_ms=res["latency_ms"], tokens=res["tokens"],
388
+ score=decision.get("score"), threshold=decision.get("threshold"), lens=res.get("lens"),
389
+ prompt_text=_last_user(messages), reply_text=res["reply"])
390
+ if not self.transport: # no console to send them to: the decision only feeds the metrics
391
+ with self.client._lock:
392
+ self.client._queue.clear()
393
+ m = self.client.metrics; dep = m.dep
394
+ m.requests.inc(dep, "activation_monitor", "true" if self.activation_on else "false")
395
+ m.latency.observe(res["latency_ms"] / 1000, dep, "activation_monitor")
396
+ return {**res, **decision, "request_id": hash_request_id(rid)}
397
+
398
+ def _set_removed(self, removed: bool):
399
+ if removed != self.removed:
400
+ self.log("this model was removed from monitoring in the console: still serving, not reporting" if removed
401
+ else "this model was restored in the console: reporting again")
402
+ self.removed = self.client.removed = removed
403
+
404
+ def run_batch(self, why: str) -> dict | None:
405
+ """A batch over the agent's own prompt file, for the console's "Run a batch" button and --every."""
406
+ if self.removed:
407
+ self.log(f"batch ({why}) skipped: this model was removed from monitoring in the console")
408
+ return None
409
+ if not self.prompts:
410
+ self.log(f"batch requested ({why}) but the agent has no --prompts file; ignored")
411
+ return None
412
+ rows = [self.prompts[(int(time.time()) + i) % len(self.prompts)] for i in range(self.batch_size)]
413
+ started, t0, reqs = time.time(), time.perf_counter(), []
414
+ for i, row in enumerate(rows):
415
+ rid = f"batch-{started}-{i}"
416
+ received = 1000 * (time.perf_counter() - t0)
417
+ res = self.runner.run(self.runner.messages(row), hash_request_id(rid))
418
+ if not self.activation_on:
419
+ st, reason, sms = "abstain", "activation monitor switched off in the console", None
420
+ elif res["features"] is None:
421
+ st, reason, sms = "abstain", "capture_failed", 0.0
422
+ else:
423
+ ev = score(self.artifact, Event(hash_request_id(rid), self.score_fp, None, {self.runner.spec.feature_id: res["features"]}))
424
+ st, reason, sms = ev["status"], ev["reason"], ev["scoring_ms"]
425
+ reqs.append({"request_id": hash_request_id(rid), "status": st, "reason": reason, "received_ms": received, "scoring_ms": sms,
426
+ "tokens": res["tokens"], **({} if self.activation_on else {"behavior": UNCHECKED}),
427
+ **(_score_fields(ev) if self.activation_on and res["features"] is not None else {}),
428
+ **({"lens": res["lens"]} if res.get("lens") else {}),
429
+ **({"prompt": _last_user(self.runner.messages(row))[:4000], "reply": res["reply"][:8000]} if self.client.send_text else {})})
430
+ trace = {"model": self.deployment["model_id"], "revision": self.deployment["revision"][:80], "fingerprint": self.monitor["fingerprint"],
431
+ "monitor": self.monitor["monitor_id"], "behavior": self.artifact.behavior, "batch_id": hashlib.sha256(f"{started}".encode()).hexdigest()[:32],
432
+ "started_unix": started, "completed_ms": 1000 * (time.perf_counter() - t0), "requests": reqs}
433
+ if self.transport:
434
+ self.transport.post("batch", {"trace": trace})
435
+ counts: dict[str, int] = {}
436
+ for r in reqs:
437
+ counts[r["status"]] = counts.get(r["status"], 0) + 1
438
+ self.log(f"batch ({why}): {counts}, {trace['completed_ms']:.0f} ms")
439
+ return trace
440
+
441
+ def hello(self):
442
+ if self.transport:
443
+ out = self.transport.post("hello", {"version": AGENT_VERSION, "deployment": self.deployment, "monitor": self.monitor})
444
+ self._set_removed(bool(out.get("removed")))
445
+ if self.runner.lens is not None: # the workspace's leak rules also flag lens words
446
+ from .lens import compile_rules
447
+ self.runner.lens_rules = compile_rules(out.get("targets") or [])
448
+
449
+ def poll_once(self) -> dict | None:
450
+ """Ask the console for a command and for this deployment's switches. Returns the command, if any."""
451
+ polled = self.transport.post("poll", {})
452
+ if isinstance(polled.get("monitoring"), dict):
453
+ self._set_removed(bool(polled["monitoring"].get("removed")))
454
+ on = bool(polled["monitoring"].get("activation", True))
455
+ if on != self.activation_on:
456
+ self.log(f"activation monitor switched {'on' if on else 'off'} in the console")
457
+ self.activation_on = on
458
+ return polled.get("command")
459
+
460
+ def loop(self, *, poll: float = 3.0, every: float = 0.0):
461
+ """Poll the console for commands until stopped. Exits with BAD_TOKEN when the console does not know the token."""
462
+ last_auto = last_hello = time.time()
463
+ backoff = poll
464
+ while not self._stop.is_set():
465
+ try:
466
+ if self.transport:
467
+ cmd = self.poll_once()
468
+ if cmd and cmd.get("type") == "run_batch":
469
+ self.run_batch("requested in the console")
470
+ if time.time() - last_hello > 300: # the console may have restarted or the deployment been removed
471
+ last_hello = time.time()
472
+ self.hello()
473
+ if every and time.time() - last_auto >= every:
474
+ last_auto = time.time()
475
+ self.run_batch("scheduled")
476
+ backoff = poll
477
+ except RuntimeError as exc:
478
+ if "HTTP 401" in str(exc):
479
+ self.log("the console does not know this token: the connection was revoked, or the token was copied incompletely")
480
+ raise SystemExit(BAD_TOKEN)
481
+ self.log(f"console error ({exc}); retrying in {backoff:.0f} s")
482
+ backoff = min(60, backoff * 2)
483
+ except (urllib.error.URLError, TimeoutError, OSError) as exc:
484
+ self.log(f"console unreachable ({type(exc).__name__}: {exc}); retrying in {backoff:.0f} s")
485
+ backoff = min(60, backoff * 2)
486
+ self._stop.wait(backoff)
487
+
488
+ def stop(self):
489
+ self._stop.set()
490
+ self.client.close()
491
+
492
+
493
+ def make_agent_server(agent: Agent, *, host: str = "127.0.0.1", port: int = 8000) -> ThreadingHTTPServer:
494
+ """An OpenAI-compatible endpoint (`/v1/chat/completions`, `/v1/models`) served by the monitored model itself.
495
+
496
+ Every request is monitored; the reply is returned whatever the decision (the agent never blocks or edits output).
497
+ `stream: true` is answered as a server-sent event stream carrying the whole reply in one chunk."""
498
+ model_name = agent.deployment["model_id"]
499
+
500
+ class Handler(BaseHTTPRequestHandler):
501
+
502
+ # Headers and body go out as two writes; without this, Nagle's algorithm and the client's delayed ACK
503
+
504
+ # can hold each response on a kept-alive connection for up to ~40 ms.
505
+
506
+ disable_nagle_algorithm = True
507
+ protocol_version = "HTTP/1.1"
508
+
509
+ def log_message(self, fmt, *args):
510
+ pass
511
+
512
+ def _json(self, obj: dict, status: int = 200):
513
+ data = json.dumps(obj).encode()
514
+ self.send_response(status)
515
+ self.send_header("Content-Type", "application/json")
516
+ self.send_header("Content-Length", str(len(data)))
517
+ self.end_headers()
518
+ self.wfile.write(data)
519
+
520
+ def do_GET(self):
521
+ if self.path.rstrip("/") in ("/v1/models", "/models"):
522
+ return self._json({"object": "list", "data": [{"id": model_name, "object": "model", "owned_by": "self-hosted"}]})
523
+ if localview.respond(self, agent.client, "EvalRadar agent: recent requests"):
524
+ return
525
+ if self.path == "/evalradar/metrics":
526
+ body = agent.client.metrics.registry.render()
527
+ self.send_response(200)
528
+ self.send_header("Content-Type", CONTENT_TYPE)
529
+ self.send_header("Content-Length", str(len(body)))
530
+ self.end_headers()
531
+ return self.wfile.write(body)
532
+ if self.path == "/evalradar/health":
533
+ return self._json({"ok": not agent.mismatch, "model_id": model_name, "monitor": agent.monitor["monitor_id"], "served": agent.served,
534
+ "alerts": agent.alerts, "fingerprint_mismatch": agent.mismatch,
535
+ "last_error": agent.client.last_error if agent.transport else None})
536
+ self._json({"error": "not found"}, 404)
537
+
538
+ def do_POST(self):
539
+ if self.path.rstrip("/") not in ("/v1/chat/completions", "/chat/completions"):
540
+ return self._json({"error": "not found"}, 404)
541
+ try:
542
+ n = int(self.headers.get("Content-Length") or 0)
543
+ if not 0 < n <= 4 * 1024 * 1024:
544
+ return self._json({"error": "request body missing or too large"}, 413 if n else 400)
545
+ body = json.loads(self.rfile.read(n))
546
+ msgs = agent.runner.messages({"messages": body.get("messages")})
547
+ except (ValueError, TypeError) as exc:
548
+ return self._json({"error": {"message": f"bad request: {exc}", "type": "invalid_request_error"}}, 400)
549
+ try:
550
+ out = agent.handle(msgs, self.headers.get("X-Request-Id"))
551
+ except Exception as exc: # a generation failure is the caller's error to see; nothing is reported for it
552
+ return self._json({"error": {"message": f"generation failed: {type(exc).__name__}: {exc}", "type": "server_error"}}, 500)
553
+ cid, created = "chatcmpl-" + out["request_id"][:24], int(time.time())
554
+ usage = {"prompt_tokens": out["prompt_tokens"], "completion_tokens": out["tokens"], "total_tokens": out["prompt_tokens"] + out["tokens"]}
555
+ if body.get("stream"):
556
+ chunks = [{"id": cid, "object": "chat.completion.chunk", "created": created, "model": model_name,
557
+ "choices": [{"index": 0, "delta": {"role": "assistant", "content": out["reply"]}, "finish_reason": None}]},
558
+ {"id": cid, "object": "chat.completion.chunk", "created": created, "model": model_name,
559
+ "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}]
560
+ data = "".join(f"data: {json.dumps(c)}\n\n" for c in chunks).encode() + b"data: [DONE]\n\n"
561
+ self.send_response(200)
562
+ self.send_header("Content-Type", "text/event-stream")
563
+ self.send_header("Content-Length", str(len(data)))
564
+ self.end_headers()
565
+ return self.wfile.write(data)
566
+ self._json({"id": cid, "object": "chat.completion", "created": created, "model": model_name,
567
+ "choices": [{"index": 0, "message": {"role": "assistant", "content": out["reply"]}, "finish_reason": "stop"}],
568
+ "usage": usage, "evalradar": {"decision": out["status"], "request_id": out["request_id"]}})
569
+
570
+ srv = ThreadingHTTPServer((host, port), Handler)
571
+ srv.daemon_threads = True
572
+ return srv
573
+
574
+
575
+ def err(msg: str):
576
+ print(msg, file=sys.stderr, flush=True)