Retry malformed OmniRoute benchmark responses
This commit is contained in:
parent
470370d015
commit
d7d9aab9c2
|
|
@ -134,6 +134,12 @@ recorded, it uses the smart route alias. Override with
|
|||
`LAB_DOCTOR_LAB_OMNI_MODEL` or `LAB_DOCTOR_LAB_OMNI_URL` (loopback `/v1` only).
|
||||
OmniRoute can fall back or change providers; the report records the requested
|
||||
and returned model names where available, which are not proof of backend identity.
|
||||
OmniRoute requests allow up to 4096 output tokens including reasoning. An empty
|
||||
or malformed JSON response gets one fresh retry with an explicit JSON-only
|
||||
instruction. Both responses, usage, finish reasons and elapsed times are kept in
|
||||
the private report; total latency includes both attempts. This additional retry
|
||||
and larger output budget differ from local models and affect direct comparisons.
|
||||
The final answer must still pass the same evidence and command validation.
|
||||
This can use an external provider and its quotas; no live Doctor evidence is sent.
|
||||
External inference has no local scope memory measurement or GPU equivalence.
|
||||
This experiment does not change the production doctor model or stop services.
|
||||
|
|
|
|||
|
|
@ -47,6 +47,7 @@ START_AVAILABLE = 9 * 1024 ** 3
|
|||
STOP_AVAILABLE = 768 * 1024 ** 2
|
||||
CONTEXT = 4096
|
||||
OUTPUT_TOKENS = 768
|
||||
OMNI_OUTPUT_TOKENS = 4096
|
||||
CASES = (
|
||||
("runner_disabled", "warn\tKubernetes apps\tgitea-runner\thealth=Progressing, sync=Synced\tThe synced repository intentionally sets Kubernetes replicas to 0; Debian is the intended runner host. Live deployment desired=0 ready=0; Debian runner service is active. Registration and job execution are unverified.\tkubectl get pods -A -o wide\t\t\n"),
|
||||
("runner_intent_unknown", "warn\tKubernetes apps\tgitea-runner\thealth=Progressing, sync=Unknown\tLive deployment desired=0 ready=0; Debian runner service is active. Synced repository revision unavailable; whether zero replicas is intentional is unknown.\tkubectl get pods -A -o wide\t\t\n"),
|
||||
|
|
@ -273,15 +274,17 @@ def case_report(case_id, tsv, directory):
|
|||
return doctor.report_from_tsv(path, "Doctor model lab: " + case_id, "k3s", "k3s")
|
||||
|
||||
|
||||
def answer(server, backend, model, report):
|
||||
def answer(server, backend, model, report, retry=False):
|
||||
prompt = doctor.build_prompt(report)
|
||||
if retry:
|
||||
prompt += "\nYour previous response was empty or malformed JSON. Return one valid JSON object only."
|
||||
if backend.startswith("ollama-"):
|
||||
payload = {"model": model, "prompt": prompt, "format": doctor.schema(report), "stream": False,
|
||||
"keep_alive": "5m", "options": {"num_ctx": CONTEXT, "num_predict": OUTPUT_TOKENS, "temperature": 0, "num_gpu": 0}}
|
||||
data = request(server.base + "/api/generate", payload, timeout=1800)
|
||||
return data.get("response", ""), data.get("eval_count"), data.get("model")
|
||||
return data.get("response", ""), data.get("eval_count"), data.get("model"), {"usage": {"completion_tokens": data.get("eval_count")}, "finish_reason": data.get("done_reason")}
|
||||
payload = {"model": model, "messages": [{"role": "user", "content": prompt}], "temperature": 0,
|
||||
"max_tokens": OUTPUT_TOKENS, "stream": False}
|
||||
"max_tokens": OMNI_OUTPUT_TOKENS if backend == "omniroute" else OUTPUT_TOKENS, "stream": False}
|
||||
if backend == "llama-cpu":
|
||||
payload["response_format"] = {"type": "json_object"}
|
||||
if backend == "omniroute":
|
||||
|
|
@ -291,7 +294,8 @@ def answer(server, backend, model, report):
|
|||
data = request(server.base + "/v1/chat/completions", payload, timeout=1800)
|
||||
else:
|
||||
data = request(server.base + "/v1/chat/completions", payload, timeout=1800, headers=headers)
|
||||
return data["choices"][0]["message"].get("content", ""), (data.get("usage") or {}).get("completion_tokens"), data.get("model")
|
||||
choice = data["choices"][0]
|
||||
return choice["message"].get("content", ""), (data.get("usage") or {}).get("completion_tokens"), data.get("model"), {"usage": data.get("usage"), "finish_reason": choice.get("finish_reason")}
|
||||
|
||||
|
||||
def read_env_values(path, keys):
|
||||
|
|
@ -332,6 +336,38 @@ def parse_answer(response):
|
|||
return json.loads(match.group(1) if match else text)
|
||||
|
||||
|
||||
def evaluate_answer(server, backend, model, report):
|
||||
"""Retry only malformed OmniRoute JSON; preserve each independent attempt."""
|
||||
attempts = []
|
||||
for index in range(2 if backend == "omniroute" else 1):
|
||||
started = time.monotonic()
|
||||
try:
|
||||
response, tokens, returned_model, metadata = answer(server, backend, model, report, retry=index > 0)
|
||||
attempt = {"response": response, "generated_tokens": tokens, "returned_model": returned_model,
|
||||
"elapsed_seconds": round(time.monotonic() - started, 2), **metadata}
|
||||
attempts.append(attempt)
|
||||
try:
|
||||
parsed = parse_answer(response)
|
||||
except (ValueError, TypeError) as exc:
|
||||
attempt.update(contract="rejected", validation_error=str(exc))
|
||||
if backend == "omniroute" and index == 0:
|
||||
continue
|
||||
break
|
||||
try:
|
||||
doctor.validate(parsed, report)
|
||||
attempt["contract"] = "valid"
|
||||
except (ValueError, TypeError, KeyError) as exc:
|
||||
attempt.update(contract="rejected", validation_error=str(exc))
|
||||
break
|
||||
except (OSError, ValueError, KeyError, IndexError, urllib.error.URLError) as exc:
|
||||
attempts.append({"contract": "error", "error": str(exc), "elapsed_seconds": round(time.monotonic() - started, 2)})
|
||||
break
|
||||
final = dict(attempts[-1])
|
||||
final["elapsed_seconds"] = round(sum(item["elapsed_seconds"] for item in attempts), 2)
|
||||
final["attempts"] = attempts
|
||||
return final
|
||||
|
||||
|
||||
def auto_rank(path):
|
||||
"""Score blinded synthetic cases with an isolated local LLM judge."""
|
||||
path = Path(path).resolve()
|
||||
|
|
@ -468,20 +504,9 @@ def suite_run(repeats):
|
|||
for case_id, tsv in CASES:
|
||||
print(f"[{repeat + 1}/{repeats}] {backend}: {case_id}", flush=True)
|
||||
report = case_report(case_id + f"-{repeat + 1}-{backend}", tsv, report_dir)
|
||||
start = time.monotonic()
|
||||
row = {"backend": backend, "model": model, "case": case_id, "repeat": repeat + 1,
|
||||
"review_id": uuid.uuid4().hex, "manual_review_required": True}
|
||||
try:
|
||||
response, tokens, returned_model = answer(server, backend, model, report)
|
||||
row.update(elapsed_seconds=round(time.monotonic() - start, 2), generated_tokens=tokens, returned_model=returned_model)
|
||||
try:
|
||||
doctor.validate(parse_answer(response), report)
|
||||
row["contract"] = "valid"
|
||||
except (ValueError, TypeError, KeyError) as exc:
|
||||
row.update(contract="rejected", validation_error=str(exc))
|
||||
row["response"] = response
|
||||
except (OSError, ValueError, KeyError, IndexError, urllib.error.URLError) as exc:
|
||||
row.update(contract="error", error=str(exc), elapsed_seconds=round(time.monotonic() - start, 2))
|
||||
row.update(evaluate_answer(server, backend, model, report))
|
||||
results.append(row)
|
||||
if server.low_memory or (server.process is not None and server.process.poll() is not None):
|
||||
raise RuntimeError(f"{backend} stopped during inference; see its private server log")
|
||||
|
|
|
|||
|
|
@ -53,12 +53,46 @@ class DoctorModelLabTests(unittest.TestCase):
|
|||
server = lab.ExternalServer("http://127.0.0.1:20128", "example-private-key")
|
||||
result = {"choices": [{"message": {"content": "{}"}}], "model": "provider/model"}
|
||||
with mock.patch.object(lab, "request", return_value=result) as call:
|
||||
_, _, actual = lab.answer(server, "omniroute", "provider/model", report)
|
||||
_, _, actual, metadata = lab.answer(server, "omniroute", "provider/model", report)
|
||||
self.assertEqual(actual, "provider/model")
|
||||
self.assertEqual(call.call_args.args[1]["max_tokens"], 4096)
|
||||
self.assertEqual(call.call_args.args[0], "http://127.0.0.1:20128/v1/chat/completions")
|
||||
self.assertIn("gitea-runner", call.call_args.args[1]["messages"][0]["content"])
|
||||
self.assertEqual(call.call_args.kwargs["headers"]["Authorization"], "Bearer example-private-key")
|
||||
|
||||
def test_omniroute_retries_malformed_json_and_records_both_attempts(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
name, tsv = lab.CASES[0]
|
||||
report = lab.case_report(name, tsv, Path(directory))
|
||||
valid = json.dumps({"observed_facts": ["C01"], "possible_causes": [], "missing_evidence": [], "next_command": None})
|
||||
responses = [("{bad", 1700, "provider/model", {"usage": {"completion_tokens": 1700}, "finish_reason": "stop"}),
|
||||
(valid, 1900, "provider/model", {"usage": {"completion_tokens": 1900}, "finish_reason": "stop"})]
|
||||
with mock.patch.object(lab, "answer", side_effect=responses) as call:
|
||||
result = lab.evaluate_answer(None, "omniroute", "provider/model", report)
|
||||
self.assertEqual(result["contract"], "valid")
|
||||
self.assertEqual(len(result["attempts"]), 2)
|
||||
self.assertEqual(result["attempts"][0]["contract"], "rejected")
|
||||
self.assertEqual(result["attempts"][0]["usage"]["completion_tokens"], 1700)
|
||||
self.assertTrue(call.call_args.kwargs["retry"])
|
||||
|
||||
def test_omniroute_does_not_retry_semantic_validation_failure(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
name, tsv = lab.CASES[0]
|
||||
report = lab.case_report(name, tsv, Path(directory))
|
||||
invalid = json.dumps({"observed_facts": ["C99"], "possible_causes": [], "missing_evidence": [], "next_command": None})
|
||||
with mock.patch.object(lab, "answer", return_value=(invalid, 1, "model", {"usage": {}, "finish_reason": "stop"})) as call:
|
||||
result = lab.evaluate_answer(None, "omniroute", "model", report)
|
||||
self.assertEqual(result["contract"], "rejected")
|
||||
self.assertEqual(call.call_count, 1)
|
||||
|
||||
def test_omniroute_rejects_two_malformed_attempts_and_preserves_both(self):
|
||||
response = (None, 10, "model", {"usage": {"completion_tokens": 10}, "finish_reason": "stop"})
|
||||
with mock.patch.object(lab, "answer", return_value=response) as call:
|
||||
result = lab.evaluate_answer(None, "omniroute", "model", {})
|
||||
self.assertEqual(result["contract"], "rejected")
|
||||
self.assertEqual(len(result["attempts"]), 2)
|
||||
self.assertEqual(call.call_count, 2)
|
||||
|
||||
def test_external_config_reads_values_without_executing_them_and_requires_loopback(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
routes = Path(directory) / "routes"
|
||||
|
|
|
|||
Loading…
Reference in New Issue