rakam-eval-sdk 0.1.16rc1__tar.gz → 0.2.0rc1__tar.gz

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.
@@ -1,9 +1,10 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: rakam-eval-sdk
3
- Version: 0.1.16rc1
3
+ Version: 0.2.0rc1
4
4
  Summary: Evaluation Framework SDK
5
5
  Author: Mohamed Bachar Touil
6
6
  License: MIT
7
+ Requires-Dist: dotenv>=0.9.9
7
8
  Requires-Dist: psutil>=7.2.1
8
9
  Requires-Dist: pydantic>=2.10.6
9
10
  Requires-Dist: requests
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "rakam-eval-sdk"
7
- version = "0.1.16rc1"
7
+ version = "0.2.0rc1"
8
8
  description = "Evaluation Framework SDK"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.8"
@@ -13,6 +13,7 @@ authors = [
13
13
  { name = "Mohamed Bachar Touil" }
14
14
  ]
15
15
  dependencies = [
16
+ "dotenv>=0.9.9",
16
17
  "psutil>=7.2.1",
17
18
  "pydantic>=2.10.6",
18
19
  "requests",
@@ -25,6 +26,9 @@ dev = [
25
26
  "pytest>=8.3.5",
26
27
  "twine>=6.1.0",
27
28
  ]
29
+ [tool.pytest.ini_options]
30
+ testpaths = ["tests"]
31
+ python_files = "test_*.py"
28
32
 
29
33
  [tool.isort]
30
34
  profile = "black"
@@ -39,6 +43,10 @@ name = "testpypi"
39
43
  url = "https://test.pypi.org/simple/"
40
44
  publish-url = "https://test.pypi.org/legacy/"
41
45
  explicit = true
46
+ [tool.setuptools]
47
+ package-dir = {"" = "src"}
42
48
 
49
+ [tool.setuptools.packages.find]
50
+ where = ["src"]
43
51
  [project.scripts]
44
52
  rakam_eval = "rakam_eval_sdk.cli:main"
@@ -0,0 +1,527 @@
1
+ # cli.py
2
+ import json
3
+ import os
4
+ import sys
5
+ import uuid
6
+ from datetime import datetime
7
+ from pathlib import Path
8
+ from pprint import pprint
9
+ from typing import Any, Optional
10
+
11
+ import typer
12
+ from dotenv import load_dotenv
13
+ from rich.console import Console
14
+ from rich.panel import Panel
15
+ from rich.pretty import Pretty
16
+
17
+ from rakam_eval_sdk.client import DeepEvalClient
18
+ from rakam_eval_sdk.decorators import eval_run
19
+ from rakam_eval_sdk.utils.decorator_utils import (
20
+ find_decorated_functions,
21
+ load_module_from_path,
22
+ )
23
+
24
+ load_dotenv()
25
+ app = typer.Typer(help="CLI tools for evaluation utilities")
26
+ console = Console()
27
+
28
+ # add root of the project to sys.path
29
+ PROJECT_ROOT = os.path.abspath(".")
30
+ if PROJECT_ROOT not in sys.path:
31
+ sys.path.insert(0, PROJECT_ROOT)
32
+
33
+
34
+ @app.command()
35
+ def list(
36
+ directory: Path = typer.Argument(
37
+ Path("./eval"),
38
+ exists=True,
39
+ file_okay=False,
40
+ dir_okay=True,
41
+ help="Directory to scan (default: ./eval)",
42
+ ),
43
+ recursive: bool = typer.Option(
44
+ False,
45
+ "--recursive",
46
+ "-r",
47
+ help="Recursively search for Python files",
48
+ ),
49
+ ) -> None:
50
+ """
51
+ Find functions decorated with @track.
52
+ """
53
+ TARGET_DECORATOR = eval_run.__name__
54
+ files = directory.rglob("*.py") if recursive else directory.glob("*.py")
55
+
56
+ found = False
57
+
58
+ for file in sorted(files):
59
+ functions = find_decorated_functions(file, TARGET_DECORATOR)
60
+ for fn in functions:
61
+ found = True
62
+ typer.echo(f"{file}:{fn}")
63
+
64
+ if not found:
65
+ typer.echo(f"No @{TARGET_DECORATOR} functions found.")
66
+
67
+
68
+ list_app = typer.Typer(help="List resources")
69
+ app.add_typer(list_app, name="list")
70
+
71
+
72
+ @list_app.command("runs")
73
+ def list_runs(
74
+ limit: int = typer.Option(20, help="Max number of runs"),
75
+ offset: int = typer.Option(0, help="Pagination offset"),
76
+ status: Optional[str] = typer.Option(
77
+ None, help="Filter by status (running, completed, failed)"
78
+ ),
79
+ ):
80
+ """
81
+ List evaluation runs (newest first).
82
+ """
83
+ client = DeepEvalClient()
84
+
85
+ runs = client.list_evaluation_testcases(
86
+ limit=limit,
87
+ offset=offset,
88
+ raise_exception=True,
89
+ )
90
+
91
+ if not runs:
92
+ typer.echo("No evaluation runs found.")
93
+ return
94
+
95
+ # optional status filtering (client-side for now)
96
+ if status:
97
+ runs = [
98
+ r for r in runs
99
+ if r.get("result", {}).get("status") == status
100
+ ]
101
+
102
+ typer.echo(
103
+ f"[id] "
104
+ f"{'unique_id':<20}"
105
+ f"{'label':<20}"
106
+ f"created_at"
107
+ )
108
+ # pretty CLI output
109
+ for run in runs:
110
+ run_id = run.get("id")
111
+ label = run.get("label") or "-"
112
+ uid = run.get("unique_id") or "-"
113
+ created_at = run.get("created_at")
114
+
115
+ if created_at:
116
+ try:
117
+ created_at = datetime.fromisoformat(created_at).strftime(
118
+ "%Y-%m-%d %H:%M:%S"
119
+ )
120
+ except ValueError:
121
+ pass
122
+
123
+ typer.echo(
124
+ f"[{run_id}] "
125
+ f"{uid:<20} "
126
+ f"{label:<20} "
127
+ f"{created_at}"
128
+ )
129
+
130
+
131
+ @list_app.command("show")
132
+ def show_testcase(
133
+ id: Optional[int] = typer.Option(
134
+ None,
135
+ "--id",
136
+ help="Numeric evaluation testcase ID",
137
+ ),
138
+ uid: Optional[str] = typer.Option(
139
+ None,
140
+ "--uid",
141
+ help="Evaluation testcase unique_id",
142
+ ),
143
+ raw: bool = typer.Option(
144
+ False,
145
+ "--raw",
146
+ help="Print raw JSON instead of formatted output",
147
+ ),
148
+ ):
149
+ """
150
+ Show a single evaluation testcase by ID or unique_id.
151
+ """
152
+ if not id and not uid:
153
+ raise typer.BadParameter("You must provide either --id or --uid")
154
+
155
+ if id and uid:
156
+ raise typer.BadParameter("Provide only one of --id or --uid")
157
+
158
+ client = DeepEvalClient()
159
+
160
+ if id:
161
+ result = client.get_evaluation_testcase_by_id(id)
162
+ identifier = f"id={id}"
163
+ else:
164
+ result = client.get_evaluation_testcase_by_unique_id(uid)
165
+ identifier = f"unique_id={uid}"
166
+
167
+ if not result:
168
+ console.print(
169
+ Panel(
170
+ f"No response received for {identifier}",
171
+ title="Error",
172
+ style="red",
173
+ )
174
+ )
175
+ raise typer.Exit(code=1)
176
+
177
+ if isinstance(result, dict) and result.get("error"):
178
+ console.print(
179
+ Panel(
180
+ result["error"],
181
+ title="Error",
182
+ style="red",
183
+ )
184
+ )
185
+ raise typer.Exit(code=1)
186
+
187
+ if raw:
188
+ console.print(Pretty(result))
189
+ raise typer.Exit()
190
+
191
+ console.print(
192
+ Panel.fit(
193
+ Pretty(result),
194
+ title="Evaluation TestCase",
195
+ subtitle=identifier,
196
+ )
197
+ )
198
+
199
+
200
+ def validate_eval_result(result: Any, fn_name: str) -> str:
201
+ eval_config = getattr(result, "__eval_config__", None)
202
+
203
+ if not isinstance(eval_config, str):
204
+ expected = "EvalConfig or SchemaEvalConfig"
205
+ actual = type(result).__name__
206
+
207
+ typer.echo(
208
+ f" ❌ Invalid return type from `{fn_name}`\n"
209
+ f" Expected: {expected}\n"
210
+ f" Got: {actual}"
211
+ )
212
+ return ""
213
+
214
+ return eval_config
215
+
216
+
217
+ @app.command()
218
+ def run(
219
+ directory: Path = typer.Argument(
220
+ Path("./eval"),
221
+ exists=True,
222
+ file_okay=False,
223
+ dir_okay=True,
224
+ help="Directory to scan (default: ./eval)",
225
+ ),
226
+ recursive: bool = typer.Option(
227
+ False,
228
+ "-r",
229
+ "--recursive",
230
+ help="Recursively search for Python files",
231
+ ),
232
+ dry_run: bool = typer.Option(
233
+ False,
234
+ "--dry-run",
235
+ help="Only list functions without executing them",
236
+ ),
237
+ save_runs: bool = typer.Option(
238
+ False,
239
+ "--save-runs",
240
+ help="Save each evaluation run result to a JSON file",
241
+ ),
242
+ output_dir: Path = typer.Option(
243
+ Path("./eval_runs"),
244
+ "--output-dir",
245
+ help="Directory where run results are saved",
246
+ ),
247
+ ) -> None:
248
+ """
249
+ Find and execute all functions decorated with @eval_run.
250
+ """
251
+ files = directory.rglob("*.py") if recursive else directory.glob("*.py")
252
+ TARGET_DECORATOR = eval_run.__name__
253
+
254
+ executed_any = False
255
+
256
+ if save_runs and not dry_run:
257
+ output_dir.mkdir(parents=True, exist_ok=True)
258
+
259
+ for file in sorted(files):
260
+ functions = find_decorated_functions(file, TARGET_DECORATOR)
261
+ if not functions:
262
+ continue
263
+
264
+ typer.echo(f"\n📄 {file}")
265
+
266
+ module = None
267
+ if not dry_run:
268
+ try:
269
+ module = load_module_from_path(file)
270
+ except Exception as e:
271
+ typer.echo(f" ❌ Failed to import module: {e}")
272
+ continue
273
+
274
+ for fn_name in functions:
275
+ typer.echo(f" ▶ {fn_name}")
276
+
277
+ if dry_run:
278
+ continue
279
+
280
+ try:
281
+ func = getattr(module, fn_name)
282
+ result = func()
283
+
284
+ eval_type = validate_eval_result(result, fn_name)
285
+ if not eval_type:
286
+ continue
287
+
288
+ client = DeepEvalClient()
289
+
290
+ if eval_type == "text_eval":
291
+ resp = client.text_eval(config=result)
292
+ else:
293
+ resp = client.schema_eval(config=result)
294
+
295
+ typer.echo(f"{resp}")
296
+ executed_any = True
297
+ typer.echo(f" ✅ Returned {type(result).__name__}")
298
+
299
+ if save_runs:
300
+ run_id = (
301
+ resp["id"]
302
+ if resp is not None and "id" in resp
303
+ else uuid.uuid4().hex[:8]
304
+ )
305
+
306
+ output_path = output_dir / f"run_{fn_name}_{run_id}.json"
307
+
308
+ def to_json_safe(obj: Any) -> Any:
309
+ if hasattr(obj, "model_dump"):
310
+ return obj.model_dump()
311
+ if hasattr(obj, "dict"):
312
+ return obj.dict()
313
+ return obj
314
+
315
+ with output_path.open("w", encoding="utf-8") as f:
316
+ json.dump(
317
+ to_json_safe(resp),
318
+ f,
319
+ indent=2,
320
+ ensure_ascii=False,
321
+ )
322
+
323
+ typer.echo(f" 💾 Saved run → {output_path}")
324
+
325
+ except Exception as e:
326
+ typer.echo(f" ❌ Execution failed: {e}")
327
+
328
+ if not executed_any and not dry_run:
329
+ typer.echo("\nNo @eval_run functions executed.")
330
+
331
+
332
+ def _print_and_save(
333
+ resp: dict,
334
+ pretty: bool,
335
+ out: Path | None,
336
+ overwrite: bool,
337
+ ) -> None:
338
+ if pretty:
339
+ typer.echo(typer.style("📊 Result:", bold=True))
340
+ pprint(resp)
341
+ else:
342
+ typer.echo(resp)
343
+
344
+ if out is None:
345
+ return
346
+
347
+ if out.exists() and not overwrite:
348
+ typer.echo(
349
+ f"❌ File already exists: {out} (use --overwrite to replace)")
350
+ raise typer.Exit(code=1)
351
+
352
+ out.parent.mkdir(parents=True, exist_ok=True)
353
+
354
+ with out.open("w", encoding="utf-8") as f:
355
+ json.dump(resp, f, indent=2, ensure_ascii=False)
356
+
357
+ typer.echo(f"💾 Result saved to {out}")
358
+
359
+
360
+ @app.command()
361
+ def compare_testcases(
362
+ testcase_a_id: int = typer.Argument(
363
+ ...,
364
+ help="ID of the first testcase",
365
+ ),
366
+ testcase_b_id: int = typer.Argument(
367
+ ...,
368
+ help="ID of the second testcase",
369
+ ),
370
+ pretty: bool = typer.Option(
371
+ True,
372
+ "--pretty/--raw",
373
+ help="Pretty-print the response",
374
+ ),
375
+ raise_exception: bool = typer.Option(
376
+ False,
377
+ "--raise",
378
+ help="Raise HTTP exceptions instead of swallowing them",
379
+ ),
380
+ out: Path | None = typer.Option(
381
+ None,
382
+ "-o",
383
+ "--out",
384
+ help="Optional file path to save the result as JSON",
385
+ ),
386
+ overwrite: bool = typer.Option(
387
+ False,
388
+ "--overwrite",
389
+ help="Overwrite output file if it already exists",
390
+ ),
391
+ ) -> None:
392
+ """
393
+ Compare two DeepEval evaluation testcases.
394
+ """
395
+ client = DeepEvalClient()
396
+
397
+ typer.echo(f"🔍 Comparing testcases {testcase_a_id} ↔ {testcase_b_id}")
398
+
399
+ try:
400
+ resp = client.compare_testcases(
401
+ testcase_a_id=testcase_a_id,
402
+ testcase_b_id=testcase_b_id,
403
+ raise_exception=raise_exception,
404
+ )
405
+ except Exception as e:
406
+ typer.echo(f"❌ Request failed: {e}")
407
+ raise typer.Exit(code=1)
408
+
409
+ if not resp:
410
+ typer.echo("⚠️ No response received")
411
+ raise typer.Exit(code=1)
412
+ _print_and_save(resp, pretty, out, overwrite)
413
+
414
+
415
+ @app.command()
416
+ def compare_label_latest(
417
+ label_a: str = typer.Argument(
418
+ ...,
419
+ help="First label (latest run will be used)",
420
+ ),
421
+ label_b: str = typer.Argument(
422
+ ...,
423
+ help="Second label (latest run will be used)",
424
+ ),
425
+ pretty: bool = typer.Option(
426
+ True,
427
+ "--pretty/--raw",
428
+ help="Pretty-print the response",
429
+ ),
430
+ raise_exception: bool = typer.Option(
431
+ False,
432
+ "--raise",
433
+ help="Raise HTTP exceptions instead of swallowing them",
434
+ ),
435
+ out: Path | None = typer.Option(
436
+ None,
437
+ "-o",
438
+ "--out",
439
+ help="Optional file path to save the result as JSON",
440
+ ),
441
+ overwrite: bool = typer.Option(
442
+ False,
443
+ "--overwrite",
444
+ help="Overwrite output file if it already exists",
445
+ ),
446
+ ) -> None:
447
+ """
448
+ Compare the latest evaluation runs for two labels.
449
+ """
450
+ client = DeepEvalClient()
451
+
452
+ typer.echo(f"🔍 Comparing latest runs: '{label_a}' ↔ '{label_b}'")
453
+
454
+ try:
455
+ resp = client.compare_latest_by_labels(
456
+ label_a=label_a,
457
+ label_b=label_b,
458
+ raise_exception=raise_exception,
459
+ )
460
+ except Exception as e:
461
+ typer.echo(f"❌ Request failed: {e}")
462
+ raise typer.Exit(code=1)
463
+
464
+ if not resp:
465
+ typer.echo("⚠️ No response received")
466
+ raise typer.Exit(code=1)
467
+
468
+ _print_and_save(resp, pretty, out, overwrite)
469
+
470
+
471
+ @app.command()
472
+ def compare_last(
473
+ label: str = typer.Argument(
474
+ ...,
475
+ help="Label whose last two runs will be compared",
476
+ ),
477
+ pretty: bool = typer.Option(
478
+ True,
479
+ "--pretty/--raw",
480
+ help="Pretty-print the response",
481
+ ),
482
+ raise_exception: bool = typer.Option(
483
+ False,
484
+ "--raise",
485
+ help="Raise HTTP exceptions instead of swallowing them",
486
+ ),
487
+ out: Path | None = typer.Option(
488
+ None,
489
+ "-o",
490
+ "--out",
491
+ help="Optional file path to save the result as JSON",
492
+ ),
493
+ overwrite: bool = typer.Option(
494
+ False,
495
+ "--overwrite",
496
+ help="Overwrite output file if it already exists",
497
+ ),
498
+ ) -> None:
499
+ """
500
+ Compare the last two evaluation runs of a label.
501
+ """
502
+ client = DeepEvalClient()
503
+
504
+ typer.echo(f"🔍 Comparing last two runs for label '{label}'")
505
+
506
+ try:
507
+ resp = client.compare_last_two_by_label(
508
+ label=label,
509
+ raise_exception=raise_exception,
510
+ )
511
+ except Exception as e:
512
+ typer.echo(f"❌ Request failed: {e}")
513
+ raise typer.Exit(code=1)
514
+
515
+ if not resp:
516
+ typer.echo("⚠️ No response received")
517
+ raise typer.Exit(code=1)
518
+
519
+ _print_and_save(resp, pretty, out, overwrite)
520
+
521
+
522
+ def main() -> None:
523
+ app()
524
+
525
+
526
+ if __name__ == "__main__":
527
+ main()