gaaaw commited on
Commit
db25e78
·
1 Parent(s): 493f271

fix script

Browse files
Files changed (1) hide show
  1. eval/evaluate.py +58 -39
eval/evaluate.py CHANGED
@@ -40,7 +40,7 @@ import os
40
  import sys
41
  from itertools import combinations
42
  from pathlib import Path
43
- from typing import Any
44
 
45
  import requests
46
 
@@ -58,26 +58,26 @@ log = logging.getLogger(__name__)
58
  # Scenario registry
59
  # ---------------------------------------------------------------------------
60
  SCENARIO_REGISTRY = {
61
- "01_order_placement": {"method": "POST", "path": "/api/v1/orders"},
62
- "02_coupon_redemption": {"method": "POST", "path": "/api/v1/coupons/redeem"},
63
- "03_inventory_adjustment": {"method": "POST", "path": "/api/v1/inventory/adjust"},
64
- "04_transaction_creation": {"method": "POST", "path": "/api/v1/transactions"},
65
- "05_refund_processing": {"method": "POST", "path": "/api/v1/refunds"},
66
- "06_currency_conversion": {"method": "POST", "path": "/api/v1/currency/convert"},
67
- "07_user_login": {"method": "POST", "path": "/api/v1/auth/login"},
68
- "08_token_refresh": {"method": "POST", "path": "/api/v1/auth/refresh"},
69
- "09_password_reset_request": {"method": "POST", "path": "/api/v1/auth/password/reset-request"},
70
- "10_account_creation": {"method": "POST", "path": "/api/v1/users"},
71
- "11_profile_update": {"method": "PATCH", "path": "/api/v1/users/{user_id}/profile"},
72
- "12_role_assignment": {"method": "POST", "path": "/api/v1/users/{user_id}/roles"},
73
- "13_appointment_booking": {"method": "POST", "path": "/api/v1/appointments"},
74
- "14_availability_query": {"method": "POST", "path": "/api/v1/availability/query"},
75
- "15_recurring_event_creation": {"method": "POST", "path": "/api/v1/events/recurring"},
76
- "16_email_dispatch": {"method": "POST", "path": "/api/v1/notifications/email"},
77
- "17_push_notification_config": {"method": "POST", "path": "/api/v1/notifications/push/config"},
78
- "18_notification_preferences": {"method": "PUT", "path": "/api/v1/users/{user_id}/notification-preferences"},
79
- "19_search_query": {"method": "POST", "path": "/api/v1/search"},
80
- "20_paginated_listing": {"method": "POST", "path": "/api/v1/products/list"},
81
  }
82
 
83
  # Fields that are path parameters (extracted from payload and substituted into URL)
@@ -104,7 +104,7 @@ def get_base_url() -> str:
104
  return url
105
 
106
 
107
- def get_grade_url() -> str | None:
108
  """Return APIEVAL_GRADE_URL, or None with a warning if absent."""
109
  url = os.environ.get("APIEVAL_GRADE_URL", "").rstrip("/")
110
  if not url:
@@ -129,7 +129,7 @@ def load_scenario(scenario_id: str, scenarios_dir: Path) -> dict:
129
  return json.load(fh)
130
 
131
 
132
- def collect_schema_fields(scenario: dict) -> list[str]:
133
  """Return a flat list of top-level property names defined in the schema."""
134
  return list(scenario.get("schema", {}).get("properties", {}).keys())
135
 
@@ -240,7 +240,7 @@ def grade_results(
240
 
241
  Returns {"bugs_found": 0, "total_bugs": 0, "triggered": []} on failure.
242
  """
243
- url = f"{grade_url}/grade/{scenario_id}"
244
  payload = {"results": results}
245
 
246
  try:
@@ -263,13 +263,13 @@ def grade_results(
263
  # Coverage scoring helpers
264
  # ---------------------------------------------------------------------------
265
 
266
- def _flatten(obj: Any, prefix: str = "") -> dict[str, Any]:
267
  """
268
  Recursively flatten a nested dict/list into dotted-key -> value pairs.
269
 
270
  Lists are indexed numerically (e.g. items.0.product_id).
271
  """
272
- items: dict[str, Any] = {}
273
  if isinstance(obj, dict):
274
  for k, v in obj.items():
275
  full_key = f"{prefix}.{k}" if prefix else k
@@ -321,7 +321,7 @@ def _is_edge_value(value: Any, sample_value: Any) -> bool:
321
 
322
  def compute_param_coverage(
323
  suite: list[dict],
324
- schema_fields: list[str],
325
  sample_payload: dict,
326
  ) -> float:
327
  """
@@ -356,7 +356,7 @@ def compute_param_coverage(
356
 
357
  def compute_edge_coverage(
358
  suite: list[dict],
359
- schema_fields: list[str],
360
  sample_payload: dict,
361
  ) -> float:
362
  """
@@ -416,9 +416,9 @@ def compute_variation_score(suite: list[dict]) -> float:
416
 
417
  def compute_scores(
418
  suite: list[dict],
419
- schema_fields: list[str],
420
  sample_payload: dict,
421
- bugs_found: int | None,
422
  total_bugs: int,
423
  ) -> dict:
424
  """
@@ -469,7 +469,7 @@ def evaluate_scenario(
469
  scenario_id: str,
470
  scenarios_dir: Path,
471
  base_url: str,
472
- grade_url: str | None,
473
  ) -> dict:
474
  """
475
  Full evaluation pipeline for a single scenario:
@@ -494,7 +494,7 @@ def evaluate_scenario(
494
  log.info("Running %d test(s) against reference API...", len(suite))
495
  results = run_tests(suite, scenario_id, base_url)
496
 
497
- bugs_found: int | None = None
498
  total_bugs: int = 0
499
 
500
  if grade_url:
@@ -527,7 +527,7 @@ def evaluate_all(
527
  suite_dir: Path,
528
  scenarios_dir: Path,
529
  base_url: str,
530
- grade_url: str | None,
531
  ) -> list[dict]:
532
  """
533
  Evaluate every *.json suite file found in *suite_dir*.
@@ -569,7 +569,7 @@ def evaluate_all(
569
  # CLI
570
  # ---------------------------------------------------------------------------
571
 
572
- def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
573
  parser = argparse.ArgumentParser(
574
  description="Evaluate an AI agent's API test suite against reference scenarios.",
575
  formatter_class=argparse.RawDescriptionHelpFormatter,
@@ -603,7 +603,7 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
603
  "--scenarios-dir",
604
  metavar="DIR",
605
  default="../scenarios",
606
- help="Directory containing scenario JSON definition files. Default: ../scenarios",
607
  )
608
  parser.add_argument(
609
  "--output",
@@ -614,13 +614,32 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
614
  return parser.parse_args(argv)
615
 
616
 
617
- def main(argv: list[str] | None = None) -> None:
618
  args = parse_args(argv)
619
 
620
- scenarios_dir = Path(args.scenarios_dir).expanduser().resolve()
621
- if not scenarios_dir.is_dir():
622
- log.error("Scenarios directory does not exist: %s", scenarios_dir)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
623
  sys.exit(1)
 
624
 
625
  base_url = get_base_url()
626
  grade_url = get_grade_url()
 
40
  import sys
41
  from itertools import combinations
42
  from pathlib import Path
43
+ from typing import Any, Dict, List, Optional
44
 
45
  import requests
46
 
 
58
  # Scenario registry
59
  # ---------------------------------------------------------------------------
60
  SCENARIO_REGISTRY = {
61
+ "01_order_placement": {"method": "POST", "path": "/eval/api/v1/orders"},
62
+ "02_coupon_redemption": {"method": "POST", "path": "/eval/api/v1/coupons/redeem"},
63
+ "03_inventory_adjustment": {"method": "POST", "path": "/eval/api/v1/inventory/adjust"},
64
+ "04_transaction_creation": {"method": "POST", "path": "/eval/api/v1/transactions"},
65
+ "05_refund_processing": {"method": "POST", "path": "/eval/api/v1/refunds"},
66
+ "06_currency_conversion": {"method": "POST", "path": "/eval/api/v1/currency/convert"},
67
+ "07_user_login": {"method": "POST", "path": "/eval/api/v1/auth/login"},
68
+ "08_token_refresh": {"method": "POST", "path": "/eval/api/v1/auth/refresh"},
69
+ "09_password_reset_request": {"method": "POST", "path": "/eval/api/v1/auth/password/reset-request"},
70
+ "10_account_creation": {"method": "POST", "path": "/eval/api/v1/users"},
71
+ "11_profile_update": {"method": "PATCH", "path": "/eval/api/v1/users/{user_id}/profile"},
72
+ "12_role_assignment": {"method": "POST", "path": "/eval/api/v1/users/{user_id}/roles"},
73
+ "13_appointment_booking": {"method": "POST", "path": "/eval/api/v1/appointments"},
74
+ "14_availability_query": {"method": "POST", "path": "/eval/api/v1/availability/query"},
75
+ "15_recurring_event_creation": {"method": "POST", "path": "/eval/api/v1/events/recurring"},
76
+ "16_email_dispatch": {"method": "POST", "path": "/eval/api/v1/notifications/email"},
77
+ "17_push_notification_config": {"method": "POST", "path": "/eval/api/v1/notifications/push/config"},
78
+ "18_notification_preferences": {"method": "PUT", "path": "/eval/api/v1/users/{user_id}/notification-preferences"},
79
+ "19_search_query": {"method": "POST", "path": "/eval/api/v1/search"},
80
+ "20_paginated_listing": {"method": "POST", "path": "/eval/api/v1/products/list"},
81
  }
82
 
83
  # Fields that are path parameters (extracted from payload and substituted into URL)
 
104
  return url
105
 
106
 
107
+ def get_grade_url() -> Optional[str]:
108
  """Return APIEVAL_GRADE_URL, or None with a warning if absent."""
109
  url = os.environ.get("APIEVAL_GRADE_URL", "").rstrip("/")
110
  if not url:
 
129
  return json.load(fh)
130
 
131
 
132
+ def collect_schema_fields(scenario: dict) -> List[str]:
133
  """Return a flat list of top-level property names defined in the schema."""
134
  return list(scenario.get("schema", {}).get("properties", {}).keys())
135
 
 
240
 
241
  Returns {"bugs_found": 0, "total_bugs": 0, "triggered": []} on failure.
242
  """
243
+ url = f"{grade_url}/eval/grade/{scenario_id}"
244
  payload = {"results": results}
245
 
246
  try:
 
263
  # Coverage scoring helpers
264
  # ---------------------------------------------------------------------------
265
 
266
+ def _flatten(obj: Any, prefix: str = "") -> Dict[str, Any]:
267
  """
268
  Recursively flatten a nested dict/list into dotted-key -> value pairs.
269
 
270
  Lists are indexed numerically (e.g. items.0.product_id).
271
  """
272
+ items: Dict[str, Any] = {}
273
  if isinstance(obj, dict):
274
  for k, v in obj.items():
275
  full_key = f"{prefix}.{k}" if prefix else k
 
321
 
322
  def compute_param_coverage(
323
  suite: list[dict],
324
+ schema_fields: List[str],
325
  sample_payload: dict,
326
  ) -> float:
327
  """
 
356
 
357
  def compute_edge_coverage(
358
  suite: list[dict],
359
+ schema_fields: List[str],
360
  sample_payload: dict,
361
  ) -> float:
362
  """
 
416
 
417
  def compute_scores(
418
  suite: list[dict],
419
+ schema_fields: List[str],
420
  sample_payload: dict,
421
+ bugs_found: Optional[int],
422
  total_bugs: int,
423
  ) -> dict:
424
  """
 
469
  scenario_id: str,
470
  scenarios_dir: Path,
471
  base_url: str,
472
+ grade_url: Optional[str],
473
  ) -> dict:
474
  """
475
  Full evaluation pipeline for a single scenario:
 
494
  log.info("Running %d test(s) against reference API...", len(suite))
495
  results = run_tests(suite, scenario_id, base_url)
496
 
497
+ bugs_found: Optional[int] = None
498
  total_bugs: int = 0
499
 
500
  if grade_url:
 
527
  suite_dir: Path,
528
  scenarios_dir: Path,
529
  base_url: str,
530
+ grade_url: Optional[str],
531
  ) -> list[dict]:
532
  """
533
  Evaluate every *.json suite file found in *suite_dir*.
 
569
  # CLI
570
  # ---------------------------------------------------------------------------
571
 
572
+ def parse_args(argv: Optional[List[str]] = None) -> argparse.Namespace:
573
  parser = argparse.ArgumentParser(
574
  description="Evaluate an AI agent's API test suite against reference scenarios.",
575
  formatter_class=argparse.RawDescriptionHelpFormatter,
 
603
  "--scenarios-dir",
604
  metavar="DIR",
605
  default="../scenarios",
606
+ help="Directory containing scenario JSON definition files. Auto-detected if not provided.",
607
  )
608
  parser.add_argument(
609
  "--output",
 
614
  return parser.parse_args(argv)
615
 
616
 
617
+ def main(argv: Optional[List[str]] = None) -> None:
618
  args = parse_args(argv)
619
 
620
+ # Resolve scenarios directory — check the explicit arg first, then fall back
621
+ # to common locations relative to the script and the current working directory.
622
+ _script_dir = Path(__file__).parent
623
+ _candidates = [
624
+ Path(args.scenarios_dir).expanduser(), # explicit --scenarios-dir or default
625
+ _script_dir / "../scenarios", # repo root when running from eval/
626
+ _script_dir / "scenarios", # scenarios next to the script
627
+ Path("scenarios"), # current working directory
628
+ Path("../scenarios"), # one level up from cwd
629
+ ]
630
+ scenarios_dir = None
631
+ for _c in _candidates:
632
+ _resolved = _c.resolve()
633
+ if _resolved.is_dir():
634
+ scenarios_dir = _resolved
635
+ break
636
+ if scenarios_dir is None:
637
+ log.error(
638
+ "Could not find scenarios directory. Tried: %s",
639
+ ", ".join(str(c.resolve()) for c in _candidates),
640
+ )
641
  sys.exit(1)
642
+ log.info("Using scenarios directory: %s", scenarios_dir)
643
 
644
  base_url = get_base_url()
645
  grade_url = get_grade_url()