lingologos-math / tools /solve.py
tailot's picture
Add the fourteen sentence families and the decision rule of README section 3
f74e990 verified
Raw History Blame Contribute Delete
7.09 kB
#!/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 lgmath 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="lgmath_"))
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("LGMATH_FAULTS")
os.environ["LGMATH_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("LGMATH_FAULTS", None)
else:
os.environ["LGMATH_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())