coqar-clarifications / code /run_pilot.py
rvashurin's picture
Publish paired CoQAR clarification datasets
833376d verified
Raw History Blame Contribute Delete
23.7 kB
"""Small, resumable, budget-limited CoQAR clarification experiment."""
import argparse
from concurrent.futures import ThreadPoolExecutor
import hashlib
import importlib.metadata
import json
import math
import os
from pathlib import Path
import platform
import random
import socket
import subprocess
import sys
import threading
import time
from datetime import datetime, timezone
import requests
ROOT = Path(__file__).resolve().parent
MODEL = "gpt-5.6-luna"
RATES = {"input": 0.20, "cached_input": 0.02, "output": 1.20}
def menu_schema(version):
item = {"id": {"type": "string"}, "scenario": {"type": "string"},
"probability": {"type": "number"}}
props = {"status": {"type": "string", "enum": ["already_answerable", "underspecified"]},
"gap": {"type": "string"}}
if version == "latent_v2":
item["exclusions"] = {"type": "array", "items": {"type": "string"}}
props["constraints"] = {"type": "array", "items": {"type": "string"}}
props["items"] = {"type": "array", "items": {"type": "object", "properties": item,
"required": list(item), "additionalProperties": False}}
return {"type": "object", "properties": props, "required": list(props), "additionalProperties": False}
def sha(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def save(path, value):
temporary = path.with_suffix(path.suffix + ".tmp")
temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2))
temporary.replace(path)
def metadata(workers=4):
def git(*args):
return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip()
if git("status", "--porcelain"):
raise RuntimeError("Commit the experiment code and prompts before running.")
return {
"commit_hash": git("rev-parse", "HEAD"), "git_clean": True,
"repo": {"path": str(ROOT), "remote": git("remote", "-v")},
"timestamp_utc": datetime.now(timezone.utc).isoformat(),
"commands": [{"cwd": str(Path.cwd()), "argv": [sys.executable, *sys.argv]}],
"configs": {"model": MODEL, "reasoning": "none", "temperature": 1.0, "workers": workers,
"top_p": "default", "store": False, "rates_per_million_usd": RATES,
"pricing_source": "https://developers.openai.com/api/docs/models/gpt-5.6-luna"},
"dataset": {"selection": "data/pilot10.json", "sha256": sha(ROOT / "data/pilot10.json")},
"model": {"requested": MODEL, "snapshot": "Alias; actual response model recorded per call"},
"environment": {"python": platform.python_version(), "platform": platform.platform(),
"packages": {d.metadata['Name']: d.version for d in importlib.metadata.distributions()}},
"compute": {"hostname": socket.gethostname(), "device": "remote OpenAI API"},
"seeds": {"menu_draws": 20260911, "api_seed": None,
"note": "Independent API calls, no conversation state; exact API replay not deterministic"},
"prompts": {p.name: {"sha256": sha(p), "text": p.read_text()} for p in sorted((ROOT / "prompts").glob("*.txt"))},
}
class Client:
def __init__(self, meta, cap, namespace, ledger_path=None):
if not math.isfinite(cap) or cap <= 0:
raise ValueError("Budget must be finite and positive.")
if not namespace or "/" in namespace:
raise ValueError("Call namespace must be a nonempty path component.")
self.lock = threading.RLock()
self.namespace = namespace
self.reasoning = meta.get("configs", {}).get("reasoning", "none")
if self.reasoning not in ("none", "low"):
raise ValueError("This pilot supports reasoning none or low.")
self.path = Path(ledger_path) if ledger_path is not None else ROOT / "results/api_ledger.json"
self.path.parent.mkdir(parents=True, exist_ok=True)
self.ledger = json.loads(self.path.read_text()) if self.path.exists() else {
"metadata": meta, "runs": [], "calls": []}
self.ledger["runs"].append(meta)
self.cap = cap
self.key = os.environ.get("OPENAI_API_KEY")
if not self.key:
raise RuntimeError("OPENAI_API_KEY is absent; no secrets are logged.")
save(self.path, self.ledger)
def spent(self):
with self.lock:
return sum(c.get("cost_usd", c.get("reservation_usd", 0)) for c in self.ledger["calls"])
def interrupt_pending(self):
"""Keep reservations for dispatched calls whose outcomes remain unknown."""
with self.lock:
for record in self.ledger["calls"]:
if record["id"].startswith(self.namespace + "/") and record["status"] == "pending":
record["status"] = "interrupted_uncertain"
record["error_type"] = "KeyboardInterrupt"
record.pop("cost_usd", None)
save(self.path, self.ledger)
def call(self, identifier, instructions, payload, max_output=400, structured=True, schema=None,
reasoning_effort=None):
identifier = self.namespace + "/" + identifier
request = {"model": MODEL, "instructions": instructions,
"input": ("Input JSON:\n" if structured else "") + json.dumps(payload, ensure_ascii=False),
"reasoning": {"effort": reasoning_effort or self.reasoning}, "temperature": 1.0,
"max_output_tokens": max_output, "store": False, "service_tier": "default"}
if structured:
request["text"] = {"format": {"type": "json_object"}}
if schema is not None:
request["text"] = {"format": {"type": "json_schema", "name": "experiment_output",
"strict": True, "schema": schema}}
request_hash = hashlib.sha256(json.dumps(request, sort_keys=True).encode()).hexdigest()
# UTF-8 bytes exceed ordinary token counts; reserve an extra 2048-token
# overhead and 25% input premium. Reserve under the lock before dispatch,
# so every concurrent request counts all other pending reservations.
input_bound = len(json.dumps(request, ensure_ascii=False).encode()) + 2048
reserve = (input_bound * RATES["input"] * 1.25 + max_output * RATES["output"]) / 1e6
with self.lock:
existing = [c for c in self.ledger["calls"] if c["id"] == identifier]
if existing:
prior = existing[-1]
corrected_rejection = (prior["status"] == "api_error" and prior.get("http_status") == 400
and prior["request_sha256"] != request_hash)
if prior["request_sha256"] != request_hash and not corrected_rejection:
raise RuntimeError(f"Request changed for {identifier}; use a new version ID.")
if prior["status"] != "completed" and not corrected_rejection:
raise RuntimeError(f"Preserved failed/uncertain call {identifier}; not automatically reissued.")
if not corrected_rejection:
return prior
if self.spent() + reserve > self.cap:
raise RuntimeError(f"Budget guard: estimated spend {self.spent():.4f} + reserve {reserve:.4f} exceeds ${self.cap}")
record = {"id": identifier, "request": request, "request_sha256": request_hash,
"commit_hash": self.ledger["runs"][-1]["commit_hash"],
"status": "pending", "reservation_usd": reserve,
"started_utc": datetime.now(timezone.utc).isoformat()}
self.ledger["calls"].append(record)
save(self.path, self.ledger)
try:
response = requests.post("https://api.openai.com/v1/responses",
headers={"Authorization": "Bearer " + self.key},
json=request, timeout=(15, 90))
body = response.json()
with self.lock:
record["http_status"] = response.status_code
record["response"] = body
record["request_id"] = response.headers.get("x-request-id")
if not response.ok:
record["status"] = "api_error"
# Only explicit client/auth/rate-limit rejections release the reserve.
if response.status_code in (400, 401, 403, 404, 422, 429):
record["cost_usd"] = 0
save(self.path, self.ledger)
raise RuntimeError(f"API rejected {identifier}: {body.get('error', {}).get('code')} {body.get('error', {}).get('message')}")
usage = body.get("usage") or {}
cached = (usage.get("input_tokens_details") or {}).get("cached_tokens", 0)
if (any(type(usage.get(k)) is not int or usage[k] < 0
for k in ("input_tokens", "output_tokens"))
or type(cached) is not int or not 0 <= cached <= usage["input_tokens"]):
record["status"] = "usage_uncertain"
save(self.path, self.ledger)
raise RuntimeError("Response lacks valid token usage; budget reservation retained.")
record["cost_usd"] = ((usage["input_tokens"] - cached) * RATES["input"]
+ cached * RATES["cached_input"]
+ usage["output_tokens"] * RATES["output"]) / 1e6
record["text"] = "".join(part.get("text", "") for item in body.get("output", [])
if item.get("type") == "message" for part in item.get("content", [])
if part.get("type") == "output_text")
record["status"] = "completed" if body.get("status") == "completed" else "incomplete"
if structured and record["status"] == "completed":
try:
record["parsed"] = json.loads(record["text"])
except json.JSONDecodeError:
record["status"] = "parse_error"
save(self.path, self.ledger)
print(f"{identifier}: {record['status']}; cumulative estimated ${self.spent():.4f}", flush=True)
if record["status"] != "completed":
raise RuntimeError(f"Invalid output {identifier}; raw response saved, no resampling.")
return record
except BaseException as error:
with self.lock:
if record["status"] in ("pending", "interrupted_uncertain"):
record["status"] = ("interrupted_uncertain" if isinstance(error, KeyboardInterrupt)
else "transport_uncertain" if isinstance(error, requests.RequestException)
else "response_uncertain")
record["error_type"] = type(error).__name__
record.pop("cost_usd", None)
save(self.path, self.ledger)
if isinstance(error, requests.RequestException):
raise RuntimeError("Transport failed; reservation retained and request not retried.") from error
raise
def prompt(name):
return (ROOT / "prompts" / (name + ".txt")).read_text()
def sample_menu(menu, example_id, method, sample_index):
items = menu.get("items", [])
if not 1 <= len(items) <= 5 or len({i["id"] for i in items}) != len(items):
raise ValueError("Menu must have 1-5 unique IDs.")
probabilities = [float(i["probability"]) for i in items]
if any(not math.isfinite(p) or p < 0 for p in probabilities) or not math.isclose(sum(probabilities), 1, abs_tol=0.02):
raise ValueError("Menu weights are invalid or do not approximately sum to 1.")
seed_text = f"20260911:{example_id}:{method}:{sample_index}"
seed = int(hashlib.sha256(seed_text.encode()).hexdigest(), 16)
draw = random.Random(seed).random()
total = sum(probabilities)
cumulative = 0
for item, probability in zip(items, probabilities):
cumulative += probability / total
if draw < cumulative:
return item["id"], {"uniform_draw": draw, "seed_text": seed_text,
"normalization": total, "sampling": "categorical with replacement"}
raise AssertionError("Categorical selection failed")
def parse_sample(record, story, baseline=False):
if baseline:
raw = record["text"].strip()
text_part, delimiter, justification = raw.partition("\nJustification:")
if not delimiter or not text_part.startswith("Text:"):
return {"valid_format": False, "clarified_story": story,
"raw_text": raw, "justification": "baseline parse failure; no usable completion"}
clarified = text_part[len("Text:"):].strip()
return {"valid_format": True, "clarified_story": clarified,
"passage_preserved": clarified.startswith(story.strip()),
"unchanged": clarified == story.strip(), "justification": justification.strip()}
value = record["parsed"]
valid = (value.get("status") in ("completed", "already_answerable")
and isinstance(value.get("addition"), str)
and isinstance(value.get("justification"), str))
if not valid:
return {"valid_format": False, "clarified_story": story, "raw_parsed": value}
addition = value["addition"].strip()
return {**value, "valid_format": True, "clarified_story": story + ("\n\n" + addition if addition else ""),
"passage_preserved": True, "unchanged": not addition}
def run(args):
if not 1 <= args.workers <= 4:
raise ValueError("Workers must be between one and four.")
meta = metadata(args.workers)
meta["configs"]["reasoning"] = args.reasoning
meta["configs"]["audit_reasoning"] = "none"
menu_limit = 4096 if args.reasoning == "low" else 1100
sample_limit = 2048 if args.reasoning == "low" else 400
meta["configs"]["generation_output_limits"] = {"menu": menu_limit, "sample": sample_limit}
namespace = meta["dataset"]["sha256"][:12]
if args.condition == "original":
namespace += "-original"
if args.reasoning != "none":
namespace += "-" + args.reasoning
meta["configs"]["call_namespace"] = namespace
meta["configs"]["condition"] = args.condition
meta["configs"]["budget_cap_usd"] = args.budget
selection = json.loads((ROOT / "data/pilot10.json").read_text())
examples = selection["examples"]
if len(examples) != 10:
raise ValueError("Pilot must contain exactly ten fixed examples.")
result_dir = ROOT / "results"
if args.reasoning != "none":
result_dir /= "reasoning_" + args.reasoning
result_dir /= args.condition
elif args.condition == "original":
result_dir /= "original_story"
result_path = result_dir / "pilot.json"
result = json.loads(result_path.read_text()) if result_path.exists() else {
"metadata": meta, "selection": selection, "input_audits": {}, "methods": {}}
if result["metadata"]["dataset"]["sha256"] != meta["dataset"]["sha256"]:
raise RuntimeError("The fixed pilot selection changed; use a separate results directory.")
if result["metadata"]["configs"].get("condition", "modified") != args.condition:
raise RuntimeError("Input condition changed; use a separate results directory.")
if result["metadata"]["configs"].get("reasoning", "none") != args.reasoning:
raise RuntimeError("Reasoning effort changed; use a separate results directory.")
client = Client(meta, args.budget, namespace, ledger_path=result_dir / "api_ledger.json")
result.setdefault("runs", []).append(meta)
for example in examples:
eid = example["id"]
story, question = example[args.condition + "_story"], example["question"]
# Pass only the chosen story and fixed standalone question. Rationale,
# gold answer, IDs, source domain, and dialogue history remain excluded.
visible = {"story": story, "question": question}
if args.stage == "audit_inputs":
for condition, passage in [("modified", example["modified_story"]), ("original", example["original_story"])]:
call = client.call(f"audit_input/{eid}/{condition}", prompt("audit_input"),
{"story": passage, "question": question}, max_output=350,
reasoning_effort="none")
result["input_audits"].setdefault(eid, {})[condition] = call["parsed"]
save(result_path, result)
continue
for method in args.methods.split(","):
group = result["methods"].setdefault(method, {}).setdefault(eid, {"samples": []})
menu = None
if method.startswith("latent"):
menu_id = f"{method}/{eid}/menu"
previous = next((c for c in client.ledger["calls"]
if c["id"] == client.namespace + "/" + menu_id and c["status"] == "completed"), None)
if method == "latent_v2" and previous and any("probability" not in i for i in previous["parsed"].get("items", [])):
# Repair only omitted weights on the exact saved support; never
# regenerate scenarios to obtain favorable diversity.
fixed_menu = previous["parsed"]
weight_item = {"type": "object", "properties": {"id": {"type": "string"}, "probability": {"type": "number"}},
"required": ["id", "probability"], "additionalProperties": False}
weight_schema = {"type": "object", "properties": {"weights": {"type": "array", "items": weight_item}},
"required": ["weights"], "additionalProperties": False}
repaired = client.call(menu_id + "_weights_repair",
"Assign model-estimated probability masses to the fixed supplied menu conditioned on the visible story and question. Return each existing ID exactly once with a nonnegative probability, summing to 1. Do not add, remove, rename or replace scenarios. Do not make weights uniform or diverse by design. Return JSON only.",
{**visible, "fixed_menu": fixed_menu}, max_output=400, schema=weight_schema)
weights = repaired["parsed"]["weights"]
if len(weights) != len(fixed_menu["items"]) or {w["id"] for w in weights} != {i["id"] for i in fixed_menu["items"]}:
raise ValueError("Weight-only repair changed menu IDs.")
lookup = {w["id"]: w["probability"] for w in weights}
menu = {**fixed_menu, "items": [{**i, "probability": lookup[i["id"]]} for i in fixed_menu["items"]]}
group["weight_repair_call_id"] = repaired["id"]
else:
menu_call = client.call(menu_id, prompt(method + "_menu"), visible, max_output=menu_limit,
schema=menu_schema(method) if method == "latent_v2" else None)
menu = menu_call["parsed"]
group["menu"] = menu
group["menu_call_id"] = client.namespace + "/" + menu_id
save(result_path, result)
def sample_one(index):
payload = dict(visible)
selection_info = {}
if menu is not None:
selected_id, selection_info = sample_menu(menu, eid, method, index)
selection_info["selected_id"] = selected_id
payload.update({"menu": menu, "selected_id": selected_id})
instructions = prompt("latent_v2_render" if method == "latent_v2" else "latent_render")
else:
instructions = prompt(method)
if method == "baseline":
# Preserve baseline wording and delimiter layout exactly.
instructions = instructions.replace("<input>\n</input>", "<input>\n" + story + "\n</input>")
instructions = instructions.replace("<question>\n</question>", "<question>\n" + question + "\n</question>")
payload = "Follow the provided instruction."
record = client.call(f"{method}/{eid}/sample/{index}", instructions, payload,
max_output=2500 if method == "baseline" else sample_limit,
structured=method != "baseline")
return {"sample_index": index, "api_call_id": record["id"],
**selection_info, **parse_sample(record, story, method == "baseline")}
# Menus and audits stay sequential; only these five independent
# sample calls overlap. Consume futures in sample-index order.
with ThreadPoolExecutor(max_workers=args.workers) as executor:
futures = [executor.submit(sample_one, index) for index in range(5)]
failures = []
try:
for index, future in enumerate(futures):
try:
sample = future.result()
except Exception as error:
failures.append(error)
continue
group["samples"] = sorted(
[s for s in group["samples"] if s["sample_index"] != index] + [sample],
key=lambda item: item["sample_index"])
save(result_path, result)
except KeyboardInterrupt:
for future in futures:
future.cancel()
client.interrupt_pending()
raise
if failures:
raise failures[0]
if args.audit:
samples = []
for sample in group["samples"]:
entry = {"sample_index": sample["sample_index"], "clarified_story": sample["clarified_story"]}
if menu is not None:
entry["selected_state"] = next(i for i in menu["items"] if i["id"] == sample["selected_id"])
entry["constraints"] = menu.get("constraints", [])
samples.append(entry)
audit = client.call(f"audit_samples/{method}/{eid}", prompt("audit_samples"),
{**visible, "samples": samples}, max_output=1800,
reasoning_effort="none")
group["audit"] = audit["parsed"]
save(result_path, result)
result["estimated_cost_usd"] = client.spent()
save(result_path, result)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--stage", choices=["audit_inputs", "sample"], default="sample")
parser.add_argument("--methods", default="baseline,direct_v1,latent_v1")
parser.add_argument("--condition", choices=["modified", "original"], default="modified")
parser.add_argument("--reasoning", choices=["none", "low"], default="none")
parser.add_argument("--audit", action="store_true")
parser.add_argument("--budget", type=float, default=1.0)
parser.add_argument("--workers", type=int, choices=range(1, 5), default=4)
run(parser.parse_args())