Shiftedx's picture
Publish Shiftedx Bench v0.1.0
f039f41 verified
Raw
History Blame Contribute Delete
2.7 kB
from __future__ import annotations
import json
import re
from dataclasses import dataclass
from typing import Any
from .sandbox import run_python_submission
@dataclass(frozen=True)
class Score:
passed: bool
value: float
maximum: float
error: str | None = None
def response_text(response: dict[str, Any]) -> str:
return str(response.get("content") or "")
def strict_json(text: str) -> Any:
stripped = text.strip()
if stripped.startswith("```") or not stripped:
raise ValueError("Expected bare JSON without Markdown fences")
decoder = json.JSONDecoder()
value, end = decoder.raw_decode(stripped)
if stripped[end:].strip():
raise ValueError("Unexpected text after JSON value")
return value
def _normalize_tool_calls(response: dict[str, Any]) -> list[dict[str, Any]]:
normalized = []
for call in response.get("tool_calls") or []:
function = call.get("function") or {}
arguments = function.get("arguments", {})
if isinstance(arguments, str):
arguments = json.loads(arguments)
normalized.append({"name": function.get("name"), "arguments": arguments})
return normalized
def score_response(scorer: str, expected: Any, response: dict[str, Any]) -> Score:
try:
if scorer == "exact_text":
actual = response_text(response).strip()
passed = actual == str(expected)
elif scorer == "strict_json_exact":
actual = strict_json(response_text(response))
passed = actual == expected
elif scorer == "strict_json_subset":
actual = strict_json(response_text(response))
if not isinstance(actual, dict) or not isinstance(expected, dict):
passed = False
else:
passed = all(actual.get(key) == value for key, value in expected.items())
elif scorer == "tool_calls_exact":
actual = _normalize_tool_calls(response)
passed = actual == expected
elif scorer == "python_code":
text = response_text(response).strip()
match = re.fullmatch(r"```(?:python)?\s*(.*?)\s*```", text, re.DOTALL | re.IGNORECASE)
code = match.group(1) if match else text
outcome = run_python_submission(code, str(expected["tests"]))
passed = outcome["passed"]
return Score(passed, float(passed), 1.0, outcome.get("error"))
else:
raise ValueError(f"Unknown scorer: {scorer}")
return Score(passed, float(passed), 1.0, None if passed else "answer mismatch")
except Exception as exc:
return Score(False, 0.0, 1.0, f"{type(exc).__name__}: {exc}")