-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheval_runner.py
More file actions
230 lines (197 loc) · 8.4 KB
/
Copy patheval_runner.py
File metadata and controls
230 lines (197 loc) · 8.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
"""Example WebSocket client for the LangSmith evals service.
Connects to the /ws/evaluate endpoint, sends one EvaluateRequest payload, and
prints the streamed events as they arrive: per-example progress while the run
is in flight, then the aggregate summary (mean score per evaluator) at the end.
This is a thin reference client, NOT the CI runner. For CI/threshold gating use
run_evals.py (in-process, exits 0/1/2). For a minimal token-free smoke test see
ws_smoke_test.py.
Protocol (see app/server.py + app/runner.py):
envelope: {"type": ..., "data": {...}}
order: started -> dataset_synced -> run_planned
-> example_completed* (or example_failed) -> completed
error is terminal and the socket closes after it.
Usage:
pip install websockets python-dotenv
# Evaluate an existing LangSmith dataset:
python eval_runner.py --url ws://<host>/ws/evaluate \
--dataset my-dataset --evaluators correctness,answer_relevance \
--prefix my-run --metadata git_sha=abc123 release=v1.2.3
# Sync inline examples first, then evaluate (requires --allow-overwrite
# to replace examples in an existing dataset):
python eval_runner.py --url ws://<host>/ws/evaluate \
--dataset my-dataset --examples examples.json \
--evaluators correctness --allow-overwrite
"""
from __future__ import annotations
import argparse
import asyncio
import json
import logging
import os
from pathlib import Path
import websockets
from dotenv import load_dotenv
load_dotenv()
log = logging.getLogger(__name__)
logging.basicConfig(level=os.getenv("LOG_LEVEL", "INFO"))
# One reconnect attempt budget for transient handshake failures (the server
# only accepts one payload per connection, so this is just connect resilience).
MAX_ATTEMPTS = 3
RETRY_BASE_DELAY = 1.0
def _fmt_scores(results: list[dict]) -> str:
"""Compact per-evaluator score string for one example."""
return ", ".join(
f"{r.get('key', '?')}={r.get('score')}" for r in results
) or "(no scores)"
def _build_payload(
dataset_name: str,
evaluators: list[str],
examples: list[dict] | None,
experiment_prefix: str | None,
metadata: dict,
allow_overwrite: bool,
) -> dict:
payload: dict = {
"dataset_name": dataset_name,
"evaluators": evaluators,
"metadata": metadata,
"allow_overwrite": allow_overwrite,
}
if experiment_prefix:
payload["experiment_prefix"] = experiment_prefix
if examples is not None:
payload["examples"] = examples
return payload
async def _consume(ws, payload: dict) -> str:
"""Send the payload, print streamed events, return the terminal type."""
await ws.send(json.dumps(payload))
log.info(
"sent EvaluateRequest (dataset=%s, evaluators=%s, inline_examples=%s)",
payload["dataset_name"], payload["evaluators"],
len(payload.get("examples") or []),
)
terminal = "disconnected"
async for raw in ws:
msg = json.loads(raw)
kind = msg.get("type")
data = msg.get("data", {})
if kind == "started":
log.info(
"[started] dataset=%s target=%s target_provider=%s "
"judge_provider=%s judge_model=%s",
data.get("dataset_name"), data.get("target_type"),
data.get("target_provider"), data.get("judge_provider"),
data.get("judge_model"),
)
elif kind == "dataset_synced":
log.info("[synced] action=%s count=%s",
data.get("action"), data.get("example_count"))
elif kind == "run_planned":
log.info("[planned] total=%s evaluators=%s",
data.get("total_examples"), data.get("evaluators"))
elif kind == "example_completed":
# --- progress message: one per example as the run advances ---
prog = data.get("progress", {})
log.info("[progress %s/%s] %s",
prog.get("completed"), prog.get("total"),
_fmt_scores(data.get("results", [])))
# Surface per-evaluator errors (score=None) inline.
for r in data.get("results", []):
if r.get("score") is None:
log.warning(" %s: %s", r.get("key"),
(r.get("comment") or "")[:200])
elif kind == "example_failed":
log.error("[example_failed idx=%s] %s",
data.get("index"), data.get("error"))
elif kind == "completed":
# --- final summary: mean score per evaluator ---
log.info("[completed] examples=%s failures=%s duration=%ss",
data.get("total_examples"), data.get("failures"),
data.get("duration_s"))
for name, agg in (data.get("summary") or {}).items():
log.info(" %s: mean=%s n=%s",
name, agg.get("mean"), agg.get("count"))
terminal = "completed"
break
elif kind == "error":
log.error("[error stage=%s] %s", data.get("stage"),
data.get("message") or data.get("errors"))
terminal = "error"
break
else:
log.warning("[unknown type=%s] %s", kind, data)
return terminal
async def run(
url: str,
dataset_name: str,
evaluators: list[str],
examples: list[dict] | None,
experiment_prefix: str | None,
metadata: dict,
allow_overwrite: bool,
) -> int:
payload = _build_payload(
dataset_name, evaluators, examples,
experiment_prefix, metadata, allow_overwrite,
)
attempt = 0
while attempt < MAX_ATTEMPTS:
attempt += 1
try:
log.info("connecting to %s (attempt %s/%s)",
url, attempt, MAX_ATTEMPTS)
async with websockets.connect(url, ping_interval=20,
ping_timeout=20) as ws:
terminal = await _consume(ws, payload)
return 0 if terminal == "completed" else 1
except (OSError, websockets.exceptions.WebSocketException) as exc:
if attempt >= MAX_ATTEMPTS:
log.error("giving up after %s attempts: %s", attempt, exc)
return 1
delay = RETRY_BASE_DELAY * attempt
log.warning("connect failed (%s); retrying in %.1fs", exc, delay)
await asyncio.sleep(delay)
return 1
def _parse_metadata(pairs: list[str] | None) -> dict:
"""Turn ['k=v', 'a=b'] into {'k': 'v', 'a': 'b'}."""
out: dict[str, str] = {}
for item in pairs or []:
if "=" not in item:
raise ValueError(f"metadata must be KEY=VALUE, got {item!r}")
key, value = item.split("=", 1)
out[key.strip()] = value.strip()
return out
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--url", default="ws://localhost:8000/ws/evaluate",
help="WebSocket URL of the /ws/evaluate endpoint.")
parser.add_argument("--dataset", required=True,
help="LangSmith dataset name.")
parser.add_argument("--examples", default=None,
help="Path to a JSON array of inline examples to sync "
"before evaluating (omit to use the dataset as-is).")
parser.add_argument("--evaluators", default="correctness",
help="Comma-separated evaluator names.")
parser.add_argument("--prefix", default=None,
help="Experiment prefix for this run.")
parser.add_argument("--metadata", nargs="*", metavar="KEY=VALUE",
help="Optional run metadata as key=value pairs.")
parser.add_argument("--allow-overwrite", action="store_true",
help="Allow replacing examples in an existing dataset.")
args = parser.parse_args()
examples = None
if args.examples:
examples = json.loads(Path(args.examples).read_text(encoding="utf-8"))
evaluators = [e.strip() for e in args.evaluators.split(",") if e.strip()]
metadata = _parse_metadata(args.metadata)
return asyncio.run(run(
url=args.url,
dataset_name=args.dataset,
evaluators=evaluators,
examples=examples,
experiment_prefix=args.prefix,
metadata=metadata,
allow_overwrite=args.allow_overwrite,
))
if __name__ == "__main__":
raise SystemExit(main())