ai-eval-platform 1.0.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.
- ai_eval/__init__.py +6 -0
- ai_eval/_version.py +2 -0
- ai_eval/cli.py +139 -0
- ai_eval/client.py +157 -0
- ai_eval/gate.py +134 -0
- ai_eval/monitor.py +107 -0
- ai_eval/py.typed +0 -0
- ai_eval/tracing.py +166 -0
- ai_eval_platform-1.0.0.dist-info/METADATA +162 -0
- ai_eval_platform-1.0.0.dist-info/RECORD +14 -0
- ai_eval_platform-1.0.0.dist-info/WHEEL +5 -0
- ai_eval_platform-1.0.0.dist-info/entry_points.txt +2 -0
- ai_eval_platform-1.0.0.dist-info/licenses/LICENSE +202 -0
- ai_eval_platform-1.0.0.dist-info/top_level.txt +1 -0
ai_eval/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"""Python SDK and CLI for the AI Evaluation Platform."""
|
|
2
|
+
from ai_eval._version import __version__
|
|
3
|
+
from ai_eval.client import ApiError, Client
|
|
4
|
+
from ai_eval.gate import GateResult, evaluate_gate, run_stats
|
|
5
|
+
|
|
6
|
+
__all__ = ["ApiError", "Client", "GateResult", "evaluate_gate", "run_stats", "__version__"]
|
ai_eval/_version.py
ADDED
ai_eval/cli.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""
|
|
2
|
+
`ai-eval` command line. Exit codes: 0 gate passed, 1 gate failed, 2 error.
|
|
3
|
+
|
|
4
|
+
ai-eval run --project P --dataset D --outputs outputs.json \
|
|
5
|
+
--fail-under pass_rate=0.9 --metric factual_accuracy=0.8
|
|
6
|
+
|
|
7
|
+
Credentials: AI_EVAL_API_KEY (or --api-key); API URL: AI_EVAL_API_URL (or --api-url).
|
|
8
|
+
"""
|
|
9
|
+
import argparse
|
|
10
|
+
import csv
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import sys
|
|
14
|
+
from typing import Dict, List, Optional
|
|
15
|
+
|
|
16
|
+
from ai_eval._version import __version__
|
|
17
|
+
from ai_eval.client import ApiError, Client
|
|
18
|
+
from ai_eval.gate import GATE_NAMES, evaluate_gate, format_report, parse_conditions
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _load_json_or_jsonl(path: str):
|
|
22
|
+
with open(path, encoding="utf-8") as f:
|
|
23
|
+
text = f.read()
|
|
24
|
+
if path.endswith(".jsonl"):
|
|
25
|
+
return [json.loads(line) for line in text.splitlines() if line.strip()]
|
|
26
|
+
return json.loads(text)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def load_outputs(path: str) -> Dict[str, str]:
|
|
30
|
+
"""{case_id: output}, a JSON list of {case_id, llm_output}, JSONL of the same, or a CSV."""
|
|
31
|
+
if path.endswith(".csv"):
|
|
32
|
+
with open(path, encoding="utf-8-sig", newline="") as f:
|
|
33
|
+
rows = list(csv.DictReader(f))
|
|
34
|
+
else:
|
|
35
|
+
data = _load_json_or_jsonl(path)
|
|
36
|
+
if isinstance(data, dict):
|
|
37
|
+
return {str(k): str(v) for k, v in data.items()}
|
|
38
|
+
rows = data
|
|
39
|
+
out = {}
|
|
40
|
+
for r in rows:
|
|
41
|
+
cid = r.get("case_id") or r.get("id")
|
|
42
|
+
text = r.get("llm_output") or r.get("output") or r.get("response")
|
|
43
|
+
if cid is not None and text is not None:
|
|
44
|
+
out[str(cid)] = str(text)
|
|
45
|
+
return out
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def load_cases(path: str) -> List[dict]:
|
|
49
|
+
data = _load_json_or_jsonl(path)
|
|
50
|
+
cases = data.get("cases", data) if isinstance(data, dict) else data
|
|
51
|
+
for i, c in enumerate(cases, start=1):
|
|
52
|
+
c.setdefault("case_id", str(i))
|
|
53
|
+
c.setdefault("prompt", "")
|
|
54
|
+
return cases
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
58
|
+
p = argparse.ArgumentParser(prog="ai-eval", description="AI Evaluation Platform CLI")
|
|
59
|
+
p.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
60
|
+
p.add_argument("--api-key", default=None, help="Default: $AI_EVAL_API_KEY")
|
|
61
|
+
p.add_argument("--api-url", default=None, help="Default: $AI_EVAL_API_URL or the public API")
|
|
62
|
+
sub = p.add_subparsers(dest="command", required=True)
|
|
63
|
+
|
|
64
|
+
r = sub.add_parser("run", help="Evaluate a run and apply a quality gate")
|
|
65
|
+
src = r.add_mutually_exclusive_group(required=True)
|
|
66
|
+
src.add_argument("--dataset", help="Dataset id to evaluate")
|
|
67
|
+
src.add_argument("--file", help="Cases as .json/.jsonl (list of cases) or .csv/.xlsx (uploaded as-is)")
|
|
68
|
+
src.add_argument("--job", help="Skip submitting: gate an existing run by job id")
|
|
69
|
+
r.add_argument("--dataset-version", type=int, help="Default: the latest version")
|
|
70
|
+
r.add_argument("--outputs", help="Outputs for dataset rows: JSON {case_id: output}, JSONL or CSV")
|
|
71
|
+
r.add_argument("--project", help="Project id (its metrics and thresholds apply)")
|
|
72
|
+
r.add_argument("--metrics", help="Comma-separated metric keys (default: the project's metrics)")
|
|
73
|
+
r.add_argument("--run-name", default=os.environ.get("AI_EVAL_RUN_NAME"))
|
|
74
|
+
r.add_argument("--version-label", help="Version label recorded on the run, e.g. a git SHA")
|
|
75
|
+
r.add_argument("--version-model", help="Model behind this version")
|
|
76
|
+
r.add_argument("--version-prompt-file", help="File with the system prompt (hashed into the version)")
|
|
77
|
+
r.add_argument("--fail-under", action="append", default=[],
|
|
78
|
+
help=f"NAME=VALUE gate, NAME in {', '.join(GATE_NAMES)} (repeatable)")
|
|
79
|
+
r.add_argument("--metric", action="append", default=[],
|
|
80
|
+
help="KEY=VALUE: metric KEY must average >= VALUE (also its pass mark) (repeatable)")
|
|
81
|
+
r.add_argument("--timeout", type=float, default=1800, help="Seconds to wait for the run (default 1800)")
|
|
82
|
+
r.add_argument("--report-json", help="Write the gate result as JSON to this path")
|
|
83
|
+
return p
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def cmd_run(args, client: Client) -> int:
|
|
87
|
+
fail_under = parse_conditions(args.fail_under, GATE_NAMES)
|
|
88
|
+
metric_marks = parse_conditions(args.metric)
|
|
89
|
+
metrics = [m.strip() for m in args.metrics.split(",")] if args.metrics else None
|
|
90
|
+
if metrics is None and args.project:
|
|
91
|
+
metrics = client.get_project(args.project).get("metrics") or None
|
|
92
|
+
version = None
|
|
93
|
+
if args.version_label:
|
|
94
|
+
version = {"label": args.version_label, "model": args.version_model}
|
|
95
|
+
if args.version_prompt_file:
|
|
96
|
+
with open(args.version_prompt_file, encoding="utf-8") as f:
|
|
97
|
+
version["prompt"] = f.read()
|
|
98
|
+
version = {k: v for k, v in version.items() if v}
|
|
99
|
+
|
|
100
|
+
if args.job:
|
|
101
|
+
job_id = args.job
|
|
102
|
+
elif args.dataset:
|
|
103
|
+
outputs = load_outputs(args.outputs) if args.outputs else None
|
|
104
|
+
job_id = client.evaluate_batch(dataset_id=args.dataset, dataset_version=args.dataset_version,
|
|
105
|
+
outputs=outputs, metrics=metrics, project_id=args.project,
|
|
106
|
+
run_name=args.run_name, version=version)["job_id"]
|
|
107
|
+
elif args.file.endswith((".csv", ".xlsx", ".xls")):
|
|
108
|
+
job_id = client.evaluate_file(args.file, metrics=metrics, project_id=args.project,
|
|
109
|
+
run_name=args.run_name, version=version)["job_id"]
|
|
110
|
+
else:
|
|
111
|
+
job_id = client.evaluate_batch(load_cases(args.file), metrics=metrics, project_id=args.project,
|
|
112
|
+
run_name=args.run_name, version=version)["job_id"]
|
|
113
|
+
print(f"Run {job_id} submitted, waiting for results...", file=sys.stderr)
|
|
114
|
+
|
|
115
|
+
results = client.wait_for_results(job_id, timeout=args.timeout)
|
|
116
|
+
gate = evaluate_gate(results, fail_under, metric_marks)
|
|
117
|
+
print(format_report(gate, results.get("run")))
|
|
118
|
+
if args.report_json:
|
|
119
|
+
with open(args.report_json, "w", encoding="utf-8") as f:
|
|
120
|
+
json.dump({"job_id": job_id, "passed": gate.passed, "stats": gate.stats,
|
|
121
|
+
"checks": [{"name": c.name, "actual": c.actual, "required": c.required, "ok": c.ok}
|
|
122
|
+
for c in gate.checks]}, f, indent=2)
|
|
123
|
+
return 0 if gate.passed else 1
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def main(argv: Optional[List[str]] = None, client: Optional[Client] = None) -> int:
|
|
127
|
+
args = build_parser().parse_args(argv)
|
|
128
|
+
try:
|
|
129
|
+
client = client or Client(api_key=args.api_key, base_url=args.api_url)
|
|
130
|
+
if args.command == "run":
|
|
131
|
+
return cmd_run(args, client)
|
|
132
|
+
except (ValueError, ApiError, RuntimeError, TimeoutError, OSError) as e:
|
|
133
|
+
print(f"ai-eval: error: {e}", file=sys.stderr)
|
|
134
|
+
return 2
|
|
135
|
+
return 2
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
if __name__ == "__main__":
|
|
139
|
+
sys.exit(main())
|
ai_eval/client.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Minimal HTTP client for the AI Evaluation Platform API (standard library only).
|
|
3
|
+
|
|
4
|
+
from ai_eval import Client
|
|
5
|
+
c = Client(api_key="...", base_url="https://api.ai-evaluation-platform.com")
|
|
6
|
+
job = c.evaluate_batch(cases=[{"case_id": "1", "prompt": "...", "llm_output": "..."}],
|
|
7
|
+
project_id="...", run_name="ci")
|
|
8
|
+
results = c.wait_for_results(job["job_id"])
|
|
9
|
+
"""
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import time
|
|
13
|
+
import urllib.error
|
|
14
|
+
import urllib.request
|
|
15
|
+
import uuid
|
|
16
|
+
from typing import Any, Dict, Iterable, List, Optional
|
|
17
|
+
|
|
18
|
+
from ai_eval._version import __version__
|
|
19
|
+
|
|
20
|
+
DEFAULT_BASE_URL = "https://api.ai-evaluation-platform.com"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ApiError(Exception):
|
|
24
|
+
def __init__(self, status: int, detail: str):
|
|
25
|
+
super().__init__(f"HTTP {status}: {detail}")
|
|
26
|
+
self.status = status
|
|
27
|
+
self.detail = detail
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Client:
|
|
31
|
+
def __init__(self, api_key: Optional[str] = None, base_url: Optional[str] = None, timeout: float = 60.0):
|
|
32
|
+
self.api_key = api_key or os.environ.get("AI_EVAL_API_KEY", "")
|
|
33
|
+
if not self.api_key:
|
|
34
|
+
raise ValueError("No API key: pass api_key= or set AI_EVAL_API_KEY")
|
|
35
|
+
self.base_url = (base_url or os.environ.get("AI_EVAL_API_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
36
|
+
self.timeout = timeout
|
|
37
|
+
|
|
38
|
+
# -- transport --------------------------------------------------------------
|
|
39
|
+
|
|
40
|
+
def request(self, method: str, path: str, body: Any = None, *, raw: Optional[bytes] = None,
|
|
41
|
+
content_type: str = "application/json", retries: int = 3) -> Any:
|
|
42
|
+
data = raw if raw is not None else (json.dumps(body).encode("utf-8") if body is not None else None)
|
|
43
|
+
headers = {"X-API-Key": self.api_key, "Accept": "application/json", "User-Agent": f"ai-eval-sdk/{__version__}"}
|
|
44
|
+
if data is not None:
|
|
45
|
+
headers["Content-Type"] = content_type
|
|
46
|
+
for attempt in range(retries + 1):
|
|
47
|
+
req = urllib.request.Request(self.base_url + path, data=data, method=method, headers=headers)
|
|
48
|
+
try:
|
|
49
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
|
50
|
+
text = resp.read().decode("utf-8")
|
|
51
|
+
return json.loads(text) if text else None
|
|
52
|
+
except urllib.error.HTTPError as e:
|
|
53
|
+
text = e.read().decode("utf-8", "replace")
|
|
54
|
+
# Retry throttling / cold-start gateway errors; everything else is final.
|
|
55
|
+
if e.code in (429, 502, 503, 504) and attempt < retries:
|
|
56
|
+
time.sleep(2 ** attempt)
|
|
57
|
+
continue
|
|
58
|
+
try:
|
|
59
|
+
detail = json.loads(text).get("detail", text)
|
|
60
|
+
except ValueError:
|
|
61
|
+
detail = text
|
|
62
|
+
raise ApiError(e.code, detail if isinstance(detail, str) else json.dumps(detail))
|
|
63
|
+
except urllib.error.URLError:
|
|
64
|
+
if attempt < retries:
|
|
65
|
+
time.sleep(2 ** attempt)
|
|
66
|
+
continue
|
|
67
|
+
raise
|
|
68
|
+
|
|
69
|
+
def _multipart(self, path: str, fields: Dict[str, str], file_field: str, filename: str, content: bytes) -> Any:
|
|
70
|
+
boundary = uuid.uuid4().hex
|
|
71
|
+
parts: List[bytes] = []
|
|
72
|
+
for k, v in fields.items():
|
|
73
|
+
if v is None:
|
|
74
|
+
continue
|
|
75
|
+
parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{k}"\r\n\r\n{v}\r\n'.encode())
|
|
76
|
+
parts.append((f'--{boundary}\r\nContent-Disposition: form-data; name="{file_field}"; filename="{filename}"\r\n'
|
|
77
|
+
f'Content-Type: application/octet-stream\r\n\r\n').encode() + content + b"\r\n")
|
|
78
|
+
parts.append(f"--{boundary}--\r\n".encode())
|
|
79
|
+
return self.request("POST", path, raw=b"".join(parts), content_type=f"multipart/form-data; boundary={boundary}")
|
|
80
|
+
|
|
81
|
+
# -- evaluations ------------------------------------------------------------
|
|
82
|
+
|
|
83
|
+
def evaluate_batch(self, cases: Optional[List[dict]] = None, *, metrics: Optional[List[str]] = None,
|
|
84
|
+
project_id: Optional[str] = None, run_name: Optional[str] = None,
|
|
85
|
+
version: Optional[dict] = None, dataset_id: Optional[str] = None,
|
|
86
|
+
dataset_version: Optional[int] = None, outputs: Optional[Dict[str, str]] = None) -> dict:
|
|
87
|
+
body = {k: v for k, v in {
|
|
88
|
+
"cases": cases or [], "metrics": metrics, "project_id": project_id, "run_name": run_name,
|
|
89
|
+
"version": version, "dataset_id": dataset_id, "dataset_version": dataset_version, "outputs": outputs,
|
|
90
|
+
}.items() if v is not None}
|
|
91
|
+
return self.request("POST", "/evaluate/batch", body)
|
|
92
|
+
|
|
93
|
+
def evaluate_file(self, path: str, *, metrics: Optional[List[str]] = None, project_id: Optional[str] = None,
|
|
94
|
+
run_name: Optional[str] = None, version: Optional[dict] = None) -> dict:
|
|
95
|
+
with open(path, "rb") as f:
|
|
96
|
+
content = f.read()
|
|
97
|
+
return self._multipart("/upload/evaluate", {
|
|
98
|
+
"metrics": ",".join(metrics) if metrics else None, "project_id": project_id, "run_name": run_name,
|
|
99
|
+
"version": json.dumps(version) if version else None,
|
|
100
|
+
}, "file", os.path.basename(path), content)
|
|
101
|
+
|
|
102
|
+
def job_status(self, job_id: str) -> dict:
|
|
103
|
+
return self.request("GET", f"/evaluate/status/{job_id}")
|
|
104
|
+
|
|
105
|
+
def wait(self, job_id: str, timeout: float = 1800, poll: float = 5.0) -> dict:
|
|
106
|
+
"""Poll until the job completes. Raises TimeoutError / RuntimeError (job failed)."""
|
|
107
|
+
deadline = time.time() + timeout
|
|
108
|
+
while True:
|
|
109
|
+
s = self.job_status(job_id)
|
|
110
|
+
if s["status"] == "complete":
|
|
111
|
+
return s
|
|
112
|
+
if s["status"] == "failed":
|
|
113
|
+
raise RuntimeError(s.get("error") or "Evaluation job failed")
|
|
114
|
+
if time.time() > deadline:
|
|
115
|
+
raise TimeoutError(f"Job {job_id} still {s['status']} after {int(timeout)}s")
|
|
116
|
+
time.sleep(poll)
|
|
117
|
+
|
|
118
|
+
def run_results(self, job_id: str) -> dict:
|
|
119
|
+
return self.request("GET", f"/runs/{job_id}/results")
|
|
120
|
+
|
|
121
|
+
def wait_for_results(self, job_id: str, timeout: float = 1800, poll: float = 5.0) -> dict:
|
|
122
|
+
self.wait(job_id, timeout=timeout, poll=poll)
|
|
123
|
+
# Report rows are written just before the job flips to complete; allow for lag.
|
|
124
|
+
for attempt in range(5):
|
|
125
|
+
try:
|
|
126
|
+
return self.run_results(job_id)
|
|
127
|
+
except ApiError as e:
|
|
128
|
+
if e.status != 404 or attempt == 4:
|
|
129
|
+
raise
|
|
130
|
+
time.sleep(2)
|
|
131
|
+
raise RuntimeError("unreachable")
|
|
132
|
+
|
|
133
|
+
# -- projects / datasets / custom metrics -----------------------------------
|
|
134
|
+
|
|
135
|
+
def get_project(self, project_id: str) -> dict:
|
|
136
|
+
return self.request("GET", f"/projects/{project_id}")
|
|
137
|
+
|
|
138
|
+
def list_datasets(self) -> List[dict]:
|
|
139
|
+
return self.request("GET", "/datasets")["datasets"]
|
|
140
|
+
|
|
141
|
+
def create_dataset(self, name: str, rows: Iterable[dict], **kw) -> dict:
|
|
142
|
+
return self.request("POST", "/datasets", {"name": name, "rows": list(rows), **kw})
|
|
143
|
+
|
|
144
|
+
def dataset_rows(self, dataset_id: str, version: int) -> List[dict]:
|
|
145
|
+
rows, offset = [], 0
|
|
146
|
+
while True:
|
|
147
|
+
page = self.request("GET", f"/datasets/{dataset_id}/versions/{version}/rows?offset={offset}&limit=1000")
|
|
148
|
+
rows += page["rows"]
|
|
149
|
+
offset += len(page["rows"])
|
|
150
|
+
if offset >= page["total"] or not page["rows"]:
|
|
151
|
+
return rows
|
|
152
|
+
|
|
153
|
+
def list_custom_metrics(self) -> List[dict]:
|
|
154
|
+
return self.request("GET", "/custom-metrics")["metrics"]
|
|
155
|
+
|
|
156
|
+
def set_label(self, report_id: str, label: Optional[str], note: Optional[str] = None) -> dict:
|
|
157
|
+
return self.request("PATCH", f"/reports/{report_id}/label", {"label": label, "note": note})
|
ai_eval/gate.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Quality gate: decide whether a run is good enough to ship.
|
|
3
|
+
|
|
4
|
+
Conditions
|
|
5
|
+
- `--fail-under NAME=VALUE` (repeatable), NAME one of:
|
|
6
|
+
pass_rate share of cases where every metric meets its pass mark
|
|
7
|
+
good_rate share of cases labelled Good (Good/Bad/Unknown auto-labels)
|
|
8
|
+
overall | safety | truth | quality run average of that score
|
|
9
|
+
- `--metric KEY=VALUE` (repeatable): the run average of metric KEY must be >= VALUE, and
|
|
10
|
+
VALUE becomes KEY's pass mark when computing pass_rate.
|
|
11
|
+
|
|
12
|
+
Pass marks for pass_rate: --metric values, then the project's thresholds (returned with
|
|
13
|
+
the run), then 0.70.
|
|
14
|
+
"""
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from typing import Dict, List, Optional, Tuple
|
|
17
|
+
|
|
18
|
+
DEFAULT_PASS_MARK = 0.70
|
|
19
|
+
RUN_SCORES = ("overall", "safety", "truth", "quality")
|
|
20
|
+
GATE_NAMES = ("pass_rate", "good_rate") + RUN_SCORES
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def parse_conditions(items: Optional[List[str]], allowed: Optional[Tuple[str, ...]] = None) -> Dict[str, float]:
|
|
24
|
+
out: Dict[str, float] = {}
|
|
25
|
+
for item in items or []:
|
|
26
|
+
for part in item.split(","):
|
|
27
|
+
part = part.strip()
|
|
28
|
+
if not part:
|
|
29
|
+
continue
|
|
30
|
+
if "=" not in part:
|
|
31
|
+
raise ValueError(f"Expected NAME=VALUE, got {part!r}")
|
|
32
|
+
name, value = part.split("=", 1)
|
|
33
|
+
name = name.strip()
|
|
34
|
+
if allowed and name not in allowed:
|
|
35
|
+
raise ValueError(f"Unknown gate {name!r}; use one of: {', '.join(allowed)}")
|
|
36
|
+
try:
|
|
37
|
+
v = float(value)
|
|
38
|
+
except ValueError:
|
|
39
|
+
raise ValueError(f"{name}: {value!r} is not a number")
|
|
40
|
+
if not 0 <= v <= 1:
|
|
41
|
+
raise ValueError(f"{name}: {v} must be between 0 and 1")
|
|
42
|
+
out[name] = v
|
|
43
|
+
return out
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass
|
|
47
|
+
class Check:
|
|
48
|
+
name: str
|
|
49
|
+
actual: Optional[float]
|
|
50
|
+
required: float
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def ok(self) -> bool:
|
|
54
|
+
return self.actual is not None and self.actual + 1e-9 >= self.required
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass
|
|
58
|
+
class GateResult:
|
|
59
|
+
checks: List[Check] = field(default_factory=list)
|
|
60
|
+
stats: dict = field(default_factory=dict)
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def passed(self) -> bool:
|
|
64
|
+
return all(c.ok for c in self.checks)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _mean(vals: List[float]) -> Optional[float]:
|
|
68
|
+
return sum(vals) / len(vals) if vals else None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def run_stats(results: dict, metric_marks: Optional[Dict[str, float]] = None) -> dict:
|
|
72
|
+
"""Aggregate GET /runs/{job_id}/results into the numbers the gate checks."""
|
|
73
|
+
cases = results.get("cases") or []
|
|
74
|
+
run = results.get("run") or {}
|
|
75
|
+
marks = {**(run.get("thresholds") or {}), **(metric_marks or {})}
|
|
76
|
+
|
|
77
|
+
per_metric: Dict[str, List[float]] = {}
|
|
78
|
+
names: Dict[str, str] = {}
|
|
79
|
+
passing = 0
|
|
80
|
+
for c in cases:
|
|
81
|
+
ok = True
|
|
82
|
+
for m in c.get("metrics") or []:
|
|
83
|
+
if m.get("status") == "error" or m.get("score") is None:
|
|
84
|
+
continue
|
|
85
|
+
per_metric.setdefault(m["metric_key"], []).append(float(m["score"]))
|
|
86
|
+
names[m["metric_key"]] = m.get("metric_name") or m["metric_key"]
|
|
87
|
+
if float(m["score"]) < marks.get(m["metric_key"], DEFAULT_PASS_MARK):
|
|
88
|
+
ok = False
|
|
89
|
+
passing += ok
|
|
90
|
+
|
|
91
|
+
labelled = [c.get("label") for c in cases if c.get("label")]
|
|
92
|
+
summary = lambda k: _mean([c["summary"][f"{k}_score"] for c in cases
|
|
93
|
+
if (c.get("summary") or {}).get(f"{k}_score") is not None])
|
|
94
|
+
return {
|
|
95
|
+
"cases": len(cases),
|
|
96
|
+
"pass_rate": passing / len(cases) if cases else None,
|
|
97
|
+
"good_rate": labelled.count("good") / len(labelled) if labelled else None,
|
|
98
|
+
"labels": {k: labelled.count(k) for k in ("good", "bad", "unknown")} if labelled else None,
|
|
99
|
+
**{k: summary(k) for k in RUN_SCORES},
|
|
100
|
+
"metrics": {k: {"name": names[k], "avg": _mean(v), "min": min(v), "n": len(v),
|
|
101
|
+
"mark": marks.get(k, DEFAULT_PASS_MARK)} for k, v in per_metric.items()},
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def evaluate_gate(results: dict, fail_under: Dict[str, float], metric_marks: Dict[str, float]) -> GateResult:
|
|
106
|
+
stats = run_stats(results, metric_marks)
|
|
107
|
+
checks = [Check(name, stats.get(name), v) for name, v in fail_under.items()]
|
|
108
|
+
for key, v in metric_marks.items():
|
|
109
|
+
checks.append(Check(f"metric:{key}", (stats["metrics"].get(key) or {}).get("avg"), v))
|
|
110
|
+
return GateResult(checks=checks, stats=stats)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def format_report(gate: GateResult, run: Optional[dict] = None) -> str:
|
|
114
|
+
s = gate.stats
|
|
115
|
+
f = lambda v: "-" if v is None else f"{v:.2f}"
|
|
116
|
+
lines = []
|
|
117
|
+
if run:
|
|
118
|
+
lines.append(f"Run: {run.get('run_name') or 'Untitled run'} ({run.get('job_id', '')})")
|
|
119
|
+
lines.append(f"Cases: {s['cases']} pass rate: {f(s['pass_rate'])} overall: {f(s['overall'])}"
|
|
120
|
+
+ (f" good/bad/unknown: {s['labels']['good']}/{s['labels']['bad']}/{s['labels']['unknown']}"
|
|
121
|
+
if s.get("labels") else ""))
|
|
122
|
+
if s["metrics"]:
|
|
123
|
+
width = max(len(m["name"]) for m in s["metrics"].values())
|
|
124
|
+
lines.append("")
|
|
125
|
+
lines.append(f"{'Metric'.ljust(width)} avg min mark")
|
|
126
|
+
for m in sorted(s["metrics"].values(), key=lambda m: m["avg"] if m["avg"] is not None else 2):
|
|
127
|
+
lines.append(f"{m['name'].ljust(width)} {f(m['avg'])} {f(m['min'])} {m['mark']:.2f}")
|
|
128
|
+
if gate.checks:
|
|
129
|
+
lines.append("")
|
|
130
|
+
for c in gate.checks:
|
|
131
|
+
lines.append(f"[{'PASS' if c.ok else 'FAIL'}] {c.name}: {f(c.actual)} (needs >= {c.required:.2f})")
|
|
132
|
+
lines.append("")
|
|
133
|
+
lines.append("Quality gate " + ("PASSED" if gate.passed else "FAILED"))
|
|
134
|
+
return "\n".join(lines)
|
ai_eval/monitor.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Production monitoring client: log every production interaction; a background thread sends
|
|
3
|
+
them to POST /monitor/ingest in batches. The project's sample rate decides which ones are
|
|
4
|
+
evaluated (only those count as evaluations).
|
|
5
|
+
|
|
6
|
+
from ai_eval import Client
|
|
7
|
+
from ai_eval.monitor import Monitor
|
|
8
|
+
|
|
9
|
+
monitor = Monitor(Client(), project_id="...")
|
|
10
|
+
monitor.log(prompt=question, llm_output=answer, id=request_id,
|
|
11
|
+
metadata={"locale": "de"}, latency_ms=812, cost_usd=0.0021)
|
|
12
|
+
...
|
|
13
|
+
monitor.close() # flushes; also runs at interpreter exit
|
|
14
|
+
|
|
15
|
+
log() never blocks on the network and never raises; if the queue is full (the API is
|
|
16
|
+
unreachable for a long time) the oldest records are dropped and counted in `dropped`.
|
|
17
|
+
"""
|
|
18
|
+
import atexit
|
|
19
|
+
import queue
|
|
20
|
+
import threading
|
|
21
|
+
import time
|
|
22
|
+
from typing import Any, Dict, List, Optional
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Monitor:
|
|
26
|
+
def __init__(self, client=None, project_id: str = "", batch_size: int = 100, flush_interval: float = 5.0,
|
|
27
|
+
max_queue: int = 10000, version: Optional[dict] = None):
|
|
28
|
+
if client is None:
|
|
29
|
+
from ai_eval.client import Client
|
|
30
|
+
client = Client()
|
|
31
|
+
if not project_id:
|
|
32
|
+
raise ValueError("project_id is required")
|
|
33
|
+
self.client = client
|
|
34
|
+
self.project_id = project_id
|
|
35
|
+
self.batch_size = max(1, min(batch_size, 500))
|
|
36
|
+
self.flush_interval = flush_interval
|
|
37
|
+
self.version = version
|
|
38
|
+
self.dropped = 0
|
|
39
|
+
self.sent = 0
|
|
40
|
+
self.last_error: Optional[str] = None
|
|
41
|
+
self._q: "queue.Queue[dict]" = queue.Queue(maxsize=max_queue)
|
|
42
|
+
self._stop = threading.Event()
|
|
43
|
+
self._flush_now = threading.Event()
|
|
44
|
+
self._lock = threading.Lock()
|
|
45
|
+
self._thread = threading.Thread(target=self._run, name="ai-eval-monitor", daemon=True)
|
|
46
|
+
self._thread.start()
|
|
47
|
+
atexit.register(self.close)
|
|
48
|
+
|
|
49
|
+
def log(self, llm_output: str, prompt: str = "", **fields: Any) -> None:
|
|
50
|
+
"""Queue one interaction. Fields: id, golden_answer, context, metadata, latency_ms,
|
|
51
|
+
input_tokens, output_tokens, cost_usd, timestamp, session_id, trace_id."""
|
|
52
|
+
rec: Dict[str, Any] = {"prompt": prompt, "llm_output": llm_output, **{k: v for k, v in fields.items() if v is not None}}
|
|
53
|
+
rec.setdefault("timestamp", time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))
|
|
54
|
+
while True:
|
|
55
|
+
try:
|
|
56
|
+
self._q.put_nowait(rec)
|
|
57
|
+
break
|
|
58
|
+
except queue.Full:
|
|
59
|
+
try:
|
|
60
|
+
self._q.get_nowait()
|
|
61
|
+
self.dropped += 1
|
|
62
|
+
except queue.Empty:
|
|
63
|
+
pass
|
|
64
|
+
if self._q.qsize() >= self.batch_size:
|
|
65
|
+
self._flush_now.set()
|
|
66
|
+
|
|
67
|
+
def _drain(self, limit: int) -> List[dict]:
|
|
68
|
+
batch = []
|
|
69
|
+
while len(batch) < limit:
|
|
70
|
+
try:
|
|
71
|
+
batch.append(self._q.get_nowait())
|
|
72
|
+
except queue.Empty:
|
|
73
|
+
break
|
|
74
|
+
return batch
|
|
75
|
+
|
|
76
|
+
def _send(self, batch: List[dict]) -> None:
|
|
77
|
+
body = {"project_id": self.project_id, "records": batch}
|
|
78
|
+
if self.version:
|
|
79
|
+
body["version"] = self.version
|
|
80
|
+
try:
|
|
81
|
+
self.client.request("POST", "/monitor/ingest", body)
|
|
82
|
+
self.sent += len(batch)
|
|
83
|
+
except Exception as e: # monitoring must never break the app
|
|
84
|
+
self.last_error = str(e)
|
|
85
|
+
self.dropped += len(batch)
|
|
86
|
+
|
|
87
|
+
def flush(self) -> None:
|
|
88
|
+
with self._lock:
|
|
89
|
+
while True:
|
|
90
|
+
batch = self._drain(self.batch_size)
|
|
91
|
+
if not batch:
|
|
92
|
+
return
|
|
93
|
+
self._send(batch)
|
|
94
|
+
|
|
95
|
+
def _run(self) -> None:
|
|
96
|
+
while not self._stop.is_set():
|
|
97
|
+
self._flush_now.wait(self.flush_interval)
|
|
98
|
+
self._flush_now.clear()
|
|
99
|
+
self.flush()
|
|
100
|
+
|
|
101
|
+
def close(self) -> None:
|
|
102
|
+
if self._stop.is_set():
|
|
103
|
+
return
|
|
104
|
+
self._stop.set()
|
|
105
|
+
self._flush_now.set()
|
|
106
|
+
self._thread.join(timeout=10)
|
|
107
|
+
self.flush()
|
ai_eval/py.typed
ADDED
|
File without changes
|
ai_eval/tracing.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Manual tracing: wrap an agent run in `trace()` and its steps in `span()`.
|
|
3
|
+
|
|
4
|
+
from ai_eval import Client
|
|
5
|
+
from ai_eval.tracing import Tracer
|
|
6
|
+
|
|
7
|
+
tracer = Tracer(Client(), project_id="...")
|
|
8
|
+
with tracer.trace("support-agent", session_id=conversation_id, input=question) as t:
|
|
9
|
+
with tracer.span("plan", kind="llm", model="claude", input=prompt) as s:
|
|
10
|
+
s.output = call_llm(prompt)
|
|
11
|
+
s.tokens(120, 30)
|
|
12
|
+
with tracer.span("lookup_order", kind="tool", input={"id": 42}) as s:
|
|
13
|
+
s.output = lookup_order(42)
|
|
14
|
+
t.output = answer
|
|
15
|
+
tracer.flush() # also runs at interpreter exit
|
|
16
|
+
|
|
17
|
+
Spans nest automatically (a span opened inside another becomes its child). Traces are sent
|
|
18
|
+
to POST /traces in batches; `evaluate=True` asks the platform to score each trace as it
|
|
19
|
+
arrives (one evaluation per trace). For framework auto-instrumentation (LangChain,
|
|
20
|
+
LangGraph, CrewAI, Google ADK) use their OpenTelemetry instrumentors and point the OTLP
|
|
21
|
+
exporter at <api>/v1/traces instead - see the SDK README.
|
|
22
|
+
"""
|
|
23
|
+
import atexit
|
|
24
|
+
import contextvars
|
|
25
|
+
import threading
|
|
26
|
+
import time
|
|
27
|
+
import traceback
|
|
28
|
+
import uuid
|
|
29
|
+
from contextlib import contextmanager
|
|
30
|
+
from typing import Any, Dict, Iterator, List, Optional
|
|
31
|
+
|
|
32
|
+
KINDS = ("llm", "tool", "retrieval", "agent", "chain", "embedding", "other")
|
|
33
|
+
|
|
34
|
+
_current_trace: contextvars.ContextVar = contextvars.ContextVar("ai_eval_trace", default=None)
|
|
35
|
+
_current_span: contextvars.ContextVar = contextvars.ContextVar("ai_eval_span", default=None)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _now_ms() -> float:
|
|
39
|
+
return time.time() * 1000
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class Span:
|
|
43
|
+
def __init__(self, name: str, kind: str, parent_id: Optional[str], input: Any = None, model: Optional[str] = None):
|
|
44
|
+
self.span_id = uuid.uuid4().hex[:16]
|
|
45
|
+
self.parent_id = parent_id
|
|
46
|
+
self.name = name
|
|
47
|
+
self.kind = kind if kind in KINDS else "other"
|
|
48
|
+
self.input = input
|
|
49
|
+
self.output: Any = None
|
|
50
|
+
self.model = model
|
|
51
|
+
self.attributes: Dict[str, Any] = {}
|
|
52
|
+
self.input_tokens: Optional[int] = None
|
|
53
|
+
self.output_tokens: Optional[int] = None
|
|
54
|
+
self.cost_usd: Optional[float] = None
|
|
55
|
+
self.start_time = _now_ms()
|
|
56
|
+
self.end_time: Optional[float] = None
|
|
57
|
+
self.status = "ok"
|
|
58
|
+
self.error: Optional[str] = None
|
|
59
|
+
|
|
60
|
+
def tokens(self, input_tokens: Optional[int] = None, output_tokens: Optional[int] = None) -> "Span":
|
|
61
|
+
self.input_tokens, self.output_tokens = input_tokens, output_tokens
|
|
62
|
+
return self
|
|
63
|
+
|
|
64
|
+
def set(self, key: str, value: Any) -> "Span":
|
|
65
|
+
self.attributes[key] = value
|
|
66
|
+
return self
|
|
67
|
+
|
|
68
|
+
def to_dict(self) -> dict:
|
|
69
|
+
d = {"span_id": self.span_id, "parent_id": self.parent_id, "name": self.name, "kind": self.kind,
|
|
70
|
+
"start_time": self.start_time, "end_time": self.end_time or _now_ms(), "input": self.input,
|
|
71
|
+
"output": self.output, "model": self.model, "input_tokens": self.input_tokens,
|
|
72
|
+
"output_tokens": self.output_tokens, "cost_usd": self.cost_usd, "status": self.status,
|
|
73
|
+
"error": self.error, "attributes": self.attributes or None}
|
|
74
|
+
return {k: v for k, v in d.items() if v is not None}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class Trace:
|
|
78
|
+
def __init__(self, name: str, session_id: Optional[str], input: Any, metadata: Optional[dict]):
|
|
79
|
+
self.trace_id = uuid.uuid4().hex
|
|
80
|
+
self.session_id = session_id
|
|
81
|
+
self.metadata = metadata
|
|
82
|
+
self.root = Span(name, "agent", None, input=input)
|
|
83
|
+
self.spans: List[Span] = [self.root]
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def output(self):
|
|
87
|
+
return self.root.output
|
|
88
|
+
|
|
89
|
+
@output.setter
|
|
90
|
+
def output(self, value):
|
|
91
|
+
self.root.output = value
|
|
92
|
+
|
|
93
|
+
def to_dict(self) -> dict:
|
|
94
|
+
d = {"trace_id": self.trace_id, "session_id": self.session_id, "name": self.root.name,
|
|
95
|
+
"metadata": self.metadata, "spans": [s.to_dict() for s in self.spans]}
|
|
96
|
+
return {k: v for k, v in d.items() if v is not None}
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class Tracer:
|
|
100
|
+
def __init__(self, client=None, project_id: Optional[str] = None, batch_size: int = 20,
|
|
101
|
+
evaluate: bool = False, metrics: Optional[List[str]] = None):
|
|
102
|
+
if client is None:
|
|
103
|
+
from ai_eval.client import Client
|
|
104
|
+
client = Client()
|
|
105
|
+
self.client = client
|
|
106
|
+
self.project_id = project_id
|
|
107
|
+
self.batch_size = max(1, batch_size)
|
|
108
|
+
self.evaluate = evaluate
|
|
109
|
+
self.metrics = metrics
|
|
110
|
+
self._buffer: List[dict] = []
|
|
111
|
+
self._lock = threading.Lock()
|
|
112
|
+
atexit.register(self.flush)
|
|
113
|
+
|
|
114
|
+
@contextmanager
|
|
115
|
+
def trace(self, name: str, session_id: Optional[str] = None, input: Any = None,
|
|
116
|
+
metadata: Optional[dict] = None) -> Iterator[Trace]:
|
|
117
|
+
t = Trace(name, session_id, input, metadata)
|
|
118
|
+
tok_t = _current_trace.set(t)
|
|
119
|
+
tok_s = _current_span.set(t.root)
|
|
120
|
+
try:
|
|
121
|
+
yield t
|
|
122
|
+
except BaseException as e:
|
|
123
|
+
t.root.status, t.root.error = "error", f"{type(e).__name__}: {e}"
|
|
124
|
+
raise
|
|
125
|
+
finally:
|
|
126
|
+
t.root.end_time = _now_ms()
|
|
127
|
+
_current_span.reset(tok_s)
|
|
128
|
+
_current_trace.reset(tok_t)
|
|
129
|
+
self._enqueue(t.to_dict())
|
|
130
|
+
|
|
131
|
+
@contextmanager
|
|
132
|
+
def span(self, name: str, kind: str = "other", input: Any = None, model: Optional[str] = None) -> Iterator[Span]:
|
|
133
|
+
t: Optional[Trace] = _current_trace.get()
|
|
134
|
+
if t is None:
|
|
135
|
+
raise RuntimeError("tracer.span() must be used inside tracer.trace()")
|
|
136
|
+
parent: Optional[Span] = _current_span.get()
|
|
137
|
+
s = Span(name, kind, parent.span_id if parent else t.root.span_id, input=input, model=model)
|
|
138
|
+
t.spans.append(s)
|
|
139
|
+
tok = _current_span.set(s)
|
|
140
|
+
try:
|
|
141
|
+
yield s
|
|
142
|
+
except BaseException as e:
|
|
143
|
+
s.status, s.error = "error", "".join(traceback.format_exception_only(type(e), e)).strip()
|
|
144
|
+
raise
|
|
145
|
+
finally:
|
|
146
|
+
s.end_time = _now_ms()
|
|
147
|
+
_current_span.reset(tok)
|
|
148
|
+
|
|
149
|
+
def _enqueue(self, trace: dict) -> None:
|
|
150
|
+
with self._lock:
|
|
151
|
+
self._buffer.append(trace)
|
|
152
|
+
full = len(self._buffer) >= self.batch_size
|
|
153
|
+
if full:
|
|
154
|
+
self.flush()
|
|
155
|
+
|
|
156
|
+
def flush(self) -> Optional[dict]:
|
|
157
|
+
with self._lock:
|
|
158
|
+
batch, self._buffer = self._buffer, []
|
|
159
|
+
if not batch:
|
|
160
|
+
return None
|
|
161
|
+
body = {"traces": batch, "project_id": self.project_id, "evaluate": self.evaluate, "metrics": self.metrics}
|
|
162
|
+
try:
|
|
163
|
+
return self.client.request("POST", "/traces", {k: v for k, v in body.items() if v is not None})
|
|
164
|
+
except Exception as e: # tracing must never break the app
|
|
165
|
+
print(f"ai-eval: could not send {len(batch)} trace(s): {e}")
|
|
166
|
+
return None
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ai-eval-platform
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Python SDK and `ai-eval` CI quality-gate CLI for the AI Evaluation Platform
|
|
5
|
+
Author: AssertThat
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://ai-evaluation-platform.com
|
|
8
|
+
Project-URL: Documentation, https://ai-evaluation-platform.com/docs#ci
|
|
9
|
+
Project-URL: AWS Marketplace, https://aws.amazon.com/marketplace/pp/prodview-qejr2yng5xgc6
|
|
10
|
+
Project-URL: GitHub Action, https://github.com/marketplace/actions/ai-evaluation-platform-quality-gate
|
|
11
|
+
Keywords: llm,evaluation,llm-as-a-judge,quality-gate,ci,ragas,opentelemetry,tracing
|
|
12
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
13
|
+
Classifier: Environment :: Console
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
24
|
+
Classifier: Topic :: Software Development :: Testing
|
|
25
|
+
Classifier: Typing :: Typed
|
|
26
|
+
Requires-Python: >=3.9
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
License-File: LICENSE
|
|
29
|
+
Dynamic: license-file
|
|
30
|
+
|
|
31
|
+
# ai-eval-platform (Python SDK + CLI)
|
|
32
|
+
|
|
33
|
+
Standard-library-only client for the AI Evaluation Platform API, plus an `ai-eval` command
|
|
34
|
+
that runs an evaluation and fails your CI build when quality drops.
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install ai-eval-platform
|
|
38
|
+
export AI_EVAL_API_KEY=... # Settings > API keys in the app
|
|
39
|
+
export AI_EVAL_API_URL=https://api.ai-evaluation-platform.com
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Quality gate in CI
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
# 1. Your pipeline runs your app over the dataset's prompts and writes outputs.json:
|
|
46
|
+
# {"case-1": "the app's answer", "case-2": "..."}
|
|
47
|
+
# 2. Evaluate and gate:
|
|
48
|
+
ai-eval run --project <project_id> --dataset <dataset_id> --outputs outputs.json \
|
|
49
|
+
--fail-under pass_rate=0.9 --metric factual_accuracy=0.8 --version-label "$GIT_SHA"
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
- `--fail-under NAME=VALUE` (repeatable or comma-separated): `pass_rate` (share of cases
|
|
53
|
+
where every metric meets its pass mark), `good_rate` (share labelled Good), or a run
|
|
54
|
+
average: `overall`, `safety`, `truth`, `quality`.
|
|
55
|
+
- `--metric KEY=VALUE`: the run average of metric `KEY` must be at least `VALUE`; `VALUE`
|
|
56
|
+
is also that metric's pass mark for `pass_rate`. Other metrics use the project's
|
|
57
|
+
thresholds, else 0.70.
|
|
58
|
+
- Instead of a dataset: `--file cases.jsonl` (cases with `prompt`, `llm_output`, ...) or
|
|
59
|
+
`--file results.csv` (uploaded with the same column mapping as the app), or
|
|
60
|
+
`--job <job_id>` to gate a run that already exists.
|
|
61
|
+
- Exit code 0 = passed, 1 = gate failed, 2 = error (bad arguments, API error, timeout).
|
|
62
|
+
`--report-json gate.json` writes the numbers for later steps.
|
|
63
|
+
|
|
64
|
+
The run shows up in the app with its version label, so you can compare it with the
|
|
65
|
+
previous build's run on the same dataset version.
|
|
66
|
+
|
|
67
|
+
### GitHub Actions
|
|
68
|
+
|
|
69
|
+
The [AI Evaluation Platform quality gate](https://github.com/marketplace/actions/ai-evaluation-platform-quality-gate)
|
|
70
|
+
action wraps the CLI:
|
|
71
|
+
|
|
72
|
+
```yaml
|
|
73
|
+
- run: python scripts/generate_outputs.py > outputs.json # your app
|
|
74
|
+
- uses: assertthat/ai-eval-action@v1
|
|
75
|
+
with:
|
|
76
|
+
api-key: ${{ secrets.AI_EVAL_API_KEY }}
|
|
77
|
+
project: ${{ vars.AI_EVAL_PROJECT }}
|
|
78
|
+
dataset: ${{ vars.AI_EVAL_DATASET }}
|
|
79
|
+
outputs: outputs.json
|
|
80
|
+
fail-under: pass_rate=0.9
|
|
81
|
+
metric-thresholds: factual_accuracy=0.8
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
### Bitbucket Pipelines
|
|
85
|
+
|
|
86
|
+
With the pipe:
|
|
87
|
+
|
|
88
|
+
```yaml
|
|
89
|
+
- step:
|
|
90
|
+
name: LLM quality gate
|
|
91
|
+
script:
|
|
92
|
+
- python scripts/generate_outputs.py > outputs.json # your app
|
|
93
|
+
- pipe: docker://assertthat/ai-eval-pipe:1.0.0
|
|
94
|
+
variables:
|
|
95
|
+
AI_EVAL_API_KEY: $AI_EVAL_API_KEY
|
|
96
|
+
PROJECT: $AI_EVAL_PROJECT
|
|
97
|
+
DATASET: $AI_EVAL_DATASET
|
|
98
|
+
OUTPUTS: outputs.json
|
|
99
|
+
FAIL_UNDER: pass_rate=0.9
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
Or with the CLI directly:
|
|
103
|
+
|
|
104
|
+
```yaml
|
|
105
|
+
- step:
|
|
106
|
+
name: LLM quality gate
|
|
107
|
+
image: python:3.12-slim
|
|
108
|
+
script:
|
|
109
|
+
- pip install ai-eval-platform
|
|
110
|
+
- python scripts/generate_outputs.py > outputs.json
|
|
111
|
+
- ai-eval run --project $AI_EVAL_PROJECT --dataset $AI_EVAL_DATASET --outputs outputs.json
|
|
112
|
+
--fail-under pass_rate=0.9 --version-label $BITBUCKET_COMMIT --run-name "$BITBUCKET_BRANCH"
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
(Set `AI_EVAL_API_KEY` as a secured repository variable.)
|
|
116
|
+
|
|
117
|
+
## Tracing agents
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
from ai_eval import Client
|
|
121
|
+
from ai_eval.tracing import Tracer
|
|
122
|
+
|
|
123
|
+
tracer = Tracer(Client(), project_id="...")
|
|
124
|
+
with tracer.trace("support-agent", session_id=conversation_id, input=question) as t:
|
|
125
|
+
with tracer.span("lookup_order", kind="tool", input={"id": 42}) as s:
|
|
126
|
+
s.output = lookup_order(42)
|
|
127
|
+
t.output = answer
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Or point any OpenTelemetry OTLP/HTTP exporter at `<api>/v1/traces` with the header
|
|
131
|
+
`X-API-Key` - see the [tracing docs](https://ai-evaluation-platform.com/docs#traces).
|
|
132
|
+
|
|
133
|
+
## Production monitoring
|
|
134
|
+
|
|
135
|
+
```python
|
|
136
|
+
from ai_eval.monitor import Monitor
|
|
137
|
+
|
|
138
|
+
monitor = Monitor(Client(), project_id="...") # sends in the background
|
|
139
|
+
monitor.log(prompt=question, llm_output=answer, id=request_id, latency_ms=812)
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
Turn monitoring on and set the sample rate per project in the app (Monitoring > Setup); only
|
|
143
|
+
sampled records are evaluated.
|
|
144
|
+
|
|
145
|
+
## Library use
|
|
146
|
+
|
|
147
|
+
```python
|
|
148
|
+
from ai_eval import Client, evaluate_gate
|
|
149
|
+
|
|
150
|
+
c = Client()
|
|
151
|
+
job = c.evaluate_batch(dataset_id="...", outputs={"case-1": "..."}, project_id="...",
|
|
152
|
+
version={"label": "v2", "model": "claude-sonnet", "prompt": open("system.txt").read()})
|
|
153
|
+
results = c.wait_for_results(job["job_id"])
|
|
154
|
+
gate = evaluate_gate(results, {"pass_rate": 0.9}, {"factual_accuracy": 0.8})
|
|
155
|
+
print(gate.passed, gate.stats["pass_rate"])
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
## Links
|
|
159
|
+
|
|
160
|
+
- Docs: https://ai-evaluation-platform.com/docs
|
|
161
|
+
- Buy on AWS Marketplace: https://aws.amazon.com/marketplace/pp/prodview-qejr2yng5xgc6
|
|
162
|
+
- Support: hello@ai-evaluation-platform.com
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
ai_eval/__init__.py,sha256=DnGEOpQ9r85nzYIxbHmmYhTf9eBe1MsIHUCPA8SrC2g,297
|
|
2
|
+
ai_eval/_version.py,sha256=7AftY9o0WWFDtezdMTYibHvRW1AX9lVsi4PvLpBKINM,145
|
|
3
|
+
ai_eval/cli.py,sha256=k39Jr-MASBbJ95q-sWHTHqkwmi5-sW_alzDoyN6Ga7o,6622
|
|
4
|
+
ai_eval/client.py,sha256=Tm_zx8_-sNzncqZrDZKsCdW2M_obhZF0tkthhSy0oaU,7708
|
|
5
|
+
ai_eval/gate.py,sha256=gVjzScOPNgvXcbUoYpPGw2v03cW2ssTAnDXt_dYw8dc,5545
|
|
6
|
+
ai_eval/monitor.py,sha256=X6gK_4LN6b6HhNpeAiueGrsNk7SS1bf70IwirYoYtMc,4000
|
|
7
|
+
ai_eval/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
ai_eval/tracing.py,sha256=8BZ1jk_mJ76eovVb5G-BrVbjdGBk4JYrE6FsYzjGheU,6683
|
|
9
|
+
ai_eval_platform-1.0.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
10
|
+
ai_eval_platform-1.0.0.dist-info/METADATA,sha256=Ll2fkTj8Q9Zeu5TIb3_iMrWx2nktTqkdRf1jJWOoBz8,6011
|
|
11
|
+
ai_eval_platform-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
12
|
+
ai_eval_platform-1.0.0.dist-info/entry_points.txt,sha256=u4f1UycHHzJtW8yevigspqrWVHw1hCKp_Vwl8V1Im-c,45
|
|
13
|
+
ai_eval_platform-1.0.0.dist-info/top_level.txt,sha256=ee1fRG3SB4qfFW4XwJ4zjP_jZ6TjbVeOUYsIumMsBv4,8
|
|
14
|
+
ai_eval_platform-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ai_eval
|