Datasets:
Modalities:
Text
Formats:
json
Languages:
English
Size:
< 1K
Tags:
mathematics
formal-verification
symbolic-algebra
theorem-proving
multi-agent-systems
benchmark
File size: 7,147 Bytes
c0aca40 f74e990 c0aca40 f74e990 c0aca40 4e7c9ed c0aca40 4e7c9ed c0aca40 4e7c9ed c0aca40 4e7c9ed c0aca40 4e7c9ed c0aca40 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 | #!/usr/bin/env python3
"""Solve a problem of the math language with the real LingoLOGOS orchestrator.
python tools/solve.py "solve x^2 - 5*x + 6 = 0 for x"
python tools/solve.py --json "prove x^2 + 1 > 0"
python tools/solve.py --corpus problems/corpus.jsonl --limit 5
Run from this folder (it is ``datasets/math`` inside the LingoLOGOS repository, and the bundle
root when the dataset is cloned on its own).
The script builds a throw away workspace (node datasets, seed with the user problem, launcher),
runs the seven node processes through ``MultiInstanceOrchestrator`` and then re-derives the
verdict from the transcript: it recomputes the arbiter's decision and checks that the Z3 run of
the orchestrator agrees with what every agent claimed.
"""
import argparse
import json
import os
import shutil
import stat
import sys
import tempfile
from pathlib import Path
from typing import Any, Dict, List
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
# Inside the repository this bundle sits at <repo>/datasets/math, so the orchestrator package is no
# longer a sibling of the bundle. Walk up the tree until an ancestor carries the package.
for _parent in ROOT.parents:
_candidate = _parent / "src"
if (_candidate / "lingologos_orchestrator").is_dir():
sys.path.insert(0, str(_candidate))
break
from lingologos_math import agents, corpus, pipeline, protocol # noqa: E402
def _launcher(directory: Path) -> Path:
agent = ROOT / "agents" / "math_agent"
if os.name == "nt":
path = directory / "math_agent.cmd"
path.write_text('@echo off\r\n"%s" "%s" %%*\r\n' % (sys.executable, agent))
else:
path = directory / "math_agent.sh"
path.write_text('#!/bin/sh\nexec "%s" "%s" "$@"\n' % (sys.executable, agent))
path.chmod(path.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
return path
def solve(problem: str, faults_spec: str = "", keep: bool = False) -> Dict[str, Any]:
"""Run one problem through the orchestrator and return the checked verdict."""
from lingologos_orchestrator.orchestrator import MultiInstanceOrchestrator
from lingologos_orchestrator.schema import OrchestratorError
workspace = Path(tempfile.mkdtemp(prefix="lingologos_math_"))
try:
datasets = workspace / "datasets"
shutil.copytree(ROOT / "nodes", datasets)
seed_path = datasets / "arbiter" / "seed_payload.json"
seed = json.loads(seed_path.read_text())
seed["payload"]["naturalLanguage"] = problem
seed_path.write_text(json.dumps(seed))
launcher = _launcher(workspace)
topology = json.loads((ROOT / "topology.json").read_text())
for instance in topology["instances"]:
instance["executable"] = str(launcher)
topology_path = workspace / "topology.json"
topology_path.write_text(json.dumps(topology))
previous = os.environ.get("LINGOLOGOS_MATH_FAULTS")
os.environ["LINGOLOGOS_MATH_FAULTS"] = faults_spec
try:
orchestrator = MultiInstanceOrchestrator.from_config_file(
config_path=topology_path, datasets_dir=datasets,
runtime_state_dir=workspace / "runtime_state", workspace_dir=workspace)
result = orchestrator.run_session().to_dict()
except OrchestratorError as exc:
return {"final": _unknown("orchestrator error: %s" % str(exc)[:200]), "referee": [], "records": []}
finally:
if previous is None:
os.environ.pop("LINGOLOGOS_MATH_FAULTS", None)
else:
os.environ["LINGOLOGOS_MATH_FAULTS"] = previous
return _check(result)
finally:
if keep:
print("workspace kept at %s" % workspace, file=sys.stderr)
else:
shutil.rmtree(workspace, ignore_errors=True)
def _unknown(reason: str) -> Dict[str, Any]:
return {"status": "UNKNOWN", "assurance": 0, "answer": None, "answer_text": "", "solver": None,
"problem_math": "", "reasons": [reason], "detected": []}
def _check(result: Dict[str, Any]) -> Dict[str, Any]:
records: List[Dict[str, Any]] = result["records"]
referee = [{"sender": r["sender"], "claimed": r["envelope"]["payload"]["smtConstraints"]["z3Status"],
"referee": r["smt_result"]["status"]} for r in records]
dossier = protocol.decode(records[-1]["envelope"]["payload"]["naturalLanguage"])
final = pipeline.checked_verdict(dossier, referee, arbiter_expected=True)
return {"final": final, "referee": referee, "records": records, "turns": result["total_turns"]}
def _describe(outcome: Dict[str, Any]) -> str:
final = outcome["final"]
lines = []
if final.get("problem_math"):
lines.append("Problem as understood : %s" % final["problem_math"])
lines.append("Status : %s (assurance level %d of 3)" % (final["status"], final["assurance"]))
lines.append("Answer : %s" % (final["answer_text"] or "-"))
if final["reasons"]:
lines.append("Notes : %s" % "; ".join(final["reasons"]))
if outcome["referee"]:
agree = sum(1 for r in outcome["referee"] if r["claimed"] == r["referee"])
lines.append("Orchestrator Z3 check : %d of %d envelopes confirmed" % (agree, len(outcome["referee"])))
return "\n".join(lines)
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("problem", nargs="?", help="a sentence of the math language")
parser.add_argument("--json", action="store_true", help="print the full machine readable outcome")
parser.add_argument("--faults", default="", help="comma separated agent:fault pairs (experiments only)")
parser.add_argument("--keep", action="store_true", help="keep the temporary workspace")
parser.add_argument("--corpus", help="run every problem of a corpus file and compare with its gold answers")
parser.add_argument("--limit", type=int, default=0, help="with --corpus: only the first N problems")
args = parser.parse_args()
if args.corpus:
rows = corpus.load(args.corpus)
rows = rows[: args.limit] if args.limit else rows
tally: Dict[str, int] = {}
for item in rows:
outcome = solve(item["text"], args.faults, args.keep)
label = corpus.outcome(item, outcome["final"])
tally[label] = tally.get(label, 0) + 1
print("%-6s %-16s %-14s %s" % (item["id"], label, outcome["final"]["status"], item["text"]))
print(json.dumps(tally, sort_keys=True))
return 0 if tally.get("wrong", 0) == 0 and tally.get("abstain", 0) == 0 else 1
if not args.problem:
parser.error("a problem or --corpus is required")
outcome = solve(args.problem, args.faults, args.keep)
if args.json:
print(json.dumps(outcome, indent=2, default=str))
else:
print(_describe(outcome))
return 0 if outcome["final"]["status"] != "UNKNOWN" else 2
if __name__ == "__main__":
sys.exit(main())
|