zhanla 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,484 @@
1
+ Metadata-Version: 2.4
2
+ Name: zhanla
3
+ Version: 0.1.0
4
+ Summary: CLI from Zhanla for running and uploading AI component evaluations
5
+ Project-URL: Homepage, https://benchmark-black.vercel.app/
6
+ Project-URL: Repository, https://github.com/zhanla-ai
7
+ Author-email: Zhanla <chouweimin@berkeley.edu>
8
+ License: Proprietary
9
+ Requires-Python: >=3.10
10
+ Requires-Dist: httpx>=0.28.0
11
+ Requires-Dist: rich>=13.0.0
12
+ Requires-Dist: supabase>=2.0.0
13
+ Requires-Dist: typer>=0.12.0
14
+ Description-Content-Type: text/markdown
15
+
16
+ # zhanla
17
+
18
+ Command-line interface for discovering Benchmark SDK components, running them against datasets, and syncing results to the Benchmark web app.
19
+
20
+ The CLI works with the class-based `zhanla-sdk-py` API.
21
+
22
+ ## Installation
23
+
24
+ ```bash
25
+ pip install zhanla
26
+ ```
27
+
28
+ Requires Python `>=3.10`.
29
+
30
+ Runtime dependencies:
31
+
32
+ - `typer`
33
+ - `rich`
34
+ - `supabase`
35
+ - `httpx`
36
+ - `zhanla-sdk-py`
37
+
38
+ After installation, the `zhanla` command is available in your shell.
39
+
40
+ ## Authentication
41
+
42
+ ### `zhanla login`
43
+
44
+ Authenticate with your SDK API key:
45
+
46
+ ```bash
47
+ bench login
48
+ ```
49
+
50
+ The CLI prompts for a composite key in this format:
51
+
52
+ ```text
53
+ bm_kid_XXXX.bm_sec_XXXX
54
+ ```
55
+
56
+ On success, the CLI exchanges that key for token metadata and stores credentials at `~/.benchmark/credentials.json`.
57
+
58
+ Saved fields:
59
+
60
+ | Field | Description |
61
+ |---|---|
62
+ | `key_id` | The `bm_kid_...` portion of the API key |
63
+ | `secret` | The `bm_sec_...` portion of the API key |
64
+ | `supabase_url` | Supabase project URL |
65
+ | `supabase_anon_key` | Public anon key used to initialize the client |
66
+ | `org_id` | Organization ID |
67
+
68
+ ### `zhanla logout`
69
+
70
+ Remove saved credentials:
71
+
72
+ ```bash
73
+ bench logout
74
+ ```
75
+
76
+ ### Token Refresh
77
+
78
+ When a command needs authenticated access, the CLI exchanges the saved API key for a fresh short-lived token. If you are not logged in, authenticated commands exit with:
79
+
80
+ ```text
81
+ Not logged in. Run `zhanla login` first.
82
+ ```
83
+
84
+ ## `zhanla run`
85
+
86
+ `zhanla run` supports three execution modes:
87
+
88
+ 1. Local component + local eval
89
+ 2. Local component + web autorater
90
+ 3. Fully web-backed run
91
+
92
+ The command enforces exactly one source for each required input:
93
+
94
+ - exactly one component source: local target or `--web-config`
95
+ - exactly one dataset source: `--dataset` or `--web-dataset`
96
+ - exactly one evaluation source: `--eval` or `--web-eval`
97
+
98
+ ### Local component + local eval
99
+
100
+ Run a component discovered from a Python file and score it with a local eval component:
101
+
102
+ ```bash
103
+ bench run components.py:my_tool --dataset data.json --eval evals.py:my_eval
104
+ ```
105
+
106
+ Notes:
107
+
108
+ - `component.py:name` targets a runnable component defined as a module-level `zhanla.*` instance
109
+ - `--eval eval.py:name` targets an eval component such as `CodeEval`, `LLMEval`, `Checklist`, or `EvalTree`
110
+ - If the file contains exactly one matching component, `:name` is optional
111
+
112
+ ### Local component + web autorater
113
+
114
+ Run a local component, upload the dataset and outputs, then start a managed web autorater run:
115
+
116
+ ```bash
117
+ bench run components.py:my_tool --dataset data.json --web-eval autorater-uuid
118
+ ```
119
+
120
+ This flow:
121
+
122
+ - executes the local component over your dataset
123
+ - uploads dataset rows and local outputs
124
+ - starts a remote evaluate-only run for the specified autorater
125
+ - polls until the remote run completes or fails
126
+
127
+ Eval contract note:
128
+
129
+ - the CLI sends `model_input`, `model_response`, and `expected_output` to managed evals as serialized strings
130
+ - before your eval function runs, the platform parses those strings according to the eval item's `model_response_format`
131
+ - `CodeEval` defaults to `model_response_format="JSON"` — your function receives a pre-parsed dict/object
132
+ - set `model_response_format="TEXT"` to receive the raw string instead (useful for keyword or regex checks)
133
+ - `LLMEval` always receives plain text regardless of `model_response_format`
134
+
135
+ #### `model_response_format` defaults
136
+
137
+ | Eval type | Default | Received by function |
138
+ |-----------|---------|----------------------|
139
+ | `CodeEval` | `"JSON"` | Parsed dict/object |
140
+ | `CodeEval(model_response_format="TEXT")` | `"TEXT"` | Raw string |
141
+ | `CodeEval(model_response_format="YAML")` | `"YAML"` | Parsed dict/object |
142
+ | `LLMEval` | `"TEXT"` (fixed) | Raw string |
143
+
144
+ Example — structured eval (default JSON):
145
+
146
+ ```python
147
+ bench.CodeEval(
148
+ name="check_priority",
149
+ description="Verify the priority field is correct.",
150
+ fn=lambda model_response, expected_output, **_: {
151
+ "score": 1.0 if model_response.get("priority") == expected_output.get("expected_priority") else 0.0
152
+ },
153
+ )
154
+ ```
155
+
156
+ Example — text-based eval (explicit TEXT):
157
+
158
+ ```python
159
+ bench.CodeEval(
160
+ name="contains_priority_label",
161
+ description="Check that the response mentions a priority level.",
162
+ fn=lambda model_response, **_: {
163
+ "score": 1.0 if any(label in model_response.lower() for label in ["critical", "high", "medium", "low"]) else 0.0
164
+ },
165
+ model_response_format="TEXT",
166
+ )
167
+
168
+ `--dry-run` is not supported with `--web-eval`.
169
+
170
+ ### Fully web-backed run
171
+
172
+ Start a run entirely against web-managed resources:
173
+
174
+ ```bash
175
+ bench run --web-config prompt-uuid --web-dataset dataset-uuid --web-eval autorater-uuid
176
+ ```
177
+
178
+ Optional model override:
179
+
180
+ ```bash
181
+ bench run \
182
+ --web-config prompt-uuid \
183
+ --web-dataset dataset-uuid \
184
+ --web-eval autorater-uuid \
185
+ --model-endpoint openai:gpt-4.1-mini
186
+ ```
187
+
188
+ Notes:
189
+
190
+ - `--web-config` requires both `--web-dataset` and `--web-eval`
191
+ - `--model-endpoint` is only valid with `--web-config`
192
+ - `--dry-run` is not supported for fully web-backed runs
193
+
194
+ ### Options
195
+
196
+ | Flag | Short | Description |
197
+ |---|---|---|
198
+ | `--eval <spec>` | `-e` | Local eval target in `file.py:name` form |
199
+ | `--dataset <path>` | `-d` | Local dataset file (`.json` or `.csv`) |
200
+ | `--web-eval <id>` | | Managed autorater ID |
201
+ | `--web-dataset <id>` | | Dataset ID from the web app |
202
+ | `--web-config <id>` | | Prompt ID for fully web-backed runs |
203
+ | `--model-endpoint <value>` | | Model endpoint override for fully web-backed runs |
204
+ | `--dry-run` | | Execute locally and skip sync/upload |
205
+
206
+ ### What `zhanla run` does
207
+
208
+ For local component runs, the CLI:
209
+
210
+ 1. Discovers the component from the target file.
211
+ 2. Prints a discovered-components table.
212
+ 3. Validates the component structure.
213
+ 4. Resolves a local eval or web autorater target.
214
+ 5. Checks auth when the chosen mode needs it.
215
+ 6. Loads the dataset from disk or from the web app.
216
+ 7. Executes each dataset row in sequence with a progress bar.
217
+ 8. Validates the first component output against `output_schema` when present.
218
+ 9. Uploads local definitions and run results unless `--dry-run` is set.
219
+ 10. Prints either a local score summary or a remote evaluation summary.
220
+
221
+ If sync/upload fails, the run exits with status `1`.
222
+
223
+ ## Dataset Formats
224
+
225
+ ### JSON
226
+
227
+ JSON datasets should be a top-level array.
228
+
229
+ The preferred format is a leading schema row followed by ordinary data rows:
230
+
231
+ ```json
232
+ [
233
+ {
234
+ "_schema": {
235
+ "revenue": {"type": "integer"},
236
+ "cost": {"type": "integer"}
237
+ }
238
+ },
239
+ {"revenue": 100, "cost": 40},
240
+ {"revenue": 200, "cost": 120}
241
+ ]
242
+ ```
243
+
244
+ The first items may optionally be metadata rows:
245
+
246
+ ```json
247
+ [
248
+ {
249
+ "_schema": {
250
+ "revenue": {"type": "integer"},
251
+ "cost": {"type": "integer"}
252
+ }
253
+ },
254
+ {"_config": {"name": "finance", "description": "Margin checks"}},
255
+ {"revenue": 100, "cost": 40},
256
+ {"revenue": 200, "cost": 120}
257
+ ]
258
+ ```
259
+
260
+ Leading rows with `_schema` or `_config` are treated as metadata and are not executed.
261
+ Legacy object-shaped JSON datasets with `schema` and `rows` are still accepted.
262
+
263
+ ### CSV
264
+
265
+ CSV datasets use the header row as field names:
266
+
267
+ ```csv
268
+ revenue,cost
269
+ 100,40
270
+ 200,120
271
+ ```
272
+
273
+ CSV values are loaded as strings.
274
+
275
+ ### Empty datasets
276
+
277
+ If the resolved dataset has no rows, the CLI exits with:
278
+
279
+ ```text
280
+ Dataset is empty.
281
+ ```
282
+
283
+ ## Local Execution Semantics
284
+
285
+ The CLI executes SDK components according to their current implementation:
286
+
287
+ - `Tool`: runs `fn(**row)` and normalizes non-dict output to `{"result": value}`
288
+ - `CodeEval`: runs `fn(**row_and_component_output)` and normalizes non-dict output to `{"score": value}`
289
+ - `Skill`: raises an error — Skills are prompt-only definitions and cannot be executed directly in the CLI
290
+ - `Agent`: requires a configured `runner` and `model`; calls the runner to generate a response
291
+ - `LLMProcessor`: requires a configured `runner` and `model`; calls the runner to generate a response
292
+ - `LLMEval`: requires a configured `runner` and `model`; calls the runner to score the response
293
+ - `Checklist`: runs all child evals and computes a weighted average
294
+ - `EvalTree`: routes through branches and computes weighted leaf scores
295
+ - `Orchestration`: executes the DAG and returns the final executed step output
296
+
297
+ For local evals, dataset row fields and component output fields are merged into the eval kwargs.
298
+
299
+ ## Discovery
300
+
301
+ The CLI discovers local components by importing your Python file and scanning module-level attributes for `zhanla` component instances.
302
+
303
+ That means:
304
+
305
+ - your file is executed during discovery
306
+ - module-level side effects will run
307
+ - components should usually be defined at module scope
308
+ - local imports from the same directory are supported
309
+
310
+ Name resolution rules:
311
+
312
+ - if a file has exactly one runnable component, `zhanla run file.py` auto-selects it
313
+ - if a file has multiple runnable components, use `file.py:component_name`
314
+ - if a file has exactly one eval, `--eval evals.py` auto-selects it
315
+ - if a referenced name is ambiguous or missing, the CLI exits with an error
316
+
317
+ ## Validation
318
+
319
+ The CLI validates component structure before execution.
320
+
321
+ - `Tool` must provide a callable `fn`
322
+ - `Tool` must declare a non-`None` `output_schema`
323
+ - `CodeEval` must provide a callable `fn`
324
+ - `Skill`, `Agent`, `LLMProcessor`, and `LLMEval` must define `instructions`
325
+ - `Agent`, `LLMProcessor`, and `LLMEval` must define `model`
326
+ - `Orchestration` step targets must exist and the graph must be acyclic
327
+ - `Checklist` weights must match the number of evals and be positive
328
+ - `EvalTree` branch thresholds must be in `[0.0, 1.0]`
329
+ - `EvalTree` edge weights must be positive
330
+
331
+ For local component runs with an `output_schema`, the CLI also validates the first produced output for:
332
+
333
+ - missing keys
334
+ - extra keys
335
+ - simple `isinstance` type mismatches
336
+
337
+ Schema mismatches stop the run immediately.
338
+
339
+ ## Output And Summaries
340
+
341
+ ### Local eval summary
342
+
343
+ For local evals, the CLI prints a score table and a mean score summary.
344
+
345
+ Without upload:
346
+
347
+ ```text
348
+ Mean score: 0.900
349
+ Dry run — nothing uploaded
350
+ ```
351
+
352
+ With upload:
353
+
354
+ - prints `Results uploaded`
355
+ - prints `Autorater ID` and `Autorater Run ID` when available
356
+ - prints a result URL when available
357
+
358
+ ### Remote evaluation summary
359
+
360
+ For `--web-eval` and `--web-config` flows, the CLI prints a remote summary table including:
361
+
362
+ - run status
363
+ - overall score
364
+ - items completed vs total
365
+ - remote error, if any
366
+
367
+ ## `zhanla list datasets`
368
+
369
+ List datasets available in the web app:
370
+
371
+ ```bash
372
+ bench list datasets
373
+ ```
374
+
375
+ Optional filters:
376
+
377
+ ```bash
378
+ bench list datasets --component-type tool
379
+ bench list datasets --component-id component-uuid
380
+ bench list datasets --name support
381
+ ```
382
+
383
+ Supported `--component-type` values:
384
+
385
+ - `agent`
386
+ - `skill`
387
+ - `tool`
388
+ - `orchestration`
389
+
390
+ The command requires login and prints dataset IDs that can be used with `--web-dataset`.
391
+
392
+ ## `zhanla list autoraters`
393
+
394
+ List managed autoraters available in the web app:
395
+
396
+ ```bash
397
+ bench list autoraters
398
+ ```
399
+
400
+ Optional filters:
401
+
402
+ ```bash
403
+ bench list autoraters --component-type tool
404
+ bench list autoraters --component-id component-uuid
405
+ bench list autoraters --name quality
406
+ ```
407
+
408
+ This command also requires login and prints autorater IDs that can be used with `--web-eval`.
409
+
410
+ ## Environment Variables
411
+
412
+ | Variable | Default | Description |
413
+ |---|---|---|
414
+ | `BENCH_BASE_URL` | `https://app.benchmark.dev` | Base URL for auth, evaluation APIs, and dashboard links |
415
+
416
+ ## File Locations
417
+
418
+ | Path | Purpose |
419
+ |---|---|
420
+ | `~/.benchmark/credentials.json` | Saved SDK credentials and org metadata |
421
+
422
+ ## Upload Behavior
423
+
424
+ For authenticated local runs, the CLI syncs component definitions and run results to Supabase using the short-lived access token obtained from your API key.
425
+
426
+ At a high level it:
427
+
428
+ - creates an authenticated Supabase client
429
+ - syncs or updates component definitions using content-based version hashes
430
+ - creates or reuses datasets and dataset items for local datasets
431
+ - links datasets back to the component definition
432
+ - writes component and eval run records
433
+
434
+ For local component + web autorater runs, the CLI additionally starts a remote evaluate-only run after upload.
435
+
436
+ Structured component outputs are still preserved in traces and uploaded run data. Only the eval-function boundary is normalized to plain text.
437
+
438
+ ## Examples
439
+
440
+ Run a local tool against a local eval and skip upload:
441
+
442
+ ```bash
443
+ bench run component.py:my_tool --dataset data.json --eval eval.py:my_eval --dry-run
444
+ ```
445
+
446
+ Run a local component and send outputs to a managed autorater:
447
+
448
+ ```bash
449
+ bench run component.py:my_tool --dataset data.json --web-eval 123e4567-e89b-12d3-a456-426614174000
450
+ ```
451
+
452
+ Run fully against web-managed prompt, dataset, and autorater resources:
453
+
454
+ ```bash
455
+ bench run --web-config prompt-123 --web-dataset dataset-123 --web-eval autorater-123
456
+ ```
457
+
458
+ List available datasets:
459
+
460
+ ```bash
461
+ bench list datasets
462
+ ```
463
+
464
+ List available autoraters:
465
+
466
+ ```bash
467
+ bench list autoraters
468
+ ```
469
+
470
+ ## Running Tests
471
+
472
+ ```bash
473
+ python3 -m pytest packages/cli -v
474
+ ```
475
+
476
+ The test suite covers:
477
+
478
+ - auth credential persistence
479
+ - component and eval discovery
480
+ - component validation
481
+ - dataset loading and schema validation
482
+ - local execution and eval execution
483
+ - run command behavior for dry runs, uploads, and web-backed flows
484
+ - writer upload behavior
@@ -0,0 +1,18 @@
1
+ zhanla_cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ zhanla_cli/auth.py,sha256=9CUc9Kpm5-MF4ao8n0VsKHo60aqGO2TVD9OX4PdD3rw,1769
3
+ zhanla_cli/discovery.py,sha256=BIV_odbQovAzqIO_NFuJd0NDdtnAisloARAfmHiCQug,12829
4
+ zhanla_cli/eval_contract.py,sha256=V6jjnx49KroEndIDVSonVCNqVJHgI-Vm65PFu_kzW60,1519
5
+ zhanla_cli/evaluations.py,sha256=SNLjvjBvjfgG2Y5QXFC1dta0ZG0axWNmLFgEmN3244Y,5385
6
+ zhanla_cli/executor.py,sha256=fQf_VrbOc4sZZEzY234V8FBTnAZDXHzAMlUyOCsP1RI,26426
7
+ zhanla_cli/graph_builder.py,sha256=KpcVEyC367ztjwruHceIOYs0Nld549DM5HSJtwTWVDU,3593
8
+ zhanla_cli/main.py,sha256=6YMtB6BJaMTRGofe9hpJ34baYRSPFknmxxac7BAWEDQ,33429
9
+ zhanla_cli/manifest.py,sha256=2nRIq87BAjhzNHlh6lTWgJHOBt3yFhgR-ADnMP1JAzw,593
10
+ zhanla_cli/runners.py,sha256=Jbi68moBKK7g6WBqYasTRCNcj0SS3vSd7Wd2v4mpLmU,12035
11
+ zhanla_cli/ts_adapter.py,sha256=9TDooL2nZDuxzUsFBN01I3ziuv47JlrcOmR6MFvTaFg,7238
12
+ zhanla_cli/ui.py,sha256=w7TJay71S7fdL32BiaTw6a8i12Gu9n1PHpi2nEiuTb0,6236
13
+ zhanla_cli/web.py,sha256=bo7IUVQsocB8gKSGKW0zQq-QQOgLnmKiFzyWBwNpvzs,4302
14
+ zhanla_cli/writer.py,sha256=HNg7W7DtTRRkAmH32QcsnR0_UfN0iFvwEnCfcukoTdI,38692
15
+ zhanla-0.1.0.dist-info/METADATA,sha256=5BbACC-7S95OmDojpsE0sohQIwadTwgPtQMQYBlJBs8,13541
16
+ zhanla-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
17
+ zhanla-0.1.0.dist-info/entry_points.txt,sha256=gWd_4Iq-ZrID1iJjjx7ROb6yQIpJFK-GkqDXbe0gg1w,47
18
+ zhanla-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ zhanla = zhanla_cli.main:app
zhanla_cli/__init__.py ADDED
File without changes
zhanla_cli/auth.py ADDED
@@ -0,0 +1,56 @@
1
+ """Authentication helpers for the bench CLI."""
2
+ import json
3
+ import os
4
+ from pathlib import Path
5
+ from typing import Optional
6
+
7
+ import httpx
8
+
9
+ CREDENTIALS_PATH = Path.home() / ".benchmark" / "credentials.json"
10
+
11
+
12
+ def get_credentials() -> Optional[dict]:
13
+ """Load saved credentials from disk."""
14
+ if not CREDENTIALS_PATH.exists():
15
+ return None
16
+ return json.loads(CREDENTIALS_PATH.read_text())
17
+
18
+
19
+ def save_credentials(data: dict) -> None:
20
+ """Persist credentials to disk, creating parent directories as needed."""
21
+ CREDENTIALS_PATH.parent.mkdir(parents=True, exist_ok=True)
22
+ CREDENTIALS_PATH.write_text(json.dumps(data, indent=2))
23
+
24
+
25
+ def delete_credentials() -> None:
26
+ """Remove the credentials file if it exists."""
27
+ if CREDENTIALS_PATH.exists():
28
+ CREDENTIALS_PATH.unlink()
29
+
30
+
31
+ def exchange_key_for_token(key_id: str, secret: str, base_url: str) -> dict:
32
+ """Exchange an SDK API key for a short-lived Supabase JWT.
33
+
34
+ Calls POST /api/v1/auth/token and returns the response JSON, which
35
+ includes: access_token, supabase_url, org_id, expires_at.
36
+ """
37
+ resp = httpx.post(
38
+ f"{base_url}/api/v1/auth/token",
39
+ json={"key_id": key_id, "secret": secret},
40
+ timeout=10.0,
41
+ )
42
+ resp.raise_for_status()
43
+ return resp.json()
44
+
45
+
46
+ def get_fresh_token(base_url: str) -> dict:
47
+ """Load credentials from disk and exchange them for a fresh JWT.
48
+
49
+ Returns a merged dict of credentials + token data:
50
+ key_id, secret, supabase_url, org_id, access_token, expires_at
51
+ """
52
+ creds = get_credentials()
53
+ if not creds:
54
+ raise RuntimeError("Not logged in. Run `zhanla login` first.")
55
+ token_data = exchange_key_for_token(creds["key_id"], creds["secret"], base_url)
56
+ return {**creds, **token_data}