math-stratum / tools /ask.py
tailot's picture
publish math-stratum bundle
e9dac18 verified
Raw History Blame Contribute Delete
8.76 kB
#!/usr/bin/env python3
"""Ask a question in a human language and get the answer of the math stratum back in that language.
python tools/ask.py --lang it "risolvi x^2 - 5*x + 6 = 0 per x"
python tools/ask.py --lang en "solve x^2 - 5*x + 6 = 0 for x" --json
python tools/ask.py --lang ar --corpus problems/corpus.jsonl --limit 6
Run from this folder (it is ``datasets/math-stratum`` 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 question and its language,
launcher), runs the eight node processes through ``MultiInstanceOrchestrator``, and then re-derives
the verdict from the transcript: it recomputes the arbiter's decision from the evidence the envelopes
carry, and checks that the Z3 run of the orchestrator agrees with what every node claimed about its
own envelope. What is printed is that re-derived verdict, not the one the arbiter wrote.
The prose of this script and of its labels stays English, as the repository requires; the answer
block is the one piece of data that is deliberately written in the language of the question, because
that answer is the object this bundle studies.
"""
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-stratum, so the orchestrator
# package is no longer a sibling of the bundle. Walk up the tree until an ancestor carries it.
for _parent in ROOT.parents:
_candidate = _parent / "src"
if (_candidate / "lingologos_orchestrator").is_dir():
sys.path.insert(0, str(_candidate))
break
from lgstratum import corpus, pipeline, protocol, render # noqa: E402
def _launcher(directory: Path) -> Path:
agent = ROOT / "agents" / "stratum_agent"
if os.name == "nt":
path = directory / "stratum_agent.cmd"
path.write_text('@echo off\r\n"%s" "%s" %%*\r\n' % (sys.executable, agent))
else:
path = directory / "stratum_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 ask(question: str, lang: str, faults_spec: str = "", keep: bool = False) -> Dict[str, Any]:
"""Run one question through the real orchestrator and return the checked verdict."""
from lingologos_orchestrator.orchestrator import MultiInstanceOrchestrator
from lingologos_orchestrator.schema import OrchestratorError
workspace = Path(tempfile.mkdtemp(prefix="lgstratum_"))
try:
datasets = workspace / "datasets"
shutil.copytree(ROOT / "nodes", datasets)
seed_path = datasets / "arbiter" / "seed_payload.json"
seed = json.loads(seed_path.read_text(encoding="utf-8"))
seed["payload"]["naturalLanguage"] = pipeline.seed(question, lang)["payload"]["naturalLanguage"]
seed_path.write_text(json.dumps(seed, ensure_ascii=False), encoding="utf-8")
launcher = _launcher(workspace)
topology = json.loads((ROOT / "topology.json").read_text(encoding="utf-8"))
for instance in topology["instances"]:
instance["executable"] = str(launcher)
topology_path = workspace / "topology.json"
topology_path.write_text(json.dumps(topology), encoding="utf-8")
previous = os.environ.get("LGSTRATUM_FAULTS")
os.environ["LGSTRATUM_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": [], "reply": None}
finally:
if previous is None:
os.environ.pop("LGSTRATUM_FAULTS", None)
else:
os.environ["LGSTRATUM_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 {"state": "NONE", "assurance": 0, "ceiling": 0, "math_assurance": 0, "math_status": None,
"answer": "", "reasons": [reason], "consulted_math": False, "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": referee, "transcript": records,
"dossier": dossier, "reply": render.reply(dossier, final, referee), "turns": result["total_turns"]}
def _describe(outcome: Dict[str, Any]) -> str:
final = outcome["final"]
lines = []
lines.append("Reading state : %s" % final["state"])
lines.append("Assurance shown : %d (reading ceiling %d, math assurance %s)"
% (final["assurance"], final.get("ceiling", 0),
final.get("math_assurance")))
lines.append("Math layer status : %s" % (final.get("math_status") or "-"))
if final["reasons"]:
lines.append("Notes : %s" % "; ".join(final["reasons"]))
if final.get("detected"):
lines.append("Detected : %s" % ", ".join(str(item) for item in final["detected"]))
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"])))
reply = outcome.get("reply")
if reply:
lines.append("")
lines.append("Answer in the language of the question (%s):" % reply["language"])
for line in reply["lines"]:
lines.append(" %s" % line)
return "\n".join(lines)
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("question", nargs="?", help="the question, written in the language given by --lang")
parser.add_argument("--lang", default="it", help="language of the question: it, en, es, zh, hi or ar")
parser.add_argument("--json", action="store_true", help="print the full machine readable outcome")
parser.add_argument("--faults", default="", help="comma separated node:fault pairs (experiments only)")
parser.add_argument("--keep", action="store_true", help="keep the temporary workspace")
parser.add_argument("--corpus", help="run every question of a corpus file and compare with its gold expectations")
parser.add_argument("--limit", type=int, default=0, help="with --corpus: only the first N questions")
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 = ask(item["question"], item["lang"], args.faults, args.keep)
verdict = corpus.grade(item, outcome)
label = "ok" if verdict["ok"] else "wrong"
tally[label] = tally.get(label, 0) + 1
print("%-8s %-6s %-14s %s" % (verdict["id"], label, verdict["state"], item["question"]))
for problem in verdict["problems"]:
print(" %s" % problem)
print(json.dumps(tally, sort_keys=True))
return 0 if tally.get("wrong", 0) == 0 else 1
if not args.question:
parser.error("a question or --corpus is required")
outcome = ask(args.question, args.lang, args.faults, args.keep)
if args.json:
printable = {key: value for key, value in outcome.items() if key != "records"}
print(json.dumps(printable, indent=2, ensure_ascii=False, default=str))
else:
print(_describe(outcome))
if outcome["final"].get("detected"):
return 3
return 0 if int(outcome["final"].get("assurance", 0) or 0) > 0 else 2
if __name__ == "__main__":
sys.exit(main())