Skip to content

Personal AI, On Personal Devices

Python

Eval framework: silent-failure detection, surgical reruns, continuous-score reporting (#303)

Avanika Narayand7624510bb2f
diff --git a/src/openjarvis/agents/native_openhands.py b/src/openjarvis/agents/native_openhands.py
index 052596de..d20f2a99 100644
--- a/src/openjarvis/agents/native_openhands.py
+++ b/src/openjarvis/agents/native_openhands.py
@@ -251,36 +251,26 @@ class NativeOpenHandsAgent(ToolUsingAgent):
direct_messages = self._truncate_if_needed(direct_messages)
try:
result = self._generate(direct_messages)
- content = self._strip_think_tags(result.get("content", ""))
- usage = result.get("usage", {})
- self._emit_turn_end(turns=1)
- return AgentResult(
- content=content,
- tool_results=[],
- turns=1,
- metadata={
- "prompt_tokens": usage.get("prompt_tokens", 0),
- "completion_tokens": usage.get("completion_tokens", 0),
- "total_tokens": usage.get("total_tokens", 0),
- },
- )
- except Exception as exc:
- error_str = str(exc)
- if "400" in error_str:
- error_msg = (
- "The input is too long for the "
- "model's context window. "
- "Please try a shorter message."
- )
- else:
- error_msg = "The model returned an error: " + error_str
+ except Exception:
+ # Propagate to the eval runner / server bridge so the failure
+ # is recorded as an error instead of a fake "input too long"
+ # answer that silently scores as 0%. Telemetry boundary is
+ # still emitted before re-raising.
self._emit_turn_end(turns=1, error=True)
- return AgentResult(
- content=error_msg,
- tool_results=[],
- turns=1,
- metadata={"error": True},
- )
+ raise
+ content = self._strip_think_tags(result.get("content", ""))
+ usage = result.get("usage", {})
+ self._emit_turn_end(turns=1)
+ return AgentResult(
+ content=content,
+ tool_results=[],
+ turns=1,
+ metadata={
+ "prompt_tokens": usage.get("prompt_tokens", 0),
+ "completion_tokens": usage.get("completion_tokens", 0),
+ "total_tokens": usage.get("total_tokens", 0),
+ },
+ )
messages = self._build_messages(input, context, system_prompt=system_prompt)
@@ -314,22 +304,11 @@ class NativeOpenHandsAgent(ToolUsingAgent):
try:
result = self._generate(messages, **gen_kwargs)
- except Exception as exc:
- error_str = str(exc)
- if "400" in error_str:
- error_msg = (
- "The input is too long for the model's context window. "
- "Please try a shorter message."
- )
- else:
- error_msg = f"The model returned an error: {error_str}"
+ except Exception:
+ # Propagate so the eval runner records a real error rather
+ # than a fake "input too long" string that silently scores 0.
self._emit_turn_end(turns=turns, error=True)
- return AgentResult(
- content=error_msg,
- tool_results=all_tool_results,
- turns=turns,
- metadata={"error": True},
- )
+ raise
# Accumulate usage from this generate call
usage = result.get("usage", {})
diff --git a/src/openjarvis/engine/multi.py b/src/openjarvis/engine/multi.py
index 7fa48f14..909b79ba 100644
--- a/src/openjarvis/engine/multi.py
+++ b/src/openjarvis/engine/multi.py
@@ -56,14 +56,15 @@ class MultiEngine(InferenceEngine):
if key == "cloud":
logger.info("Routing cloud model %r to cloud engine", model)
return eng
- logger.warning(
- "Model %r not found in any engine (known: %s)",
- model,
- ", ".join(sorted(self._model_map.keys())),
+ # Non-cloud models: do NOT silently fall back to cloud. A transient
+ # vLLM outage during a long agentic run would otherwise route every
+ # call to cloud, producing confusing "invalid model ID" errors
+ # across all tasks.
+ raise ValueError(
+ f"Model {model!r} not found in any engine "
+ f"(known: {', '.join(sorted(self._model_map.keys())) or '<none>'}). "
+ f"Check that the expected backend (e.g. vLLM server) is reachable."
)
- # Fall back to the first engine — caller will see the
- # downstream error if the model doesn't exist there.
- return self._engines[0][1]
def generate(
self,
diff --git a/src/openjarvis/evals/cli.py b/src/openjarvis/evals/cli.py
index 8294fb6f..d4781f7f 100644
--- a/src/openjarvis/evals/cli.py
+++ b/src/openjarvis/evals/cli.py
@@ -1426,6 +1426,154 @@ def summarize(jsonl_path):
console.print(f"[cyan]Errors:[/cyan] {len(errors)}")
[email protected]("reparse-judge")
+ "--jsonl",
+ "jsonl_path",
+ required=True,
+ type=click.Path(exists=True),
+ help="Path to a results JSONL produced by an LLM-judge benchmark.",
+)
+ "--out",
+ "out_path",
+ default=None,
+ type=click.Path(),
+ help=(
+ "Output JSONL path. Defaults to <jsonl>.reparsed when "
+ "--in-place is not set."
+ ),
+)
+ "--in-place",
+ is_flag=True,
+ default=False,
+ help="Overwrite the input JSONL (creates <jsonl>.bak first).",
+)
+ "--summary-out",
+ default=None,
+ type=click.Path(),
+ help="Output summary JSON path. Defaults to <out>.summary.json.",
+)
+def reparse_judge(jsonl_path, out_path, in_place, summary_out):
+ """Re-parse stored judge output and recover records that failed.
+
+ Reads each record raw_judge_output, runs it through the (fixed) parser,
+ and updates records whose old score was 0/None when a new score is
+ recoverable. Writes a summary.json with the recomputed accuracy + the
+ continuous-score fields, and prints a diff.
+ """
+ import json as _json
+ import shutil
+ import statistics
+ from pathlib import Path as _Path
+
+ from openjarvis.evals.scorers.liveresearch import rescore_from_metadata
+
+ in_path = _Path(jsonl_path)
+ if in_place:
+ backup = in_path.with_suffix(in_path.suffix + ".bak")
+ if not backup.exists():
+ shutil.copy2(in_path, backup)
+ target = in_path
+ else:
+ if out_path is None:
+ target = in_path.with_suffix(in_path.suffix + ".reparsed")
+ else:
+ target = _Path(out_path)
+
+ records = []
+ with open(in_path) as f:
+ for line in f:
+ line = line.strip()
+ if line:
+ records.append(_json.loads(line))
+
+ n_rescored = 0
+ old_scores = []
+ new_scores = []
+ for rec in records:
+ sm = rec.get("scoring_metadata") or {}
+ old_score = rec.get("score")
+ old_scores.append(old_score)
+ attempt = old_score is None or (
+ isinstance(old_score, (int, float)) and float(old_score) <= 0.0
+ )
+ new_score = old_score
+ if attempt:
+ res = rescore_from_metadata(sm)
+ if res is not None:
+ new_correct, new_meta = res
+ if new_meta.get("score", 0.0) > 0:
+ rec["scoring_metadata"] = new_meta
+ rec["is_correct"] = bool(new_correct)
+ rec["score"] = float(new_meta["score"])
+ new_score = rec["score"]
+ n_rescored += 1
+ new_scores.append(new_score)
+
+ target.parent.mkdir(parents=True, exist_ok=True)
+ with open(target, "w") as f:
+ for rec in records:
+ f.write(_json.dumps(rec, default=str) + chr(10))
+
+ cont = [float(s) for s in new_scores if s is not None]
+ scored = [r for r in records if r.get("is_correct") is not None]
+ correct = [r for r in scored if r.get("is_correct")]
+ accuracy = len(correct) / len(scored) if scored else 0.0
+ summary = {
+ "benchmark": records[0].get("benchmark", "?") if records else "?",
+ "model": records[0].get("model", "?") if records else "?",
+ "total_samples": len(records),
+ "scored_samples": len(scored),
+ "correct": len(correct),
+ "accuracy": round(accuracy, 4),
+ "mean_continuous_score": (round(sum(cont) / len(cont), 6) if cont else None),
+ "median_continuous_score": (
+ round(statistics.median(cont), 6) if cont else None
+ ),
+ "pct_above_0.5": (
+ round(sum(1 for v in cont if v > 0.5) / len(cont), 6) if cont else None
+ ),
+ "pct_above_0.7": (
+ round(sum(1 for v in cont if v > 0.7) / len(cont), 6) if cont else None
+ ),
+ "pct_above_0.8": (
+ round(sum(1 for v in cont if v > 0.8) / len(cont), 6) if cont else None
+ ),
+ "pct_above_0.9": (
+ round(sum(1 for v in cont if v > 0.9) / len(cont), 6) if cont else None
+ ),
+ "reparse_records_recovered": n_rescored,
+ }
+ if summary_out is None:
+ summary_path = target.with_suffix(target.suffix + ".summary.json")
+ else:
+ summary_path = _Path(summary_out)
+ summary_path.parent.mkdir(parents=True, exist_ok=True)
+ with open(summary_path, "w") as f:
+ _json.dump(summary, f, indent=2)
+
+ old_cont = [float(s) for s in old_scores if s is not None]
+ old_acc = (
+ sum(1 for s in old_cont if s >= 0.5) / len(old_cont) if old_cont else 0.0
+ )
+ old_mean = sum(old_cont) / len(old_cont) if old_cont else 0.0
+ new_mean = sum(cont) / len(cont) if cont else 0.0
+ mean_shift = new_mean - old_mean
+ acc_shift = accuracy - old_acc
+
+ console = Console()
+ console.print(f"[cyan]Input:[/cyan] {in_path}")
+ console.print(f"[cyan]Output:[/cyan] {target}")
+ console.print(f"[cyan]Summary:[/cyan] {summary_path}")
+ console.print(
+ f"[bold green]{n_rescored}[/bold green] records re-scored, "
+ f"mean shift {mean_shift:+.4f}, accuracy shift {acc_shift:+.2%}"
+ )
+
+
@main.command("list")
def list_cmd():
"""List available benchmarks and backends."""
diff --git a/src/openjarvis/evals/configs/gaia-gpt54.toml b/src/openjarvis/evals/configs/gaia-gpt54.toml
index 4a735d95..fc495b92 100644
--- a/src/openjarvis/evals/configs/gaia-gpt54.toml
+++ b/src/openjarvis/evals/configs/gaia-gpt54.toml
@@ -14,7 +14,7 @@ max_tokens = 4096
[run]
max_workers = 1
-output_dir = "results/gaia-gpt54/"
+output_dir = "results/neurips-2026/baselines/gpt54/gaia/"
seed = 42
[[models]]
@@ -25,5 +25,5 @@ engine = "cloud"
name = "gaia"
backend = "jarvis-agent"
agent = "monitor_operative"
-max_samples = 50
+max_samples = 165
tools = ["think", "calculator", "code_interpreter", "web_search", "file_read"]
diff --git a/src/openjarvis/evals/configs/pinchbench-claude-opus.toml b/src/openjarvis/evals/configs/pinchbench-claude-opus.toml
index b175aa59..6afa030c 100644
--- a/src/openjarvis/evals/configs/pinchbench-claude-opus.toml
+++ b/src/openjarvis/evals/configs/pinchbench-claude-opus.toml
@@ -16,7 +16,7 @@ engine = "cloud"
[run]
max_workers = 1
-output_dir = "results/pinchbench-claude-opus/"
+output_dir = "results/neurips-2026/baselines/claude-opus/pinchbench/"
seed = 42
[[models]]
@@ -25,6 +25,7 @@ engine = "cloud"
[[benchmarks]]
name = "pinchbench"
+max_samples = 23
backend = "jarvis-agent"
agent = "native_openhands"
tools = [
diff --git a/src/openjarvis/evals/configs/pinchbench-gemini-31-pro.toml b/src/openjarvis/evals/configs/pinchbench-gemini-31-pro.toml
index b54619ea..e8b0bccb 100644
--- a/src/openjarvis/evals/configs/pinchbench-gemini-31-pro.toml
+++ b/src/openjarvis/evals/configs/pinchbench-gemini-31-pro.toml
@@ -16,7 +16,7 @@ engine = "cloud"
[run]
max_workers = 1
-output_dir = "results/pinchbench-gemini-31-pro/"
+output_dir = "results/neurips-2026/baselines/gemini-31-pro/pinchbench/"
seed = 42
[[models]]
@@ -25,6 +25,7 @@ engine = "cloud"
[[benchmarks]]
name = "pinchbench"
+max_samples = 23
backend = "jarvis-agent"
agent = "native_openhands"
tools = [
diff --git a/src/openjarvis/evals/configs/taubench-gemini-31-pro.toml b/src/openjarvis/evals/configs/taubench-gemini-31-pro.toml
index 996e2fba..4a089e67 100644
--- a/src/openjarvis/evals/configs/taubench-gemini-31-pro.toml
+++ b/src/openjarvis/evals/configs/taubench-gemini-31-pro.toml
@@ -16,7 +16,7 @@ engine = "cloud"
[run]
max_workers = 1
-output_dir = "results/taubench-gemini-31-pro/"
+output_dir = "results/neurips-2026/baselines/gemini-31-pro/taubench/"
seed = 42
[[models]]
@@ -25,5 +25,6 @@ engine = "cloud"
[[benchmarks]]
name = "taubench"
+max_samples = 60
backend = "jarvis-direct"
split = "airline,retail"
diff --git a/src/openjarvis/evals/core/config.py b/src/openjarvis/evals/core/config.py
index cae66c26..aff39500 100644
--- a/src/openjarvis/evals/core/config.py
+++ b/src/openjarvis/evals/core/config.py
@@ -187,6 +187,12 @@ def load_eval_config(path: str | Path) -> EvalSuiteConfig:
logger.warning("Unknown benchmark name: '%s'", bench_name)
tools_raw = b.get("tools", [])
+ record_ids_raw = b.get("record_ids")
+ record_ids = (
+ [str(r) for r in record_ids_raw]
+ if isinstance(record_ids_raw, list) and record_ids_raw
+ else None
+ )
benchmarks.append(
BenchmarkConfig(
name=bench_name,
@@ -199,6 +205,7 @@ def load_eval_config(path: str | Path) -> EvalSuiteConfig:
temperature=float(b["temperature"]) if "temperature" in b else None,
max_tokens=int(b["max_tokens"]) if "max_tokens" in b else None,
subset=b.get("subset"),
+ record_ids=record_ids,
)
)
@@ -298,6 +305,7 @@ def expand_suite(suite: EvalSuiteConfig) -> List[RunConfig]:
sheets_worksheet=suite.run.sheets_worksheet,
sheets_credentials_path=suite.run.sheets_credentials_path,
max_turns=suite.run.max_turns,
+ record_ids=bench.record_ids,
)
)
diff --git a/src/openjarvis/evals/core/runner.py b/src/openjarvis/evals/core/runner.py
index 499eb721..d19b7551 100644
--- a/src/openjarvis/evals/core/runner.py
+++ b/src/openjarvis/evals/core/runner.py
@@ -53,6 +53,27 @@ LOGGER = logging.getLogger(__name__)
_THINK_TAG_RE = re.compile(r"<think>.*?</think>", re.DOTALL)
+def _extract_continuous_score(scoring_meta, is_correct):
+ """Pull continuous score (0.0-1.0) from scoring_meta, falling back to binary.
+
+ Many scorers (LLM-judge, rubric, coverage) write a continuous ``score``
+ into ``scoring_meta``; we surface that instead of binarising. Any value
+ outside [0.0, 1.0] is clamped or rejected. When no continuous score is
+ available we fall back to 1.0/0.0 from ``is_correct``.
+ """
+ if isinstance(scoring_meta, dict):
+ cand = scoring_meta.get("score")
+ if isinstance(cand, (int, float)) and not isinstance(cand, bool):
+ v = float(cand)
+ if v != v or v == float("inf") or v == float("-inf"):
+ pass
+ else:
+ return max(0.0, min(1.0, v))
+ if is_correct is None:
+ return None
+ return 1.0 if is_correct else 0.0
+
+
def _strip_think_tags(text: str) -> str:
"""Remove <think>...</think> blocks from model output."""
return _THINK_TAG_RE.sub("", text).strip()
@@ -149,6 +170,18 @@ class EvalRunner:
LOGGER.debug("Task env thread-safety probe failed: %s", exc)
records = list(self._dataset.iter_records())
+ if cfg.record_ids:
+ wanted = set(cfg.record_ids)
+ before = len(records)
+ records = [r for r in records if r.record_id in wanted]
+ LOGGER.info(
+ "Filtering %s to %d/%d records via record_ids "
+ "(first 3: %s)",
+ cfg.benchmark,
+ len(records),
+ before,
+ ", ".join(sorted(wanted)[:3]),
+ )
LOGGER.info(
"Running %s: %d samples, backend=%s, model=%s, workers=%d, episode_mode=%s",
cfg.benchmark,
@@ -389,11 +422,13 @@ class EvalRunner:
throughput_per_w = _telem.get("throughput_per_watt", 0.0)
mean_itl = _telem.get("mean_itl_ms", 0.0)
+ # Prefer continuous score from scoring_meta when scorer provides it.
+ score_val = _extract_continuous_score(scoring_meta, is_correct)
return EvalResult(
record_id=record.record_id,
model_answer=content,
is_correct=is_correct,
- score=1.0 if is_correct else (0.0 if is_correct is not None else None),
+ score=score_val,
latency_seconds=latency,
prompt_tokens=usage.get("prompt_tokens", 0),
completion_tokens=usage.get("completion_tokens", 0),
@@ -684,11 +719,12 @@ class EvalRunner:
msg for msg in messages if msg.get("role") != "system"
]
+ score_val = _extract_continuous_score(scoring_meta, is_correct)
return EvalResult(
record_id=record.record_id,
model_answer="\n---\n".join(all_responses),
is_correct=is_correct,
- score=1.0 if is_correct else (0.0 if is_correct is not None else None),
+ score=score_val,
latency_seconds=total_latency,
prompt_tokens=total_prompt_tokens,
completion_tokens=total_completion_tokens,
@@ -852,6 +888,26 @@ class EvalRunner:
accuracy = len(correct) / len(scored) if scored else 0.0
+ # Continuous-score reporting: skip None (errored) entries; clamp values
+ # outside [0,1] are already handled in _extract_continuous_score.
+ cont_scores = [
+ float(r.score) for r in results if r.score is not None
+ ]
+ if cont_scores:
+ mean_cont = sum(cont_scores) / len(cont_scores)
+ median_cont = statistics.median(cont_scores)
+ pct_above_05 = sum(1 for v in cont_scores if v > 0.5) / len(cont_scores)
+ pct_above_07 = sum(1 for v in cont_scores if v > 0.7) / len(cont_scores)
+ pct_above_08 = sum(1 for v in cont_scores if v > 0.8) / len(cont_scores)
+ pct_above_09 = sum(1 for v in cont_scores if v > 0.9) / len(cont_scores)
+ else:
+ mean_cont = None
+ median_cont = None
+ pct_above_05 = None
+ pct_above_07 = None
+ pct_above_08 = None
+ pct_above_09 = None
+
# Compute MetricStats for each metric
accuracy_vals = [1.0 if r.is_correct else 0.0 for r in scored]
latency_vals = [r.latency_seconds for r in results if r.latency_seconds > 0]
@@ -944,6 +1000,24 @@ class EvalRunner:
efficiency=efficiency_dict,
normalized_statistics=normalized_stats,
normalized_efficiency=normalized_eff,
+ mean_continuous_score=(
+ round(mean_cont, 6) if mean_cont is not None else None
+ ),
+ median_continuous_score=(
+ round(median_cont, 6) if median_cont is not None else None
+ ),
+ pct_above_0_5=(
+ round(pct_above_05, 6) if pct_above_05 is not None else None
+ ),
+ pct_above_0_7=(
+ round(pct_above_07, 6) if pct_above_07 is not None else None
+ ),
+ pct_above_0_8=(
+ round(pct_above_08, 6) if pct_above_08 is not None else None
+ ),
+ pct_above_0_9=(
+ round(pct_above_09, 6) if pct_above_09 is not None else None
+ ),
)
@@ -1101,6 +1175,12 @@ def _summary_to_dict(s: RunSummary) -> Dict[str, Any]:
"efficiency": s.efficiency,
"normalized_statistics": s.normalized_statistics,
"normalized_efficiency": s.normalized_efficiency,
+ "mean_continuous_score": s.mean_continuous_score,
+ "median_continuous_score": s.median_continuous_score,
+ "pct_above_0.5": s.pct_above_0_5,
+ "pct_above_0.7": s.pct_above_0_7,
+ "pct_above_0.8": s.pct_above_0_8,
+ "pct_above_0.9": s.pct_above_0_9,
"telemetry_summary": {
"total_energy_joules": s.total_energy_joules,
"avg_power_watts": s.avg_power_watts,
diff --git a/src/openjarvis/evals/core/types.py b/src/openjarvis/evals/core/types.py
index ee501d8d..5c40f933 100644
--- a/src/openjarvis/evals/core/types.py
+++ b/src/openjarvis/evals/core/types.py
@@ -89,6 +89,11 @@ class RunConfig:
# running thinking/reasoning models that consume turns on intermediate
# reasoning before producing tool calls.
max_turns: Optional[int] = None
+ # Filter dataset records by id. When set, only records whose record_id
+ # appears in this list are processed. Used for surgical re-runs of
+ # specific records (e.g. recovering silent-fake records without
+ # re-running the entire benchmark).
+ record_ids: Optional[List[str]] = None
@dataclass(slots=True)
@@ -152,6 +157,14 @@ class RunSummary:
efficiency: Optional[Dict[str, Any]] = None
normalized_statistics: Optional[Dict[str, Any]] = None
normalized_efficiency: Optional[Dict[str, Any]] = None
+ # Continuous-score reporting (added alongside binary accuracy so frontier
+ # models do not saturate the metric on rubric-judge benchmarks).
+ mean_continuous_score: Optional[float] = None
+ median_continuous_score: Optional[float] = None
+ pct_above_0_5: Optional[float] = None
+ pct_above_0_7: Optional[float] = None
+ pct_above_0_8: Optional[float] = None
+ pct_above_0_9: Optional[float] = None
# Internal fields set by the runner after construction
_output_path: Optional[Path] = None
_traces_dir: Optional[Path] = None
@@ -243,6 +256,7 @@ class BenchmarkConfig:
temperature: Optional[float] = None
max_tokens: Optional[int] = None
subset: Optional[str] = None
+ record_ids: Optional[List[str]] = None
@dataclass(slots=True)
diff --git a/src/openjarvis/evals/scorers/liveresearch.py b/src/openjarvis/evals/scorers/liveresearch.py
index 7895e2f1..836ed58c 100644
--- a/src/openjarvis/evals/scorers/liveresearch.py
+++ b/src/openjarvis/evals/scorers/liveresearch.py
@@ -120,6 +120,68 @@ Be a rigorous evaluator. Reserve scores of 9-10 for genuinely excellent work.
A score of 5 represents adequate but unremarkable quality."""
+
+# Optional permissive JSON parser (json5 if available; fallback otherwise).
+try:
+ import json5 as _json5 # type: ignore[import-not-found]
+except ImportError: # pragma: no cover - json5 is optional
+ _json5 = None
+
+
+def _escape_newlines_inside_strings(text: str) -> str:
+ """Escape literal CR/LF/TAB inside double-quoted JSON string spans.
+
+ Walks the text tracking whether we are inside a double-quoted string,
+ respecting backslash escapes. Outside strings the text is left untouched.
+ """
+ out: List[str] = []
+ in_string = False
+ escape_next = False
+ for ch in text:
+ if in_string:
+ if escape_next:
+ out.append(ch)
+ escape_next = False
+ continue
+ if ch == "\\":
+ out.append(ch)
+ escape_next = True
+ continue
+ if ch == "\"":
+ out.append(ch)
+ in_string = False
+ continue
+ if ch == "\n":
+ out.append("\\n")
+ continue
+ if ch == "\r":
+ out.append("\\r")
+ continue
+ if ch == "\t":
+ out.append("\\t")
+ continue
+ out.append(ch)
+ else:
+ if ch == "\"":
+ in_string = True
+ out.append(ch)
+ return "".join(out)
+
+
+def _safe_json_loads(text: str) -> Any:
+ """Permissive JSON: strict json -> json5 (if installed) -> tolerant fallback."""
+ try:
+ return json.loads(text)
+ except json.JSONDecodeError:
+ pass
+ if _json5 is not None:
+ try:
+ return _json5.loads(text)
+ except Exception: # noqa: BLE001
+ pass
+ return json.loads(_escape_newlines_inside_strings(text))
+
+
def _parse_judge_response(raw: str) -> Dict[str, Any]:
"""Parse LLM judge response, extracting dimension scores.
@@ -136,49 +198,62 @@ def _parse_judge_response(raw: str) -> Dict[str, Any]:
code_block = re.search(r"```json\s*(.*?)\s*```", raw, re.DOTALL)
if code_block:
try:
- parsed = json.loads(code_block.group(1))
+ parsed = _safe_json_loads(code_block.group(1))
if isinstance(parsed, dict):
return _normalize_response(parsed)
- except json.JSONDecodeError:
+ except (json.JSONDecodeError, ValueError):
pass
# Try balanced braces extraction
candidates: List[str] = []
depth = 0
current: List[str] = []
+ in_str = False
+ esc = False
for char in raw:
+ if in_str:
+ current.append(char)
+ if esc:
+ esc = False
+ elif char == "\\":
+ esc = True
+ elif char == "\"":
+ in_str = False
+ continue
if char == "{":
if depth == 0:
current = []
depth += 1
if depth > 0:
current.append(char)
- if char == "}":
+ if char == "\"" and depth > 0:
+ in_str = True
+ elif char == "}":
depth -= 1
if depth == 0 and current:
candidates.append("".join(current))
for candidate in reversed(candidates):
try:
- parsed = json.loads(candidate)
+ parsed = _safe_json_loads(candidate)
if isinstance(parsed, dict) and "scores" in parsed:
return _normalize_response(parsed)
- except json.JSONDecodeError:
+ except (json.JSONDecodeError, ValueError):
continue
for candidate in reversed(candidates):
try:
- parsed = json.loads(candidate)
+ parsed = _safe_json_loads(candidate)
if isinstance(parsed, dict):
return _normalize_response(parsed)
- except json.JSONDecodeError:
+ except (json.JSONDecodeError, ValueError):
continue
# Regex fallback: look for individual dimension scores
scores: Dict[str, float] = {}
for dim in DIMENSIONS:
match = re.search(
- rf"{dim}[:\s]*([\d.]+)",
+ rf'"?{dim}"?\s*[:=]\s*([\d.]+)',
raw,
re.IGNORECASE,
)
@@ -239,6 +314,48 @@ def _normalize_response(parsed: Dict[str, Any]) -> Dict[str, Any]:
return result
+def rescore_from_metadata(scoring_metadata, dimension_weights=None):
+ """Re-derive (is_correct, updated_metadata) from a stored ``raw_judge_output``.
+
+ Returns ``None`` if no raw judge output is present or no scores can be
+ parsed. Used by the ``evals reparse-judge`` CLI to fix records that
+ failed under the old, stricter parser.
+ """
+ raw = scoring_metadata.get("raw_judge_output")
+ if not isinstance(raw, str) or not raw.strip():
+ return None
+
+ parsed = _parse_judge_response(raw)
+ scores = parsed.get("scores") or {}
+ if not scores:
+ return None
+
+ weights = dimension_weights or scoring_metadata.get("dimension_weights")
+ if not isinstance(weights, dict) or not weights:
+ weights = DEFAULT_WEIGHTS
+
+ weighted_total = 0.0
+ total_weight = 0.0
+ for dim in DIMENSIONS:
+ dim_score = float(scores.get(dim, 0.0))
+ dim_weight = float(weights.get(dim, DEFAULT_WEIGHTS.get(dim, 0.25)))
+ weighted_total += dim_score * dim_weight
+ total_weight += dim_weight
+
+ if total_weight > 0:
+ weighted_total /= total_weight
+ normalized = weighted_total / 10.0
+ is_correct = normalized >= 0.5
+
+ new_meta = dict(scoring_metadata)
+ new_meta["score"] = normalized
+ new_meta["dimension_scores"] = scores
+ new_meta["dimension_weights"] = weights
+ new_meta["weighted_total_0_10"] = weighted_total
+ new_meta["notes"] = parsed.get("notes", new_meta.get("notes", ""))
+ return is_correct, new_meta
+
+
class LiveResearchBenchScorer(LLMJudgeScorer):
"""LLM-as-judge scorer for DeepResearchBench deep research tasks.
@@ -313,4 +430,4 @@ class LiveResearchBenchScorer(LLMJudgeScorer):
return is_correct, metadata
-__all__ = ["LiveResearchBenchScorer"]
+__all__ = ["LiveResearchBenchScorer", "rescore_from_metadata"]
diff --git a/tests/evals/scorers/test_liveresearch_continuous.py b/tests/evals/scorers/test_liveresearch_continuous.py
new file mode 100644
index 00000000..e820a5b3
--- /dev/null
+++ b/tests/evals/scorers/test_liveresearch_continuous.py
@@ -0,0 +1,280 @@
+"""Tests for continuous-score reporting and judge-response reparsing.
+
+Covers the ``mean_continuous_score`` family of fields in summary.json,
+the ``_safe_json_loads`` parser tolerating multi-line ``notes``, and
+the ``evals reparse-judge`` CLI.
+"""
+
+from __future__ import annotations
+
+import json
+from unittest.mock import MagicMock
+
+import pytest
+from click.testing import CliRunner
+
+from openjarvis.evals.cli import main as cli_main
+from openjarvis.evals.core.runner import EvalRunner, _extract_continuous_score
+from openjarvis.evals.core.types import EvalRecord, RunConfig
+from openjarvis.evals.scorers.liveresearch import (
+ _escape_newlines_inside_strings,
+ _parse_judge_response,
+ _safe_json_loads,
+ rescore_from_metadata,
+)
+
+
+def _make_dataset(records):
+ """Build a minimal MagicMock dataset that yields the given records."""
+ ds = MagicMock(spec=["load", "iter_records"])
+ ds.load = MagicMock()
+ ds.iter_records = MagicMock(return_value=list(records))
+ return ds
+
+
+def _make_backend(content="answer"):
+ backend = MagicMock()
+ backend.generate_full = MagicMock(return_value={
+ "content": content,
+ "usage": {"prompt_tokens": 5, "completion_tokens": 3},
+ "latency_seconds": 0.1,
+ })
+ return backend
+
+
+class _ContinuousScorer:
+ """A scorer that returns a fixed continuous score in scoring_meta."""
+
+ def __init__(self, scores):
+ self._scores = list(scores)
+ self._idx = 0
+
+ def score(self, record, model_answer):
+ v = self._scores[self._idx]
+ self._idx += 1
+ return v >= 0.5, {"score": float(v)}
+
+
+# ---------------------------------------------------------------------------
+# Part A: continuous-score fields in summary.json
+# ---------------------------------------------------------------------------
+
+
+def test_continuous_score_fields_present_in_summary(tmp_path):
+ """End-to-end: runner exposes the continuous-score family in summary.json."""
+ records = [
+ EvalRecord(record_id=f"r{i}", problem="q", reference="a", category="chat")
+ for i in range(5)
+ ]
+ dataset = _make_dataset(records)
+ backend = _make_backend()
+ # Mix of scores spanning the > 0.5 / 0.7 / 0.8 / 0.9 thresholds.
+ scorer = _ContinuousScorer([0.10, 0.55, 0.72, 0.85, 0.95])
+
+ out = tmp_path / "out.jsonl"
+ cfg = RunConfig(
+ benchmark="test",
+ backend="jarvis-direct",
+ model="test-model",
+ output_path=str(out),
+ )
+ runner = EvalRunner(cfg, dataset, backend, scorer)
+ summary = runner.run()
+
+ summary_path = out.with_suffix(".summary.json")
+ payload = json.loads(summary_path.read_text())
+
+ for key in (
+ "mean_continuous_score",
+ "median_continuous_score",
+ "pct_above_0.5",
+ "pct_above_0.7",
+ "pct_above_0.8",
+ "pct_above_0.9",
+ ):
+ assert key in payload, f"missing {key}"
+ assert isinstance(payload[key], (int, float))
+
+ assert payload["mean_continuous_score"] == pytest.approx(
+ sum([0.10, 0.55, 0.72, 0.85, 0.95]) / 5, abs=1e-6
+ )
+ assert payload["pct_above_0.5"] == pytest.approx(4 / 5)
+ assert payload["pct_above_0.7"] == pytest.approx(3 / 5)
+ assert payload["pct_above_0.8"] == pytest.approx(2 / 5)
+ assert payload["pct_above_0.9"] == pytest.approx(1 / 5)
+
+ # Existing accuracy field still present (binary, score >= 0.5)
+ assert payload["accuracy"] == pytest.approx(4 / 5)
+ # Continuous score also reflected on the in-memory summary.
+ assert summary.mean_continuous_score is not None
+ assert summary.pct_above_0_5 == pytest.approx(4 / 5)
+
+
+# Part B: parser handles multi-line notes and non-JSON quirks
+
+MULTILINE_RAW_PART1 = """{
+ "scores": {
+ "comprehensiveness": 6,
+ "insight": 5,
+ "instruction_following": 6,
+ "readability": 7
+ },"""
+
+MULTILINE_RAW_PART2 = """
+ "weighted_total": 6.0,
+ "notes": "Comprehensiveness (6): covers many topics
+but omits recent developments.
+
+Insight (5): Mostly descriptive analysis,
+limited original perspectives."
+}"""
+
+MULTILINE_RAW = MULTILINE_RAW_PART1 + MULTILINE_RAW_PART2
+
+def test_judge_parser_handles_multiline_notes():
+ """Multi-line notes strings (invalid JSON) are still recoverable."""
+ parsed = _parse_judge_response(MULTILINE_RAW)
+ scores = parsed["scores"]
+ assert scores["comprehensiveness"] == 6
+ assert scores["insight"] == 5
+ assert scores["instruction_following"] == 6
+ assert scores["readability"] == 7
+ assert parsed["weighted_total"] == pytest.approx(6.0)
+
+
+def test_safe_json_loads_strict_first():
+ """Strict JSON still parses through the permissive helper."""
+ payload = chr(123) + chr(34) + "a" + chr(34) + ": 1" + chr(125)
+ assert _safe_json_loads(payload) == {"a": 1}
+
+
+def test_escape_newlines_only_inside_strings():
+ """Newlines outside string spans are preserved (structure-preserving)."""
+ txt = (
+ chr(123) + "\n " + chr(34) + "a" + chr(34) + ": "
+ + chr(34) + "x\ny" + chr(34) + "\n" + chr(125)
+ )
+ out = _escape_newlines_inside_strings(txt)
+ assert out.startswith(chr(123) + "\n")
+ assert "\\n" in out
+ assert json.loads(out) == {"a": "x\ny"}
+
+
+# ---------------------------------------------------------------------------
+# Part C: reparse-judge CLI
+# ---------------------------------------------------------------------------
+
+
+def _make_jsonl(path, recs):
+ with open(path, "w") as f:
+ for r in recs:
+ f.write(json.dumps(r) + chr(10))
+
+
+def test_reparse_judge_idempotent(tmp_path):
+ """A clean JSONL is unchanged when re-parsed."""
+ rec = {
+ "record_id": "r1",
+ "benchmark": "liveresearch",
+ "model": "test",
+ "is_correct": True,
+ "score": 0.7,
+ "scoring_metadata": {
+ "score": 0.7,
+ "dimension_scores": {
+ "comprehensiveness": 7,
+ "insight": 7,
+ "instruction_following": 7,
+ "readability": 7,
+ },
+ },
+ }
+ in_path = tmp_path / "in.jsonl"
+ _make_jsonl(in_path, [rec])
+
+ runner = CliRunner()
+ out_path = tmp_path / "out.jsonl"
+ result = runner.invoke(
+ cli_main,
+ ["reparse-judge", "--jsonl", str(in_path), "--out", str(out_path)],
+ )
+ assert result.exit_code == 0, result.output
+ out_recs = [json.loads(line) for line in out_path.read_text().splitlines() if line]
+ assert len(out_recs) == 1
+ assert out_recs[0]["score"] == pytest.approx(0.7)
+ assert out_recs[0]["is_correct"] is True
+ # The accuracy in summary is unchanged.
+ summary_path = out_path.with_suffix(out_path.suffix + ".summary.json")
+ summary = json.loads(summary_path.read_text())
+ assert summary["accuracy"] == 1.0
+ assert summary["reparse_records_recovered"] == 0
+
+
+def test_reparse_judge_recovers_failed_record(tmp_path):
+ """A record with score=0 + parseable raw_judge_output is recovered."""
+ raw = MULTILINE_RAW
+ rec = {
+ "record_id": "r1",
+ "benchmark": "liveresearch",
+ "model": "test",
+ "is_correct": False,
+ "score": 0.0,
+ "scoring_metadata": {
+ "score": 0.0,
+ "dimension_scores": {},
+ "raw_judge_output": raw,
+ },
+ }
+ in_path = tmp_path / "in.jsonl"
+ _make_jsonl(in_path, [rec])
+
+ runner = CliRunner()
+ out_path = tmp_path / "out.jsonl"
+ result = runner.invoke(
+ cli_main,
+ ["reparse-judge", "--jsonl", str(in_path), "--out", str(out_path)],
+ )
+ assert result.exit_code == 0, result.output
+ out_recs = [json.loads(line) for line in out_path.read_text().splitlines() if line]
+ assert len(out_recs) == 1
+ rescued = out_recs[0]
+ assert rescued["score"] > 0.0
+ assert rescued["is_correct"] is True
+ assert rescued["scoring_metadata"]["dimension_scores"] == {
+ "comprehensiveness": 6.0,
+ "insight": 5.0,
+ "instruction_following": 6.0,
+ "readability": 7.0,
+ }
+ summary_path = out_path.with_suffix(out_path.suffix + ".summary.json")
+ summary = json.loads(summary_path.read_text())
+ assert summary["reparse_records_recovered"] == 1
+ assert summary["mean_continuous_score"] is not None
+
+
+# ---------------------------------------------------------------------------
+# extract_continuous_score helper unit tests
+# ---------------------------------------------------------------------------
+
+
+def test_extract_continuous_score_prefers_meta_score():
+ assert _extract_continuous_score({"score": 0.42}, True) == pytest.approx(0.42)
+ assert _extract_continuous_score({"score": 0.42}, False) == pytest.approx(0.42)
+
+
+def test_extract_continuous_score_falls_back_to_binary():
+ assert _extract_continuous_score({}, True) == 1.0
+ assert _extract_continuous_score({}, False) == 0.0
+ assert _extract_continuous_score({}, None) is None
+
+
+def test_extract_continuous_score_clamps_out_of_range():
+ assert _extract_continuous_score({"score": 1.5}, True) == 1.0
+ assert _extract_continuous_score({"score": -0.1}, False) == 0.0
+
+
+def test_rescore_from_metadata_returns_none_when_unparseable():
+ assert rescore_from_metadata({"raw_judge_output": "totally not json"}) is None
+ assert rescore_from_metadata({}) is None
+
+