#!/usr/bin/env python3 """Answer a question of the physics language with the real LingoLOGOS orchestrator. python tools/ask.py "convert 3 km to m" python tools/ask.py --json "pi period from mass, stiffness" python tools/ask.py --corpus problems/corpus.jsonl python tools/ask.py --in-process "audit V = I * R" Run from this folder (it is ``datasets/physics`` inside the LingoLOGOS repository, and the bundle root when the dataset is cloned on its own). The script builds a throw away workspace (the eleven node folders, the seed carrying the question, a launcher for the node program), runs the eleven node processes through ``MultiInstanceOrchestrator`` and then re-derives the verdict from the transcript: the dossier of the last envelope is decoded, the Z3 answers of the orchestrator are set beside what each node claimed, and the decision of the chain is recomputed from that evidence. ``--in-process`` runs the same eleven agents inside one process, which is the quicker of the two paths and the one the tests use. The chain asks the mathematics dataset as a separate process (``datasets/math``, or wherever ``LGPHYS_MATH_ROOT`` points). ``--no-math`` keeps that channel closed, so the physics answer can be seen standing on its own two roads; ``LGPHYS_FAULTS`` decides which nodes lie on purpose. """ 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 /datasets/physics, 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 lgphys import corpus, families, pipeline, protocol # noqa: E402 def _launcher(directory: Path) -> Path: agent = ROOT / "agents" / "physics_agent" if os.name == "nt": path = directory / "physics_agent.cmd" path.write_text('@echo off\r\n"%s" "%s" %%*\r\n' % (sys.executable, agent)) else: path = directory / "physics_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 _final(dossier: Dict[str, Any], decision: Dict[str, Any]) -> Dict[str, Any]: """What a run leaves behind, in the shape the corpus is scored on.""" answer = decision.get("answer") or dossier.get("answer") or {} math_block = dossier.get("math") or {} return { "status": str(decision.get("status") or "UNKNOWN"), "assurance": int(decision.get("assurance") or 0), "answer_text": str(decision.get("detail") or ""), "answer": answer, "reasons": list(decision.get("reasons") or []), "failures": list(decision.get("failures") or []), "kind": dossier.get("kind"), "problem": dossier.get("problem") or "", "delegate": dossier.get("delegate") or "", "math_status": str(math_block.get("status") or "NOT_ASKED"), "roads": sorted((dossier.get("roads") or {}).keys()), "states": dict(dossier.get("states") or {}), } def _unknown(reason: str) -> Dict[str, Any]: return {"final": {"status": "UNKNOWN", "assurance": 0, "answer_text": "", "answer": {}, "reasons": [reason], "failures": [], "kind": None, "problem": "", "delegate": "", "math_status": "NOT_ASKED", "roads": [], "states": {}}, "referee": [], "records": [], "turns": 0} def _check(result: Dict[str, Any]) -> Dict[str, Any]: """The outcome of an orchestrated run, re-derived from what the orchestrator recorded.""" records: List[Dict[str, Any]] = result["records"] if not records: return _unknown("the session produced no envelope") referee = [{"sender": r["sender"], "claimed": r["envelope"]["payload"]["smtConstraints"]["z3Status"], "referee": r["smt_result"]["status"]} for r in records] _problem, dossier = protocol.decode(records[-1]["envelope"]["payload"]["naturalLanguage"]) decision = pipeline.checked_verdict(dossier, referee) return {"final": _final(dossier, decision), "referee": referee, "records": records, "turns": result["total_turns"]} def solve(problem: str, faults_spec: str = "", keep: bool = False, in_process: bool = False) -> Dict[str, Any]: """Run one question through the eleven nodes and return the checked verdict.""" previous = os.environ.get("LGPHYS_FAULTS") os.environ["LGPHYS_FAULTS"] = faults_spec previous_cache = os.environ.get("PYTHONDONTWRITEBYTECODE") os.environ["PYTHONDONTWRITEBYTECODE"] = "1" try: if in_process: out = pipeline.run(problem, fault_spec=faults_spec) return {"final": _final(out["dossier"], out["decision"]), "referee": [{"sender": r["sender"], "claimed": r["claimed"], "referee": r["referee"]} for r in out["records"]], "records": out["records"], "turns": out["turns"]} return _orchestrated(problem, keep) finally: if previous is None: os.environ.pop("LGPHYS_FAULTS", None) else: os.environ["LGPHYS_FAULTS"] = previous if previous_cache is None: os.environ.pop("PYTHONDONTWRITEBYTECODE", None) else: os.environ["PYTHONDONTWRITEBYTECODE"] = previous_cache def _orchestrated(problem: str, keep: bool) -> Dict[str, Any]: """The real session: eleven processes, the orchestrator routing one envelope per turn.""" from lingologos_orchestrator.orchestrator import MultiInstanceOrchestrator from lingologos_orchestrator.schema import OrchestratorError workspace = Path(tempfile.mkdtemp(prefix="lgphys_")) 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"] = problem seed["payload"]["abstractSyntaxTree"] = "PhysicsProblem %s" % problem seed_path.write_text(json.dumps(seed), 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") 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 _unknown("orchestrator error: %s" % str(exc)[:200]) return _check(result) finally: if keep: print("workspace kept at %s" % workspace, file=sys.stderr) else: shutil.rmtree(workspace, ignore_errors=True) def _describe(outcome: Dict[str, Any]) -> str: final = outcome["final"] lines = [] if final.get("kind"): family = families.family_for(str(final["kind"])) lines.append("Question as read : %s" % (final["kind"] if family is None else "%s, %d road(s)" % (final["kind"], len(final["roads"])))) lines.append("Status : %s (assurance level %d of 2)" % (final["status"], final["assurance"])) lines.append("Answer : %s" % (final["answer_text"] or "-")) if final.get("delegate"): lines.append("Asked of mathematics : %s [%s]" % (final["delegate"], final["math_status"])) if final.get("failures"): lines.append("Checks that failed : %s" % ", ".join( sorted(set("%s.%s" % (agent, name) for agent, name, _burden in final["failures"])))) if final.get("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("question", nargs="?", help="a sentence of the physics 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("--in-process", action="store_true", help="run the eleven agents in this process instead of launching them") parser.add_argument("--no-math", action="store_true", help="do not ask the mathematics dataset; the physics roads answer alone") parser.add_argument("--corpus", help="run every question of a corpus file and compare with its gold") parser.add_argument("--limit", type=int, default=0, help="with --corpus: only the first N questions") args = parser.parse_args() if args.no_math: os.environ["LGPHYS_MATH_BACKEND"] = "none" 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, args.in_process) label = corpus.outcome(item, outcome["final"]) tally[label] = tally.get(label, 0) + 1 print("%-6s %-18s %-14s %s" % (item["id"], label, outcome["final"]["status"], item["text"])) print(json.dumps(tally, sort_keys=True)) bad = sum(tally.get(key, 0) for key in ("wrong", "wrong_state", "abstain", "delegation_wrong")) return 0 if bad == 0 else 1 if not args.question: parser.error("a question or --corpus is required") outcome = solve(args.question, args.faults, args.keep, args.in_process) if args.json: print(json.dumps(outcome, indent=2, sort_keys=True, default=protocol.plain)) else: print(_describe(outcome)) return 0 if outcome["final"]["status"] != "UNKNOWN" else 2 if __name__ == "__main__": sys.exit(main())