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.
evalradar/sdk.py ADDED
@@ -0,0 +1,1045 @@
1
+ """Customer-facing Python SDK for live monitoring and feedback reporting.
2
+
3
+ Prompts, model outputs and activations never leave the host: verifiers execute locally and only
4
+ hashed request ids, decisions, timings and optional ground-truth labels are sent to the console.
5
+ """
6
+ from __future__ import annotations
7
+ import hashlib
8
+ import inspect
9
+ import json
10
+ import re
11
+ from concurrent.futures import ThreadPoolExecutor
12
+ import atexit
13
+ from collections import deque
14
+ import threading
15
+ import time
16
+ import urllib.error
17
+ import urllib.parse
18
+ import urllib.request
19
+ from pathlib import Path
20
+ from typing import Any, Callable, Sequence
21
+
22
+ from . import telemetry, verifiers
23
+ from .telemetry import ClientMetrics
24
+
25
+ HEX_RE = re.compile(r"^[0-9a-f]{16,64}$")
26
+ SDK_VERSION = "sdk-6" # 3: text, console judging, removed models; 4: request summaries; 5: text_overlap checks; 6: tasks
27
+
28
+
29
+ UNCHECKED = "live_traffic" # behavior id of requests no monitor target covered
30
+ ERROR_KINDS = ("timeout", "unreachable", "http_4xx", "http_5xx", "client_error")
31
+
32
+
33
+ def error_kind(exc: BaseException) -> tuple[str, int | None]:
34
+ """What kind of failure an exception from a model client is, for the health view, and its HTTP status if any."""
35
+ status = getattr(exc, "status_code", None) or getattr(getattr(exc, "response", None), "status_code", None)
36
+ if isinstance(status, int):
37
+ return ("http_5xx" if status >= 500 else "http_4xx"), status
38
+ name = type(exc).__name__.lower()
39
+ if "timeout" in name or isinstance(exc, TimeoutError):
40
+ return "timeout", None
41
+ if "connection" in name or isinstance(exc, (ConnectionError, urllib.error.URLError)):
42
+ return "unreachable", None
43
+ return "client_error", None
44
+
45
+
46
+ def openai_compatible_judge(base_url: str, model: str, api_key: str | None = None, timeout: float = 30.0) -> Callable[[str, str], str]:
47
+ """A judge function for rubric targets: one chat completion per judged reply at an OpenAI-compatible endpoint.
48
+
49
+ The judge receives the rubric, the prompt and the reply. Point it at a model you run yourself (e.g. the vLLM that
50
+ serves your app) to keep them on your infrastructure, or at a provider you already send this traffic to."""
51
+ base = base_url.rstrip("/")
52
+ url = (base if base.endswith("/v1") else base + "/v1") + "/chat/completions"
53
+ headers = {"Content-Type": "application/json", **({"Authorization": f"Bearer {api_key}"} if api_key else {})}
54
+
55
+ def judge(system: str, user: str) -> str:
56
+ body = {"model": model, "temperature": 0, "max_tokens": 300,
57
+ "messages": [{"role": "system", "content": system}, {"role": "user", "content": user}]}
58
+ req = urllib.request.Request(url, json.dumps(body).encode(), headers, method="POST")
59
+ with urllib.request.urlopen(req, timeout=timeout) as r:
60
+ return json.loads(r.read())["choices"][0]["message"]["content"] or ""
61
+ return judge
62
+
63
+
64
+ def hash_request_id(raw_id: str) -> str:
65
+ """Turn any application request id into a stable 32-char hexadecimal hash."""
66
+ s = str(raw_id).strip()
67
+ if HEX_RE.fullmatch(s):
68
+ return s
69
+ return hashlib.sha256(s.encode("utf-8")).hexdigest()[:32]
70
+
71
+
72
+ def _read_token(token: str | None, token_file: str | Path | None) -> str | None:
73
+ if token:
74
+ return token.strip()
75
+ if token_file:
76
+ return Path(token_file).expanduser().read_text().strip()
77
+ return None
78
+
79
+
80
+ def _sample_hit(request_hash: str, sample_rate: float) -> bool:
81
+ if sample_rate >= 1.0:
82
+ return True
83
+ if sample_rate <= 0.0:
84
+ return False
85
+ bucket = int(request_hash[:8], 16) / 0xFFFFFFFF
86
+ return bucket <= sample_rate
87
+
88
+
89
+ class ConsoleTransport:
90
+ """Minimal outbound HTTPS client for /api/ingest/* endpoints."""
91
+
92
+ def __init__(self, base_url: str, token: str, *, timeout: float = 10.0):
93
+ u = urllib.parse.urlsplit(base_url)
94
+ if u.scheme != "https" and u.hostname not in ("127.0.0.1", "localhost"):
95
+ raise ValueError("console_url must use https (plain http is allowed for loopback only)")
96
+ if not token.startswith("ewa_"):
97
+ raise ValueError("agent token must start with 'ewa_'")
98
+ self.base = base_url.rstrip("/")
99
+ self.token = token
100
+ self.timeout = timeout
101
+
102
+ def post(self, what: str, body: dict) -> dict:
103
+ req = urllib.request.Request(
104
+ f"{self.base}/api/ingest/{what}",
105
+ data=json.dumps(body).encode("utf-8"),
106
+ method="POST",
107
+ headers={"Content-Type": "application/json", "Authorization": f"Bearer {self.token}"},
108
+ )
109
+ try:
110
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
111
+ return json.loads(resp.read().decode("utf-8"))
112
+ except urllib.error.HTTPError as exc:
113
+ detail = ""
114
+ try:
115
+ detail = json.loads(exc.read().decode("utf-8")).get("error", "")
116
+ except Exception:
117
+ pass
118
+ raise RuntimeError(f"console HTTP {exc.code}: {detail}") from None
119
+
120
+
121
+ PROMPT_CHARS, REPLY_CHARS = 4_000, 8_000 # text sent with a decision is cut to this
122
+ LOCAL_RECENT = 200
123
+ NO_JUDGE_REASON = "not judged: no judge model here (proxy: --judge-model; SDK: MonitorClient(judge=...))"
124
+ REMOVED_NOTE = ("this model was removed from monitoring in the console: requests are still served or forwarded, "
125
+ "but decisions are not sent until it is restored there")
126
+
127
+
128
+ class MonitorClient:
129
+ """Attach live monitoring to any Python inference loop or OpenAI-compatible client.
130
+
131
+ Supports both console-connected mode (`console_url` + `token`/`token_file`) and offline local
132
+ mode (`console_url=None` + `targets=[...]`) for unit tests and air-gapped hosts.
133
+ """
134
+
135
+ def __init__(
136
+ self,
137
+ console_url: str | None = None,
138
+ *,
139
+ token: str | None = None,
140
+ token_file: str | Path | None = None,
141
+ model_id: str = "custom/model",
142
+ revision: str = "live",
143
+ adapter: str = "none",
144
+ dtype: str = "unknown",
145
+ execution: str = "sdk",
146
+ kind: str = "self_hosted",
147
+ provider: str | None = None,
148
+ deployment_name: str | None = None,
149
+ targets: Sequence[dict] | None = None,
150
+ source: str = "sdk",
151
+ flush_interval: float = 2.0,
152
+ batch_size: int = 32,
153
+ sync_interval: float = 30.0,
154
+ auto_sync: bool = True,
155
+ background: bool = True,
156
+ timeout: float = 10.0,
157
+ max_queue: int = 10_000,
158
+ judge: Callable[[str, str], str] | None = None,
159
+ judge_workers: int = 2,
160
+ judge_backlog: int = 64,
161
+ send_text: bool | None = None,
162
+ task: str | None = None,
163
+ ):
164
+ self.model_id = model_id
165
+ # The task requests belong to when the call does not say (see verifiers.target_applies): a tag such as "support".
166
+ self.task = (str(task).strip().lower() or None) if task else None
167
+ # Prompt and reply text go with each decision unless switched off (send_text=False or EVALRADAR_SEND_TEXT=0); either
168
+ # way the most recent requests stay readable on this machine (local_requests(), the proxy's /evalradar/requests).
169
+ if send_text is None:
170
+ from ._compat import env
171
+ send_text = (env("SEND_TEXT") or "1").strip().lower() not in ("0", "false", "no", "off")
172
+ self.send_text = bool(send_text)
173
+ self.recent: deque = deque(maxlen=LOCAL_RECENT)
174
+ self.adapter = "" if adapter in ("", "none", None) else str(adapter)
175
+ self.deployment_key = f"{model_id}|{self.adapter}"
176
+ self.source = source
177
+ self.batch_size = max(1, min(256, int(batch_size)))
178
+ self.flush_interval = max(0.2, float(flush_interval))
179
+ self.sync_interval = max(5.0, float(sync_interval))
180
+ self.deployment = {
181
+ "model_id": model_id,
182
+ "revision": revision,
183
+ "adapter": adapter or "none",
184
+ "dtype": dtype,
185
+ "execution": execution,
186
+ "kind": kind,
187
+ **({"provider": provider} if provider else {}),
188
+ **({"name": deployment_name} if deployment_name else {}),
189
+ }
190
+ tok = _read_token(token, token_file)
191
+ self.transport = ConsoleTransport(console_url, tok, timeout=timeout) if console_url and tok else None
192
+ self._lock = threading.Lock()
193
+ self._queue: list[dict] = []
194
+ self.max_queue = max(1, int(max_queue))
195
+ # Rubric-judge targets in live traffic: a judge model (see openai_compatible_judge) called in the background, so a
196
+ # reply is never held up by its judgement. Only sampled requests are judged (the target's sample_rate).
197
+ self.judge_fn = judge
198
+ self._judge_pool: ThreadPoolExecutor | None = ThreadPoolExecutor(max(1, int(judge_workers)), thread_name_prefix="evalradar-judge") if judge else None
199
+ self._judge_backlog, self._judge_pending, self._judge_lock = max(1, int(judge_backlog)), 0, threading.Lock()
200
+ self.dropped = 0 # events discarded because the queue hit max_queue (oldest first)
201
+ self._targets: list[dict] = [self._normalize_local_target(t, i) for i, t in enumerate(targets or [])]
202
+ self._last_sync = 0.0
203
+ self.last_error: str | None = None
204
+ self.removed = False # the console stopped monitoring this model: decisions are not sent until it is restored
205
+ self._summaries_ok = True # False after a console too old to accept request summaries refused them
206
+ self._served: str | None = None
207
+ self._stop = threading.Event()
208
+ self.metrics = ClientMetrics(self) # counts and timings for Prometheus; see serve_metrics()
209
+ self._worker: threading.Thread | None = None
210
+
211
+ if self.transport and auto_sync:
212
+ try:
213
+ self.sync_targets()
214
+ except Exception as exc:
215
+ self.last_error = str(exc)
216
+ if background and self.transport:
217
+ self._worker = threading.Thread(target=self._loop, daemon=True)
218
+ self._worker.start()
219
+ if self.transport: # a short script that exits right after its last request still sends that request's event
220
+ atexit.register(self.close)
221
+
222
+ @staticmethod
223
+ def _normalize_local_target(t: dict, idx: int) -> dict:
224
+ validated = verifiers.validate_target(t)
225
+ validated["id"] = str(t.get("id") or f"tg_local_{idx}")
226
+ return verifiers.sanitize_target_for_agent(validated)
227
+
228
+ @property
229
+ def targets(self) -> list[dict]:
230
+ with self._lock:
231
+ return list(self._targets)
232
+
233
+ def set_targets(self, targets: Sequence[dict]):
234
+ normalized = [self._normalize_local_target(t, i) for i, t in enumerate(targets)]
235
+ with self._lock:
236
+ self._targets = normalized
237
+
238
+ def sync_targets(self) -> list[dict]:
239
+ """Pull active/shadow/collecting MonitorTarget rules for this deployment from the console."""
240
+ if not self.transport:
241
+ return self.targets
242
+ out = self.transport.post("config", {"deployment_key": self.deployment_key})
243
+ fetched = out.get("targets") if isinstance(out.get("targets"), list) else []
244
+ with self._lock:
245
+ self._targets = fetched
246
+ self._last_sync = time.time()
247
+ self.last_error = REMOVED_NOTE if out.get("removed") else None # the console answered: an earlier connection error is over
248
+ self.removed = bool(out.get("removed"))
249
+ if self.removed:
250
+ self._queue.clear()
251
+ return list(fetched)
252
+
253
+ def evaluate_output(
254
+ self,
255
+ request_id: str,
256
+ output_text: str,
257
+ *,
258
+ prompt: str = "",
259
+ expected: str | None = None,
260
+ target_id: str | None = None,
261
+ tokens: int | None = None,
262
+ latency_ms: float | None = None,
263
+ source: str | None = None,
264
+ judge_fn: Callable[[str, str], str] | None = None,
265
+ first_token_ms: float | None = None,
266
+ served_model: str | None = None,
267
+ sys_fp: str | None = None,
268
+ task: str | None = None,
269
+ ) -> list[dict]:
270
+ """Run matching local verifiers on one reply and queue sanitized decision events, plus one summary of the
271
+ request (latency, time to first token, tokens, and the model name and system fingerprint the server reported)
272
+ for the console's health view."""
273
+ req_hash = hash_request_id(request_id)
274
+ self._served = str(served_model)[:120] if served_model else None
275
+ ev_source = source or self.source
276
+ with self._lock:
277
+ candidates = list(self._targets)
278
+ results = []
279
+ applicable = uncheckable = 0
280
+ explained = 0 # uncheckable targets that reported their own reason
281
+ for t in candidates:
282
+ if target_id and t["id"] != target_id:
283
+ continue
284
+ if t.get("stage") not in ("collecting", "validating", "shadow", "active"):
285
+ continue
286
+ if not verifiers.target_matches_deployment(t, self.deployment_key):
287
+ continue
288
+ if not verifiers.target_applies(t, prompt, task or self.task):
289
+ continue
290
+ applicable += 1
291
+ v = t["verifier"]
292
+ by_console = v["kind"] == "rubric_judge" and (t.get("judging") or {}).get("where") == "console" and self.transport is not None
293
+ if v["kind"] == "rubric_judge" and judge_fn is None and self.judge_fn is None and not by_console:
294
+ # Say so for this target, so the console can show that it is not being judged and why.
295
+ uncheckable += 1
296
+ if _sample_hit(req_hash, float((t.get("policy") or {}).get("sample_rate", 1.0))):
297
+ explained += 1
298
+ results.append(self.record_decision(req_hash, "abstain", prompt_text=prompt, reply_text=output_text, behavior=t["behavior_id"], target_id=t["id"], source=ev_source,
299
+ reason=NO_JUDGE_REASON, latency_ms=latency_ms, tokens=tokens))
300
+ continue
301
+ if (v["kind"] == "external_label" or (v["kind"] == "reference_match" and expected is None)):
302
+ uncheckable += 1 # labels come from elsewhere, or a judge / reference answer is not available here
303
+ continue
304
+ sample_rate = float((t.get("policy") or {}).get("sample_rate", 1.0))
305
+ if not _sample_hit(req_hash, sample_rate):
306
+ continue
307
+ if v["kind"] == "rubric_judge" and judge_fn is None: # judged in the background: by the console, or the client's own judge
308
+ results.append(self._judge_later(t, req_hash, output_text, prompt, ev_source, latency_ms, tokens, by_console=by_console))
309
+ continue
310
+ t0 = time.perf_counter_ns()
311
+ try:
312
+ failed, reason = verifiers.verify_output(v, output_text, prompt=prompt, expected=expected, judge_fn=judge_fn)
313
+ status = "alert" if failed else "no_alert"
314
+ except Exception as exc:
315
+ status = "abstain"
316
+ reason = f"verifier_error: {type(exc).__name__}"[:120]
317
+ scoring_ms = (time.perf_counter_ns() - t0) / 1e6
318
+ event = self.record_decision(
319
+ req_hash,
320
+ status,
321
+ prompt_text=prompt, reply_text=output_text,
322
+ behavior=t["behavior_id"],
323
+ target_id=t["id"],
324
+ source=ev_source,
325
+ reason=reason,
326
+ scoring_ms=scoring_ms,
327
+ latency_ms=latency_ms,
328
+ tokens=tokens,
329
+ )
330
+ results.append(event)
331
+ self.metrics.requests.inc(self.metrics.dep, ev_source, "false" if applicable == uncheckable else "true")
332
+ if latency_ms is not None:
333
+ self.metrics.latency.observe(float(latency_ms) / 1000, self.metrics.dep, ev_source)
334
+ if not target_id and applicable == uncheckable and not explained:
335
+ # Nothing could check this request. It is still reported (as abstain, with the reason) so the console shows
336
+ # that traffic arrives and that nothing checks it, instead of showing nothing at all.
337
+ reason = ("no active monitor target applies" if applicable == 0
338
+ else "the targets here need a judge model, a reference answer or external labels")
339
+ results.append(self.record_decision(req_hash, "abstain", prompt_text=prompt, reply_text=output_text, behavior=UNCHECKED, source=ev_source,
340
+ reason=reason, latency_ms=latency_ms, tokens=tokens))
341
+ if not target_id:
342
+ self.record_request(req_hash, latency_ms=latency_ms, first_token_ms=first_token_ms, tokens=tokens, served_model=served_model, sys_fp=sys_fp)
343
+ return results
344
+
345
+ def record_request(self, request_id: str, *, latency_ms: float | None = None, first_token_ms: float | None = None, tokens: int | None = None,
346
+ error: str | None = None, http_status: int | None = None, served_model: str | None = None, sys_fp: str | None = None) -> dict:
347
+ """Queue one summary of a whole request for the health view: how long it took, how long until the first token,
348
+ how many tokens, whether it failed (error: timeout, unreachable, http_4xx, http_5xx or client_error) and which
349
+ model answered. No text. Called by evaluate_output and by the proxy and SDK wrappers when a call fails."""
350
+ ev: dict[str, Any] = {"type": "request", "request_id": hash_request_id(request_id), "ts": time.time()}
351
+ for k, v in (("latency_ms", latency_ms), ("first_token_ms", first_token_ms), ("tokens", tokens), ("http_status", http_status)):
352
+ if v is not None:
353
+ ev[k] = float(v)
354
+ if error:
355
+ ev["error"] = error if error in ERROR_KINDS else "client_error"
356
+ if served_model:
357
+ ev["served_model"] = str(served_model)[:120]
358
+ if sys_fp:
359
+ ev["sys_fp"] = str(sys_fp)[:80]
360
+ if self.removed or not self._summaries_ok:
361
+ return ev
362
+ with self._lock:
363
+ self._queue.append(ev)
364
+ self._enforce_queue_cap_locked()
365
+ return ev
366
+
367
+ def record_decision(
368
+ self,
369
+ request_id: str,
370
+ status: str,
371
+ *,
372
+ behavior: str,
373
+ source: str | None = None,
374
+ reason: str | None = None,
375
+ target_id: str | None = None,
376
+ scoring_ms: float | None = None,
377
+ decision_ms: float | None = None,
378
+ first_token_ms: float | None = None,
379
+ latency_ms: float | None = None,
380
+ tokens: int | None = None,
381
+ evidence_id: str | None = None,
382
+ score: float | None = None,
383
+ threshold: float | None = None,
384
+ lens: dict | None = None,
385
+ prompt_text: str | None = None,
386
+ reply_text: str | None = None,
387
+ ) -> dict:
388
+ """Queue one sanitized monitoring decision (never prompt or reply text). `lens` (self-hosted agent only) carries
389
+ the logit lens's top tokens per layer, which are words derived from the prompt; see evalradar.lens."""
390
+ if status not in ("alert", "no_alert", "abstain"):
391
+ raise ValueError("status must be alert, no_alert or abstain")
392
+ event: dict[str, Any] = {
393
+ "request_id": hash_request_id(request_id),
394
+ "status": status,
395
+ "behavior": str(behavior)[:120],
396
+ "source": source or self.source,
397
+ "ts": time.time(),
398
+ }
399
+ if reason:
400
+ event["reason"] = str(reason)[:120]
401
+ if target_id:
402
+ event["target_id"] = str(target_id)[:40]
403
+ if evidence_id:
404
+ event["evidence_id"] = hash_request_id(evidence_id)
405
+ for k, v in (("scoring_ms", scoring_ms), ("decision_ms", decision_ms), ("first_token_ms", first_token_ms),
406
+ ("latency_ms", latency_ms), ("tokens", tokens), ("score", score), ("threshold", threshold)):
407
+ if v is not None:
408
+ event[k] = float(v)
409
+ if lens:
410
+ event["lens"] = lens
411
+ if getattr(self, "_served", None):
412
+ event["served_model"] = self._served
413
+ if self.send_text and (prompt_text or reply_text):
414
+ event["prompt"], event["reply"] = (prompt_text or "")[:PROMPT_CHARS], (reply_text or "")[:REPLY_CHARS]
415
+ self._remember(event, prompt_text, reply_text)
416
+ self.metrics.decisions.inc(self.metrics.dep, event["behavior"], status, event["source"])
417
+ if scoring_ms is not None:
418
+ self.metrics.scoring.observe(float(scoring_ms) / 1000, self.metrics.dep, event["behavior"])
419
+ should_flush = False
420
+ if self.removed: # counted locally (metrics above), not sent
421
+ return event
422
+ with self._lock:
423
+ self._queue.append(event)
424
+ dropped = self._enforce_queue_cap_locked()
425
+ should_flush = self.transport is not None and len(self._queue) >= self.batch_size
426
+ if dropped:
427
+ self.last_error = self._dropped_message(dropped)
428
+ if should_flush and self._worker is None:
429
+ try:
430
+ self.flush()
431
+ except Exception as exc:
432
+ self.last_error = str(exc)
433
+ return event
434
+
435
+ def flush(self) -> list[dict]:
436
+ """Send queued decision events to /api/ingest/events."""
437
+ with self._lock:
438
+ if not self._queue:
439
+ return []
440
+ if not self.transport:
441
+ return []
442
+ pending = self._queue[:]
443
+ self._queue.clear()
444
+ responses = []
445
+ for i in range(0, len(pending), 256):
446
+ chunk = pending[i:i + 256]
447
+ behaviors = {e["behavior"] for e in chunk if "behavior" in e} or {UNCHECKED}
448
+ payload = {
449
+ "version": SDK_VERSION,
450
+ "deployment": self.deployment,
451
+ "source": self.source,
452
+ "monitor": f"{self.source}:live",
453
+ "behavior": next(iter(behaviors)) if len(behaviors) == 1 else "multi_target",
454
+ "events": chunk,
455
+ }
456
+ try:
457
+ try:
458
+ responses.append(self.transport.post("events", payload))
459
+ except Exception as exc:
460
+ # A console from before request summaries rejects them: stop sending them and send the decisions.
461
+ if "HTTP 400" not in str(exc) or not any(e.get("type") == "request" for e in chunk):
462
+ raise
463
+ self._summaries_ok = False
464
+ chunk = [e for e in chunk if e.get("type") != "request"]
465
+ if chunk:
466
+ responses.append(self.transport.post("events", {**payload, "events": chunk}))
467
+ self.metrics.reports.inc(self.metrics.dep, "ok")
468
+ except Exception as exc:
469
+ self.metrics.reports.inc(self.metrics.dep, "error")
470
+ if "HTTP 410" in str(exc): # removed from monitoring in the console: drop, and stop sending until restored
471
+ with self._lock:
472
+ self._queue.clear()
473
+ self.removed, self.last_error = True, REMOVED_NOTE
474
+ return responses
475
+ with self._lock:
476
+ self._queue = chunk + pending[i + 256:] + self._queue
477
+ dropped = self._enforce_queue_cap_locked()
478
+ self.last_error = f"{exc}; {self._dropped_message(dropped)}" if dropped else str(exc)
479
+ raise
480
+ return responses
481
+
482
+ def _enforce_queue_cap_locked(self) -> int:
483
+ """Drop the oldest queued events beyond max_queue. Caller holds self._lock. Returns how many were dropped."""
484
+ over = len(self._queue) - self.max_queue
485
+ if over <= 0:
486
+ return 0
487
+ del self._queue[:over]
488
+ self.dropped += over
489
+ return over
490
+
491
+ def _dropped_message(self, n: int) -> str:
492
+ return (f"event queue full (max_queue={self.max_queue}): dropped {n} oldest event(s), "
493
+ f"{self.dropped} dropped in total")
494
+
495
+ def serve_metrics(self, port: int = 9464, host: str = "127.0.0.1"):
496
+ """Expose this client's Prometheus metrics at http://host:port/metrics (loopback by default). Returns the server."""
497
+ return telemetry.serve(self.metrics.registry, host, port)
498
+
499
+ def report_feedback(self, request_id: str, behavior: str, label: int, *, source: str = "human") -> dict:
500
+ """Report a ground-truth binary label (0=pass, 1=failure) keyed by hashed request id."""
501
+ if isinstance(label, bool) or label not in (0, 1):
502
+ raise ValueError("label must be 0 or 1")
503
+ item = {"request_id": hash_request_id(request_id), "dep_key": self.deployment_key,
504
+ "behavior": str(behavior)[:120], "label": int(label), "source": source, "ts": time.time()}
505
+ if not self.transport:
506
+ return {"ok": True, "stored": 0, "item": item}
507
+ return self.transport.post("feedback", {"items": [item]})
508
+
509
+ def upload_records(self, records: Sequence[dict]) -> int:
510
+ """Upload sanitized ledger records (verdicts, counts and digests; never raw prompts)."""
511
+ if not self.transport:
512
+ return 0
513
+ total = 0
514
+ rows = list(records)
515
+ for i in range(0, len(rows), 100):
516
+ total += int(self.transport.post("records", {"records": rows[i:i + 100]}).get("stored", 0))
517
+ return total
518
+
519
+ def wrap_openai(self, client: Any, *, target_id: str | None = None, source: str = "sdk") -> Any:
520
+ """Wrap an OpenAI-compatible client so chat.completions.create() is monitored transparently.
521
+
522
+ Works with sync clients (``openai.OpenAI``) and async clients (``openai.AsyncOpenAI``): when
523
+ ``create()`` returns an awaitable, the wrapper returns a coroutine that awaits the real response
524
+ and then evaluates it. ``stream=True`` responses are wrapped so chunks reach the caller unchanged
525
+ and in real time; the accumulated reply is evaluated once when the stream ends or is closed.
526
+ A stream abandoned mid-way without ``close()`` or a ``with`` block is not evaluated.
527
+ """
528
+ monitor = self
529
+
530
+ class _CompletionsProxy:
531
+ def __init__(self, inner):
532
+ self._inner = inner
533
+ if inspect.iscoroutinefunction(getattr(inner, "create", None)):
534
+ self.create = self._create_async # keeps iscoroutinefunction() true for callers that check
535
+
536
+ def create(self, *args, **kwargs):
537
+ t0 = time.perf_counter_ns()
538
+ try:
539
+ resp = self._inner.create(*args, **kwargs)
540
+ except Exception as exc:
541
+ monitor._record_failure(exc, t0)
542
+ raise
543
+ if inspect.isawaitable(resp):
544
+ return monitor._monitor_awaitable(resp, t0, kwargs, target_id, source)
545
+ return monitor._monitor_response(resp, t0, kwargs, target_id, source)
546
+
547
+ async def _create_async(self, *args, **kwargs):
548
+ t0 = time.perf_counter_ns()
549
+ try:
550
+ resp = self._inner.create(*args, **kwargs)
551
+ except Exception as exc:
552
+ monitor._record_failure(exc, t0)
553
+ raise
554
+ if inspect.isawaitable(resp):
555
+ return await monitor._monitor_awaitable(resp, t0, kwargs, target_id, source)
556
+ return monitor._monitor_response(resp, t0, kwargs, target_id, source)
557
+
558
+ def __getattr__(self, name):
559
+ return getattr(self._inner, name)
560
+
561
+ class _ChatProxy:
562
+ def __init__(self, inner):
563
+ self._inner = inner
564
+ self.completions = _CompletionsProxy(inner.completions)
565
+
566
+ def __getattr__(self, name):
567
+ return getattr(self._inner, name)
568
+
569
+ class _ClientProxy:
570
+ def __init__(self, inner):
571
+ self._inner = inner
572
+ self.chat = _ChatProxy(inner.chat)
573
+
574
+ def __getattr__(self, name):
575
+ return getattr(self._inner, name)
576
+
577
+ return _ClientProxy(client)
578
+
579
+ def wrap_anthropic(self, client: Any, *, target_id: str | None = None, source: str = "sdk") -> Any:
580
+ """Wrap an Anthropic client (``anthropic.Anthropic`` or ``AsyncAnthropic``) so Claude calls are monitored.
581
+
582
+ ``messages.create`` is monitored with and without ``stream=True``, sync and async. The
583
+ ``messages.stream(...)`` helper is monitored when its ``with`` / ``async with`` block ends: the final
584
+ text is read from the stream then. Everything else is passed through unchanged."""
585
+ monitor = self
586
+
587
+ class _StreamManager:
588
+ def __init__(self, inner, kwargs):
589
+ self._inner, self._kwargs, self._t0, self._stream = inner, kwargs, time.perf_counter_ns(), None
590
+
591
+ def _evaluate(self):
592
+ try:
593
+ msg = self._stream.get_final_message()
594
+ monitor._monitor_response(msg, self._t0, {**self._kwargs, "stream": False}, target_id, source)
595
+ except Exception as exc: # an unfinished or failed stream has no final message
596
+ monitor.last_error = f"stream evaluation failed: {type(exc).__name__}: {exc}"[:300]
597
+
598
+ def __enter__(self):
599
+ self._stream = self._inner.__enter__()
600
+ return self._stream
601
+
602
+ def __exit__(self, *exc):
603
+ out = self._inner.__exit__(*exc)
604
+ if exc[0] is None:
605
+ self._evaluate()
606
+ return out
607
+
608
+ async def __aenter__(self):
609
+ self._stream = await self._inner.__aenter__()
610
+ return self._stream
611
+
612
+ async def __aexit__(self, *exc):
613
+ out = await self._inner.__aexit__(*exc)
614
+ if exc[0] is None:
615
+ try:
616
+ msg = await self._stream.get_final_message()
617
+ monitor._monitor_response(msg, self._t0, {**self._kwargs, "stream": False}, target_id, source)
618
+ except Exception as e:
619
+ monitor.last_error = f"stream evaluation failed: {type(e).__name__}: {e}"[:300]
620
+ return out
621
+
622
+ def __getattr__(self, name):
623
+ return getattr(self._inner, name)
624
+
625
+ class _MessagesProxy:
626
+ def __init__(self, inner):
627
+ self._inner = inner
628
+ if inspect.iscoroutinefunction(getattr(inner, "create", None)):
629
+ self.create = self._create_async
630
+
631
+ def create(self, *args, **kwargs):
632
+ t0 = time.perf_counter_ns()
633
+ try:
634
+ resp = self._inner.create(*args, **kwargs)
635
+ except Exception as exc:
636
+ monitor._record_failure(exc, t0)
637
+ raise
638
+ if inspect.isawaitable(resp):
639
+ return monitor._monitor_awaitable(resp, t0, kwargs, target_id, source)
640
+ return monitor._monitor_response(resp, t0, kwargs, target_id, source)
641
+
642
+ async def _create_async(self, *args, **kwargs):
643
+ t0 = time.perf_counter_ns()
644
+ try:
645
+ resp = self._inner.create(*args, **kwargs)
646
+ except Exception as exc:
647
+ monitor._record_failure(exc, t0)
648
+ raise
649
+ if inspect.isawaitable(resp):
650
+ return await monitor._monitor_awaitable(resp, t0, kwargs, target_id, source)
651
+ return monitor._monitor_response(resp, t0, kwargs, target_id, source)
652
+
653
+ def stream(self, *args, **kwargs):
654
+ return _StreamManager(self._inner.stream(*args, **kwargs), kwargs)
655
+
656
+ def __getattr__(self, name):
657
+ return getattr(self._inner, name)
658
+
659
+ class _ClientProxy:
660
+ def __init__(self, inner):
661
+ self._inner = inner
662
+ self.messages = _MessagesProxy(inner.messages)
663
+
664
+ def __getattr__(self, name):
665
+ return getattr(self._inner, name)
666
+
667
+ return _ClientProxy(client)
668
+
669
+ def wrap_async_openai(self, client: Any, *, target_id: str | None = None, source: str = "sdk") -> Any:
670
+ """Alias of wrap_openai for ``openai.AsyncOpenAI``-style clients (wrap_openai handles both)."""
671
+ return self.wrap_openai(client, target_id=target_id, source=source)
672
+
673
+ async def _monitor_awaitable(self, awaitable: Any, t0: int, kwargs: dict, target_id: str | None, source: str) -> Any:
674
+ try:
675
+ resp = await awaitable
676
+ except Exception as exc:
677
+ self._record_failure(exc, t0)
678
+ raise
679
+ return self._monitor_response(resp, t0, kwargs, target_id, source)
680
+
681
+ def _record_failure(self, exc: BaseException, t0: int) -> None:
682
+ """A model call that raised: counted in the health view as an error of its kind. Never raises itself."""
683
+ try:
684
+ kind, status = error_kind(exc)
685
+ self.record_request(f"err-{time.time_ns()}", latency_ms=(time.perf_counter_ns() - t0) / 1e6, error=kind, http_status=status)
686
+ except Exception:
687
+ pass
688
+
689
+ def _monitor_response(self, resp: Any, t0: int, kwargs: dict, target_id: str | None, source: str) -> Any:
690
+ """Evaluate a completed response, or wrap a streaming one. Returns what the caller should receive."""
691
+ latency_ms = (time.perf_counter_ns() - t0) / 1e6
692
+ prompt = _prompt_from_kwargs(kwargs)
693
+ if kwargs.get("stream") and not (isinstance(resp, dict) and ("choices" in resp or "content" in resp)):
694
+ if hasattr(resp, "__aiter__"):
695
+ return _AsyncMonitoredStream(resp, self, t0, prompt, target_id, source, _task_of(kwargs))
696
+ if hasattr(resp, "__iter__") or hasattr(resp, "__next__"):
697
+ return _MonitoredStream(resp, self, t0, prompt, target_id, source, _task_of(kwargs))
698
+ return resp
699
+ req_id = _field(resp, "id") or f"req-{time.time_ns()}"
700
+ try:
701
+ text, tokens = _reply_of(resp)
702
+ except Exception:
703
+ text, tokens = "", None
704
+ model, fp = _field(resp, "model"), _field(resp, "system_fingerprint")
705
+ self.evaluate_output(str(req_id), str(text), prompt=prompt, target_id=target_id, tokens=tokens,
706
+ latency_ms=latency_ms, source=source, served_model=model if isinstance(model, str) else None,
707
+ sys_fp=fp if isinstance(fp, str) else None, task=_task_of(kwargs))
708
+ return resp
709
+
710
+ def _loop(self):
711
+ while not self._stop.wait(self.flush_interval):
712
+ try:
713
+ if time.time() - self._last_sync >= self.sync_interval:
714
+ self.sync_targets()
715
+ self.flush()
716
+ except Exception as exc:
717
+ self.last_error = str(exc)
718
+
719
+ def _judge_later(self, t: dict, req_hash: str, text: str, prompt: str, source: str, latency_ms, tokens, *, by_console: bool = False) -> dict:
720
+ """Queue one rubric judgement. Returns a placeholder; the decision is recorded when the judge answers. With
721
+ by_console, the prompt and reply of this sampled request go to the console, which judges them (the target was
722
+ set to console judging by a workspace admin) and keeps only the verdict."""
723
+ with self._judge_lock:
724
+ busy = self._judge_pending >= self._judge_backlog
725
+ if not busy:
726
+ self._judge_pending += 1
727
+ if busy: # more replies than the judge can keep up with: skip this one and say so
728
+ return self.record_decision(req_hash, "abstain", prompt_text=prompt, reply_text=text, behavior=t["behavior_id"], target_id=t["id"], source=source,
729
+ reason="judge busy: this reply was not judged", latency_ms=latency_ms, tokens=tokens)
730
+
731
+ def job():
732
+ t0 = time.perf_counter_ns()
733
+ try:
734
+ if by_console:
735
+ out = self.transport.post("judge", {"target_id": t["id"], "prompt": prompt or "", "reply": text or ""})
736
+ failed, reason = bool(out["failed"]), str(out.get("reason") or "")[:100] + " (judged by the console)"
737
+ else:
738
+ failed, reason = verifiers.verify_output(t["verifier"], text, prompt=prompt, judge_fn=self.judge_fn)
739
+ status = "alert" if failed else "no_alert"
740
+ except Exception as exc:
741
+ status, reason = "abstain", f"judge_error: {type(exc).__name__}"[:120]
742
+ finally:
743
+ with self._judge_lock:
744
+ self._judge_pending -= 1
745
+ self.record_decision(req_hash, status, prompt_text=prompt, reply_text=text, behavior=t["behavior_id"], target_id=t["id"], source=source, reason=reason,
746
+ scoring_ms=(time.perf_counter_ns() - t0) / 1e6, latency_ms=latency_ms, tokens=tokens)
747
+ if self._judge_pool is None: # first console-judged reply of a client without its own judge
748
+ self._judge_pool = ThreadPoolExecutor(2, thread_name_prefix="evalradar-judge")
749
+ self._judge_pool.submit(job)
750
+ return {"request_id": req_hash, "status": "pending", "behavior": t["behavior_id"], "target_id": t["id"], "source": source}
751
+
752
+ def _remember(self, event: dict, prompt_text, reply_text):
753
+ """Keep the latest requests on this machine (text included, whatever send_text says) for local reading."""
754
+ with self._lock:
755
+ for r in self.recent:
756
+ if r["request_id"] == event["request_id"]:
757
+ r["checks"].append({k: event.get(k) for k in ("behavior", "status", "reason", "score", "threshold")})
758
+ return
759
+ self.recent.append({"request_id": event["request_id"], "ts": event["ts"], "prompt": (prompt_text or "")[:PROMPT_CHARS],
760
+ "reply": (reply_text or "")[:REPLY_CHARS], "sent_text": self.send_text,
761
+ "checks": [{k: event.get(k) for k in ("behavior", "status", "reason", "score", "threshold")}]})
762
+
763
+ def local_requests(self) -> list[dict]:
764
+ """The most recent requests seen here, newest first, with their text and every check's decision."""
765
+ with self._lock:
766
+ return list(reversed(self.recent))
767
+
768
+ def wait_for_judge(self, timeout: float = 60.0) -> bool:
769
+ """Block until queued judgements are done (scripts and tests). True when none is left."""
770
+ end = time.time() + timeout
771
+ while time.time() < end:
772
+ with self._judge_lock:
773
+ if not self._judge_pending:
774
+ return True
775
+ time.sleep(0.02)
776
+ return False
777
+
778
+ def close(self):
779
+ if self._judge_pool is not None: # judgements already queued finish (each bounded by the judge's timeout)
780
+ self._judge_pool.shutdown(wait=True)
781
+ self._stop.set()
782
+ if self._worker is not None:
783
+ self._worker.join(timeout=3.0)
784
+ try:
785
+ self.flush()
786
+ except Exception as exc:
787
+ self.last_error = str(exc)
788
+
789
+ def __enter__(self) -> "MonitorClient":
790
+ return self
791
+
792
+ def __exit__(self, *_exc):
793
+ self.close()
794
+
795
+
796
+ def _field(obj: Any, name: str) -> Any:
797
+ """Read ``name`` from an SDK object or from a plain dict (OpenAI-compatible JSON)."""
798
+ if obj is None:
799
+ return None
800
+ if isinstance(obj, dict):
801
+ return obj.get(name)
802
+ return getattr(obj, name, None)
803
+
804
+
805
+ def _text_of(content: Any) -> str:
806
+ """Text of a message content: a string, or a list of blocks (Anthropic, OpenAI multi-part) whose text parts are joined."""
807
+ if isinstance(content, str):
808
+ return content
809
+ if isinstance(content, list):
810
+ parts = []
811
+ for block in content:
812
+ if _field(block, "type") in (None, "text", "output_text", "input_text"):
813
+ text = _field(block, "text")
814
+ if isinstance(text, str):
815
+ parts.append(text)
816
+ return "".join(parts)
817
+ return ""
818
+
819
+
820
+ def _prompt_from_kwargs(kwargs: dict) -> str:
821
+ messages = kwargs.get("messages") or []
822
+ if isinstance(messages, list) and messages:
823
+ last = messages[-1]
824
+ return _text_of(last.get("content", "")) if isinstance(last, dict) else ""
825
+ return ""
826
+
827
+
828
+ TASK_HEADER = "X-EvalRadar-Task"
829
+
830
+
831
+ def _task_of(kwargs: dict) -> str | None:
832
+ """The task a wrapped call names: extra_headers={"X-EvalRadar-Task": "support"}, as with the proxy."""
833
+ headers = kwargs.get("extra_headers") if isinstance(kwargs.get("extra_headers"), dict) else {}
834
+ for k, v in headers.items():
835
+ if str(k).lower() == TASK_HEADER.lower() and v:
836
+ return str(v).strip().lower()[:40]
837
+ return None
838
+
839
+
840
+ def _reply_of(resp: Any) -> tuple[str, Any]:
841
+ """(reply text, completion tokens) of a finished response: OpenAI chat completion or Anthropic message."""
842
+ choices = _field(resp, "choices")
843
+ if choices:
844
+ return str(_field(_field(choices[0], "message"), "content") or ""), _field(_field(resp, "usage"), "completion_tokens")
845
+ content = _field(resp, "content")
846
+ if isinstance(content, list):
847
+ return _text_of(content), _field(_field(resp, "usage"), "output_tokens")
848
+ return "", None
849
+
850
+
851
+ class _StreamAccumulator:
852
+ """Collects streamed delta text and evaluates the full reply exactly once when the stream ends."""
853
+
854
+ def __init__(self, inner: Any, monitor: MonitorClient, t0: int, prompt: str, target_id: str | None, source: str, task: str | None = None):
855
+ self._inner = inner
856
+ self._task = task
857
+ self._monitor = monitor
858
+ self._t0 = t0
859
+ self._prompt = prompt
860
+ self._target_id = target_id
861
+ self._source = source
862
+ self._parts: list[str] = []
863
+ self._content_chunks = 0
864
+ self._request_id: str | None = None
865
+ self._usage_tokens: Any = None
866
+ self._first_ms: float | None = None
867
+ self._model: str | None = None
868
+ self._sys_fp: str | None = None
869
+ self._done = False
870
+ self._done_lock = threading.Lock()
871
+
872
+ def _observe(self, chunk: Any) -> None:
873
+ try:
874
+ if self._request_id is None:
875
+ cid = _field(chunk, "id")
876
+ if cid:
877
+ self._request_id = str(cid)
878
+ kind = _field(chunk, "type")
879
+ if self._model is None:
880
+ m = _field(chunk, "model") or _field(_field(chunk, "message"), "model")
881
+ if isinstance(m, str):
882
+ self._model = m
883
+ if self._sys_fp is None and isinstance(_field(chunk, "system_fingerprint"), str):
884
+ self._sys_fp = _field(chunk, "system_fingerprint")
885
+ if kind == "message_start" and self._request_id is None: # Anthropic stream events
886
+ mid = _field(_field(chunk, "message"), "id")
887
+ if mid:
888
+ self._request_id = str(mid)
889
+ usage = _field(chunk, "usage")
890
+ if usage is not None:
891
+ ct = _field(usage, "completion_tokens")
892
+ if ct is None:
893
+ ct = _field(usage, "output_tokens")
894
+ if ct is not None:
895
+ self._usage_tokens = ct
896
+ if kind == "content_block_delta":
897
+ text = _field(_field(chunk, "delta"), "text")
898
+ if text:
899
+ self._parts.append(str(text))
900
+ self._content_chunks += 1
901
+ choices = _field(chunk, "choices") or []
902
+ if choices:
903
+ content = _field(_field(choices[0], "delta"), "content")
904
+ if content:
905
+ self._parts.append(str(content))
906
+ self._content_chunks += 1
907
+ if self._first_ms is None and self._content_chunks:
908
+ self._first_ms = (time.perf_counter_ns() - self._t0) / 1e6
909
+ except Exception as exc: # a malformed chunk must never break the caller's iteration
910
+ self._monitor.last_error = f"stream chunk parse failed: {type(exc).__name__}: {exc}"[:300]
911
+
912
+ def _finish(self) -> None:
913
+ with self._done_lock:
914
+ if self._done:
915
+ return
916
+ self._done = True
917
+ try:
918
+ latency_ms = (time.perf_counter_ns() - self._t0) / 1e6
919
+ tokens = self._usage_tokens if self._usage_tokens is not None else self._content_chunks
920
+ req_id = self._request_id or f"req-{time.time_ns()}"
921
+ self._monitor.evaluate_output(req_id, "".join(self._parts), prompt=self._prompt, target_id=self._target_id,
922
+ tokens=tokens, latency_ms=latency_ms, source=self._source, first_token_ms=self._first_ms,
923
+ served_model=self._model, sys_fp=self._sys_fp, task=self._task)
924
+ except Exception as exc:
925
+ self._monitor.last_error = f"stream evaluation failed: {type(exc).__name__}: {exc}"[:300]
926
+ finally:
927
+ self._parts = []
928
+
929
+ def __getattr__(self, name):
930
+ inner = self.__dict__.get("_inner")
931
+ if inner is None:
932
+ raise AttributeError(name)
933
+ return getattr(inner, name)
934
+
935
+
936
+ class _MonitoredStream(_StreamAccumulator):
937
+ """Sync stream wrapper: iterates, closes and works as a context manager like the wrapped stream."""
938
+
939
+ def __init__(self, *args, **kwargs):
940
+ super().__init__(*args, **kwargs)
941
+ self._source_obj = self._inner
942
+ self._it: Any = None
943
+
944
+ def __iter__(self):
945
+ return self
946
+
947
+ def __next__(self):
948
+ if self._it is None:
949
+ src = self._source_obj
950
+ self._it = src if not hasattr(src, "__iter__") and hasattr(src, "__next__") else iter(src)
951
+ try:
952
+ chunk = next(self._it)
953
+ except StopIteration:
954
+ self._finish()
955
+ raise
956
+ except BaseException:
957
+ self._finish() # evaluate whatever already reached the caller before the upstream error
958
+ raise
959
+ self._observe(chunk)
960
+ return chunk
961
+
962
+ def close(self):
963
+ try:
964
+ closer = getattr(self._inner, "close", None)
965
+ if callable(closer):
966
+ return closer()
967
+ finally:
968
+ self._finish()
969
+
970
+ def __enter__(self):
971
+ enter = getattr(self._inner, "__enter__", None)
972
+ if callable(enter):
973
+ entered = enter()
974
+ if entered is not None and entered is not self._inner:
975
+ self._source_obj = entered
976
+ return self
977
+
978
+ def __exit__(self, *exc):
979
+ try:
980
+ exit_ = getattr(self._inner, "__exit__", None)
981
+ if callable(exit_):
982
+ return exit_(*exc)
983
+ closer = getattr(self._inner, "close", None)
984
+ if callable(closer):
985
+ closer()
986
+ return None
987
+ finally:
988
+ self._finish()
989
+
990
+
991
+ class _AsyncMonitoredStream(_StreamAccumulator):
992
+ """Async stream wrapper: ``async for``, ``await close()`` and ``async with`` like the wrapped stream."""
993
+
994
+ def __init__(self, *args, **kwargs):
995
+ super().__init__(*args, **kwargs)
996
+ self._source_obj = self._inner
997
+ self._it: Any = None
998
+
999
+ def __aiter__(self):
1000
+ return self
1001
+
1002
+ async def __anext__(self):
1003
+ if self._it is None:
1004
+ self._it = self._source_obj.__aiter__()
1005
+ try:
1006
+ chunk = await self._it.__anext__()
1007
+ except StopAsyncIteration:
1008
+ self._finish()
1009
+ raise
1010
+ except BaseException:
1011
+ self._finish()
1012
+ raise
1013
+ self._observe(chunk)
1014
+ return chunk
1015
+
1016
+ async def close(self):
1017
+ try:
1018
+ closer = getattr(self._inner, "close", None) or getattr(self._inner, "aclose", None)
1019
+ if callable(closer):
1020
+ out = closer()
1021
+ if inspect.isawaitable(out):
1022
+ out = await out
1023
+ return out
1024
+ finally:
1025
+ self._finish()
1026
+
1027
+ aclose = close
1028
+
1029
+ async def __aenter__(self):
1030
+ enter = getattr(self._inner, "__aenter__", None)
1031
+ if callable(enter):
1032
+ entered = await enter()
1033
+ if entered is not None and entered is not self._inner:
1034
+ self._source_obj = entered
1035
+ return self
1036
+
1037
+ async def __aexit__(self, *exc):
1038
+ try:
1039
+ exit_ = getattr(self._inner, "__aexit__", None)
1040
+ if callable(exit_):
1041
+ return await exit_(*exc)
1042
+ await self.close()
1043
+ return None
1044
+ finally:
1045
+ self._finish()