Spaces:
Sleeping
Sleeping
Upload app_deepseek.py
Browse files- app_deepseek.py +179 -0
app_deepseek.py
CHANGED
|
@@ -235,6 +235,7 @@ import shutil
|
|
| 235 |
import socket
|
| 236 |
import subprocess
|
| 237 |
import tarfile
|
|
|
|
| 238 |
import threading
|
| 239 |
import traceback
|
| 240 |
import urllib.robotparser
|
|
@@ -3041,6 +3042,10 @@ def generate_records(client, plan: CyclePlan, scenario: dict) -> dict:
|
|
| 3041 |
# ---------------------------------------------------------------------------
|
| 3042 |
AGENT_TASK_MAX_TOOL_CALLS = int(os.environ.get("GIJL_AGENT_TASK_MAX_CALLS", "8"))
|
| 3043 |
AGENT_TASK_MAX_NUDGES = 2
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3044 |
_TASK_TAG_RE = re.compile(r"<task>(.*?)</task>", re.DOTALL | re.IGNORECASE)
|
| 3045 |
_PY_CODE_BLOCK_RE = re.compile(r"```(?:python|py)?\s*\n(.*?)```", re.DOTALL)
|
| 3046 |
|
|
@@ -3126,6 +3131,129 @@ def _safe_ast_parse(ast_mod, code: str) -> bool:
|
|
| 3126 |
return True
|
| 3127 |
|
| 3128 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3129 |
def run_agent_task(client, plan: CyclePlan, scenario: dict) -> dict:
|
| 3130 |
"""Stage 2 for loops with uses_tools=True: a bounded ReAct loop over the SAME tool registry as scouting, but
|
| 3131 |
solving a genuine (simulated) user task instead of looking for raw material. Returns the same {"ok", "records"}
|
|
@@ -3207,6 +3335,25 @@ def run_agent_task(client, plan: CyclePlan, scenario: dict) -> dict:
|
|
| 3207 |
code_ok = _code_syntax_ok(final_answer)
|
| 3208 |
if code_ok is not None:
|
| 3209 |
rec["code_syntax_ok"] = code_ok # cheap, real, non-LLM signal -- see _code_syntax_ok
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3210 |
if outcome != "success" or not final_answer:
|
| 3211 |
return _fail(f"agent_task did not finish cleanly: {outcome}")
|
| 3212 |
limits = {"task_prompt": (15, 2000), "final_answer": (30, 8000)}
|
|
@@ -3339,12 +3486,44 @@ def _annotate(gen: dict, verified: str, score: int):
|
|
| 3339 |
rec["verified"], rec["verifier_score"] = verified, int(score)
|
| 3340 |
|
| 3341 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3342 |
def verify_generated(client, state, plan: CyclePlan, scenario: dict, gen: dict) -> dict:
|
| 3343 |
"""gen -> gen (annotated) or _fail(...). Never raises: an unavailable verifier marks the records
|
| 3344 |
verified='unavailable' instead of silently passing them as 'pass'."""
|
| 3345 |
if not VERIFY:
|
| 3346 |
return gen
|
| 3347 |
loop = plan.loop.name
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3348 |
try:
|
| 3349 |
content, expect = _verify_input(plan, scenario, gen["records"][0][1])
|
| 3350 |
system = _VERIFY_TEMPLATES[loop].format(untrusted_note=_UNTRUSTED_NOTE, patterns=", ".join(RESPONSE_PATTERNS))
|
|
|
|
| 235 |
import socket
|
| 236 |
import subprocess
|
| 237 |
import tarfile
|
| 238 |
+
import tempfile
|
| 239 |
import threading
|
| 240 |
import traceback
|
| 241 |
import urllib.robotparser
|
|
|
|
| 3042 |
# ---------------------------------------------------------------------------
|
| 3043 |
AGENT_TASK_MAX_TOOL_CALLS = int(os.environ.get("GIJL_AGENT_TASK_MAX_CALLS", "8"))
|
| 3044 |
AGENT_TASK_MAX_NUDGES = 2
|
| 3045 |
+
# v6.1: hard, non-LLM gates -- see _execute_python_blocks / _grounding_check. A trajectory whose final_answer
|
| 3046 |
+
# asserts specific facts absent from its OWN tool results, or whose own demonstrated code fails to run, is
|
| 3047 |
+
# rejected here and never reaches the LLM judge at all (cheaper, and not gameable by fluent prose).
|
| 3048 |
+
AGENT_TASK_MIN_GROUNDING = float(os.environ.get("GIJL_AGENT_TASK_MIN_GROUNDING", "0.6"))
|
| 3049 |
_TASK_TAG_RE = re.compile(r"<task>(.*?)</task>", re.DOTALL | re.IGNORECASE)
|
| 3050 |
_PY_CODE_BLOCK_RE = re.compile(r"```(?:python|py)?\s*\n(.*?)```", re.DOTALL)
|
| 3051 |
|
|
|
|
| 3131 |
return True
|
| 3132 |
|
| 3133 |
|
| 3134 |
+
# --- v6.1: REAL, non-LLM verification -- execution + source grounding --------------------------------------------
|
| 3135 |
+
# This is the direct fix for the gap the harness operator flagged: the pipeline was only ever checking that a
|
| 3136 |
+
# response LOOKED right to another LLM call (_VERIFY_TEMPLATES below), never that code it produced actually RUNS,
|
| 3137 |
+
# and never that a specific number/name/URL the model asserts as fact was actually present in the page or tool
|
| 3138 |
+
# output it was supposedly drawn from. An LLM judge only ever sees the text the writer-model produced; it has no
|
| 3139 |
+
# access to ground truth, so a confident, fluent, WRONG number passes every rubric field. These two checks read
|
| 3140 |
+
# the actual fetched material instead and are mechanical (regex / subprocess), so they cannot be talked out of a
|
| 3141 |
+
# verdict by fluent prose the way an LLM judge can.
|
| 3142 |
+
_UNSAFE_EXEC_RE = _DANGEROUS_TOKENS_RE # reuse the same attacker-tooling denylist as a pre-execution gate
|
| 3143 |
+
|
| 3144 |
+
|
| 3145 |
+
def _execute_python_blocks(text: str, timeout_s: int = 6):
|
| 3146 |
+
"""Actually RUNS each fenced Python block in `text` in an isolated subprocess (fresh temp dir, no inherited
|
| 3147 |
+
env beyond PATH, wall-clock timeout, and on POSIX a resource.setrlimit cap on CPU time / address space / open
|
| 3148 |
+
files / file size via preexec_fn) instead of only ast.parse()-ing it (_code_syntax_ok). That is the actual
|
| 3149 |
+
DeepMind synthetic-data-report recommendation -- verify with execution where you can -- because a syntax check
|
| 3150 |
+
only proves the code is well-formed, never that it does what the answer around it claims.
|
| 3151 |
+
Returns None when there is no Python block to run (the syntax-only path still applies in that case), else:
|
| 3152 |
+
{"attempted": n, "ran": n, "errored": n, "errors": [str, ...]}
|
| 3153 |
+
A block that imports an unavailable third-party package is excluded from "attempted" entirely -- that is a
|
| 3154 |
+
sandbox environment gap, not evidence the generated code is wrong, and must never fail the record. A block
|
| 3155 |
+
matching the attacker-tooling denylist is never executed at all and is also excluded (handled upstream by the
|
| 3156 |
+
`rejected`-side safety filter already; this is defense in depth, not a second rejection path)."""
|
| 3157 |
+
blocks = _PY_CODE_BLOCK_RE.findall(text or "")
|
| 3158 |
+
if not blocks:
|
| 3159 |
+
return None
|
| 3160 |
+
result = {"attempted": 0, "ran": 0, "errored": 0, "errors": []}
|
| 3161 |
+
for code in blocks[:5]: # cap: a handful of blocks is plenty of signal; one record must never stall the run
|
| 3162 |
+
if _UNSAFE_EXEC_RE.search(code):
|
| 3163 |
+
continue
|
| 3164 |
+
try:
|
| 3165 |
+
import ast as _ast
|
| 3166 |
+
_ast.parse(code)
|
| 3167 |
+
except SyntaxError as e:
|
| 3168 |
+
result["attempted"] += 1
|
| 3169 |
+
result["errored"] += 1
|
| 3170 |
+
result["errors"].append(f"SyntaxError: {e}")
|
| 3171 |
+
continue
|
| 3172 |
+
with tempfile.TemporaryDirectory(prefix="gijl_exec_") as sandbox_dir:
|
| 3173 |
+
script_path = os.path.join(sandbox_dir, "snippet.py")
|
| 3174 |
+
try:
|
| 3175 |
+
with open(script_path, "w", encoding="utf-8") as f:
|
| 3176 |
+
f.write(code)
|
| 3177 |
+
except OSError:
|
| 3178 |
+
continue
|
| 3179 |
+
|
| 3180 |
+
def _limit_resources(): # noqa: ANN001 -- preexec_fn: runs in the forked child, before exec
|
| 3181 |
+
try:
|
| 3182 |
+
import resource
|
| 3183 |
+
resource.setrlimit(resource.RLIMIT_CPU, (timeout_s, timeout_s + 1))
|
| 3184 |
+
resource.setrlimit(resource.RLIMIT_AS, (512 * 1024 * 1024, 512 * 1024 * 1024))
|
| 3185 |
+
resource.setrlimit(resource.RLIMIT_NOFILE, (64, 64))
|
| 3186 |
+
resource.setrlimit(resource.RLIMIT_FSIZE, (10 * 1024 * 1024, 10 * 1024 * 1024))
|
| 3187 |
+
except Exception: # noqa: BLE001 -- best-effort; non-POSIX platforms have no `resource` module
|
| 3188 |
+
pass
|
| 3189 |
+
try:
|
| 3190 |
+
proc = subprocess.run(
|
| 3191 |
+
[sys.executable, "-I", "-S", script_path],
|
| 3192 |
+
cwd=sandbox_dir, capture_output=True, text=True, errors="replace", timeout=timeout_s,
|
| 3193 |
+
env={"PATH": os.environ.get("PATH", "")},
|
| 3194 |
+
preexec_fn=(_limit_resources if os.name == "posix" else None))
|
| 3195 |
+
except subprocess.TimeoutExpired:
|
| 3196 |
+
result["attempted"] += 1
|
| 3197 |
+
result["errored"] += 1
|
| 3198 |
+
result["errors"].append("timed out")
|
| 3199 |
+
continue
|
| 3200 |
+
except Exception as e: # noqa: BLE001 -- a sandbox-launch failure must never crash the whole pipeline
|
| 3201 |
+
result["errors"].append(f"sandbox launch error: {type(e).__name__}")
|
| 3202 |
+
continue
|
| 3203 |
+
err = (proc.stderr or "").strip()
|
| 3204 |
+
if "ModuleNotFoundError" in err or "ImportError" in err:
|
| 3205 |
+
continue # third-party package unavailable in THIS sandbox -- not a verdict on the code
|
| 3206 |
+
result["attempted"] += 1
|
| 3207 |
+
if proc.returncode == 0:
|
| 3208 |
+
result["ran"] += 1
|
| 3209 |
+
else:
|
| 3210 |
+
result["errored"] += 1
|
| 3211 |
+
result["errors"].append(_trunc(err.splitlines()[-1] if err else "non-zero exit", 160))
|
| 3212 |
+
return result if result["attempted"] else None
|
| 3213 |
+
|
| 3214 |
+
|
| 3215 |
+
_NUMBER_ATOM_RE = re.compile(r"(?<![\w.])\d{1,3}(?:,\d{3})*(?:\.\d+)?\s?%?(?![\w])")
|
| 3216 |
+
_URL_ATOM_RE = re.compile(r"https?://[^\s)\]\"'<>]+")
|
| 3217 |
+
_PROPER_NOUN_RE = re.compile(r"\b[A-Z][a-zA-Z0-9]*(?:\.[A-Z][a-zA-Z0-9]*)*(?:\s+[A-Z][a-zA-Z0-9]+){1,4}\b")
|
| 3218 |
+
|
| 3219 |
+
|
| 3220 |
+
def _extract_checkable_atoms(text: str) -> list:
|
| 3221 |
+
"""Mechanically pulls out the SPECIFIC, checkable factual claims in `text`: numbers/percentages, URLs, and
|
| 3222 |
+
multi-word capitalized spans (named entities -- people, orgs, products, APIs, places). These are the claims a
|
| 3223 |
+
grounding check can actually verify against source text; ordinary connective prose is not checkable and is
|
| 3224 |
+
skipped on purpose -- this is not a claim-completeness check, only a claim-ACCURACY check on what IS checkable."""
|
| 3225 |
+
if not text:
|
| 3226 |
+
return []
|
| 3227 |
+
atoms = set()
|
| 3228 |
+
atoms.update(m.group(0) for m in _URL_ATOM_RE.finditer(text))
|
| 3229 |
+
atoms.update(m.group(0).strip() for m in _NUMBER_ATOM_RE.finditer(text)
|
| 3230 |
+
if len(re.sub(r"[^\d]", "", m.group(0))) >= 2)
|
| 3231 |
+
atoms.update(m.group(0) for m in _PROPER_NOUN_RE.finditer(text))
|
| 3232 |
+
return list(atoms)[:40] # cap: keep the check cheap and keep one outlier answer from dominating the stats
|
| 3233 |
+
|
| 3234 |
+
|
| 3235 |
+
def _grounding_check(claim_text: str, source_text: str):
|
| 3236 |
+
"""The mechanical cross-check an LLM judge structurally cannot do: every checkable atom (number, URL, named
|
| 3237 |
+
entity) asserted in `claim_text` must actually appear in `source_text` -- the REAL tool_results/page text the
|
| 3238 |
+
model had in front of it during generation, not the model's own self-report about what it found. This is what
|
| 3239 |
+
directly answers 'verification must be grounded in the page/source data, not just a quick self-graded answer'.
|
| 3240 |
+
Returns (grounded_fraction in [0,1], [up to 8 ungrounded atoms]), or (None, []) when the claim text has nothing
|
| 3241 |
+
mechanically checkable in it (pure opinion/how-to text -- not a failure, just nothing for this check to grade)."""
|
| 3242 |
+
atoms = _extract_checkable_atoms(claim_text)
|
| 3243 |
+
if not atoms:
|
| 3244 |
+
return None, []
|
| 3245 |
+
hay = _norm_text(source_text)
|
| 3246 |
+
ungrounded = []
|
| 3247 |
+
hits = 0
|
| 3248 |
+
for a in atoms:
|
| 3249 |
+
needle = _norm_text(a)
|
| 3250 |
+
if needle and needle in hay:
|
| 3251 |
+
hits += 1
|
| 3252 |
+
else:
|
| 3253 |
+
ungrounded.append(a)
|
| 3254 |
+
return hits / len(atoms), ungrounded[:8]
|
| 3255 |
+
|
| 3256 |
+
|
| 3257 |
def run_agent_task(client, plan: CyclePlan, scenario: dict) -> dict:
|
| 3258 |
"""Stage 2 for loops with uses_tools=True: a bounded ReAct loop over the SAME tool registry as scouting, but
|
| 3259 |
solving a genuine (simulated) user task instead of looking for raw material. Returns the same {"ok", "records"}
|
|
|
|
| 3335 |
code_ok = _code_syntax_ok(final_answer)
|
| 3336 |
if code_ok is not None:
|
| 3337 |
rec["code_syntax_ok"] = code_ok # cheap, real, non-LLM signal -- see _code_syntax_ok
|
| 3338 |
+
# v6.1 real execution: actually runs any code the agent put in its final_answer (see _execute_python_blocks),
|
| 3339 |
+
# instead of only syntax-checking it. A trajectory where every runnable block errors out is rejected outright --
|
| 3340 |
+
# "it parses" is not "it works", and training on code presented as working that in fact fails is the exact
|
| 3341 |
+
# hallucination-reinforcing failure mode the operator flagged.
|
| 3342 |
+
exec_result = _execute_python_blocks(final_answer)
|
| 3343 |
+
if exec_result is not None:
|
| 3344 |
+
rec["code_executed"] = exec_result
|
| 3345 |
+
if exec_result["attempted"] and exec_result["errored"] == exec_result["attempted"]:
|
| 3346 |
+
return _fail(f"every executable code block in final_answer failed to run: {exec_result['errors'][:2]}")
|
| 3347 |
+
# v6.1 source grounding: cross-checks specific facts in final_answer against the trajectory's OWN tool_results
|
| 3348 |
+
# text (see _grounding_check) -- not the model's self-report, the actual fetched content. A trajectory that
|
| 3349 |
+
# claims a number/name/URL its own tools never returned is rejected before it ever reaches the LLM judge.
|
| 3350 |
+
tool_text = "\n".join(r["content"] for s in trace.steps for r in s.get("tool_results", []))
|
| 3351 |
+
grounded_frac, ungrounded = _grounding_check(final_answer, tool_text)
|
| 3352 |
+
if grounded_frac is not None:
|
| 3353 |
+
rec["grounding_score"], rec["ungrounded_claims"] = round(grounded_frac, 2), ungrounded
|
| 3354 |
+
if grounded_frac < AGENT_TASK_MIN_GROUNDING and tool_text.strip():
|
| 3355 |
+
return _fail(f"final_answer asserts facts not found in its own tool results "
|
| 3356 |
+
f"(grounding={grounded_frac:.2f}): {ungrounded[:3]}")
|
| 3357 |
if outcome != "success" or not final_answer:
|
| 3358 |
return _fail(f"agent_task did not finish cleanly: {outcome}")
|
| 3359 |
limits = {"task_prompt": (15, 2000), "final_answer": (30, 8000)}
|
|
|
|
| 3486 |
rec["verified"], rec["verifier_score"] = verified, int(score)
|
| 3487 |
|
| 3488 |
|
| 3489 |
+
def _grounding_pretest(plan: CyclePlan, scenario: dict, rec: dict):
|
| 3490 |
+
"""v6.1: a mechanical, non-LLM gate that runs BEFORE the LLM judge even sees the record (see
|
| 3491 |
+
_grounding_check). sft_helpful and reasoning_qa are built FROM a specific source document -- the whole point
|
| 3492 |
+
is that the written answer is grounded in it, not invented. This reads the actual source/reference text and
|
| 3493 |
+
rejects a record whose specific facts are not in it, rather than trusting the writer-model's own claim (and
|
| 3494 |
+
the judge-model's agreement with that claim) that it checked. Returns None (nothing checkable / not applicable
|
| 3495 |
+
to this loop -- judgment_dpo and agent_task are handled elsewhere) or a rejection string."""
|
| 3496 |
+
loop = plan.loop.name
|
| 3497 |
+
if loop == "sft_helpful":
|
| 3498 |
+
claim = rec["messages"][1]["content"]
|
| 3499 |
+
source = scenario.get("reference") or scenario.get("body") or ""
|
| 3500 |
+
elif loop == "reasoning_qa":
|
| 3501 |
+
claim = rec.get("answer", "") + "\n" + "\n".join(rec.get("reasoning_steps", []))
|
| 3502 |
+
source = scenario.get("body") or ""
|
| 3503 |
+
else:
|
| 3504 |
+
return None
|
| 3505 |
+
if not source.strip():
|
| 3506 |
+
return None # no source text to ground against (e.g. a reference-only scenario) -- nothing to check
|
| 3507 |
+
frac, ungrounded = _grounding_check(claim, source)
|
| 3508 |
+
if frac is not None and frac < _VERIFY_SFT_MIN_GROUNDING:
|
| 3509 |
+
return f"answer asserts facts not found in the source material (grounding={frac:.2f}): {ungrounded[:3]}"
|
| 3510 |
+
return None
|
| 3511 |
+
|
| 3512 |
+
|
| 3513 |
+
_VERIFY_SFT_MIN_GROUNDING = float(os.environ.get("GIJL_SFT_MIN_GROUNDING", "0.5"))
|
| 3514 |
+
|
| 3515 |
+
|
| 3516 |
def verify_generated(client, state, plan: CyclePlan, scenario: dict, gen: dict) -> dict:
|
| 3517 |
"""gen -> gen (annotated) or _fail(...). Never raises: an unavailable verifier marks the records
|
| 3518 |
verified='unavailable' instead of silently passing them as 'pass'."""
|
| 3519 |
if not VERIFY:
|
| 3520 |
return gen
|
| 3521 |
loop = plan.loop.name
|
| 3522 |
+
ground_err = _grounding_pretest(plan, scenario, gen["records"][0][1])
|
| 3523 |
+
if ground_err:
|
| 3524 |
+
state.stats["grounding_rejected"] += 1
|
| 3525 |
+
print(f"[verify][REJECT-grounding] {loop}: {ground_err}", flush=True)
|
| 3526 |
+
return _fail(ground_err)
|
| 3527 |
try:
|
| 3528 |
content, expect = _verify_input(plan, scenario, gen["records"][0][1])
|
| 3529 |
system = _VERIFY_TEMPLATES[loop].format(untrusted_note=_UNTRUSTED_NOTE, patterns=", ".join(RESPONSE_PATTERNS))
|