Spaces:
Sleeping
Sleeping
File size: 6,274 Bytes
d21c894 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | """Request-scoped agent roles. No database, broker, tools or retained transcripts."""
from __future__ import annotations
import hashlib
import json
import re
import time
from dataclasses import dataclass
from .inference_service import valid_content
from .language_contract import clean_label, script_valid
VERSION = "1.0.0"
MODE = "hf-bounded-agent-workflow"
POLICY = "hf-human-review-2026-11-25.1"
CAPABILITIES = ("translate.v1", "interpret.compat.v1", "reply.v1")
ISSUE_INSTRUCTIONS = {
"TARGET_SCRIPT_MISMATCH": "Use the selected parent language's required writing system.",
"UNTRANSLATED_SOURCE_COPY": "Produce the requested translation, not an unchanged copy of the source.",
"INVALID_CONTENT": "Return a complete, nonempty answer, not an error message.",
}
def input_fingerprint(capability, payload):
data = json.dumps({"capability": capability, "payload": payload}, ensure_ascii=False,
sort_keys=True, separators=(",", ":"), allow_nan=False)
return hashlib.sha256(data.encode("utf-8")).hexdigest()
@dataclass(frozen=True)
class Plan:
capability: str
target_language: str
target_dialect: str
max_attempts: int
class Coordinator:
def plan(self, capability, payload, max_steps):
if capability not in CAPABILITIES or max_steps < 3:
raise ValueError("This workflow needs at least three bounded agent steps.")
clean_label(payload["source_language"])
clean_label(payload["source_dialect"])
language, dialect = (("English", "Standard English") if capability == "interpret.compat.v1" else
(clean_label(payload["target_language"]), clean_label(payload["target_dialect"])))
return Plan(capability, language, dialect, min(2, (max_steps - 1) // 2))
class Interpreter:
def generate(self, provider, plan, payload, feedback):
# Feedback comes only from the fixed critic codebook, never arbitrary tools/instructions.
return provider(plan.capability, payload, tuple(feedback))
class Critic:
"""Conservative technical checks, not a semantic/empathy ground-truth judge."""
def review(self, plan, payload, candidate):
issues, warnings = [], []
text = candidate.get("text", "")
if not isinstance(text, str):
text = ""
if not valid_content(text):
issues.append("INVALID_CONTENT")
elif not script_valid(text, plan.target_language, plan.target_dialect):
issues.append("TARGET_SCRIPT_MISMATCH")
if plan.capability == "translate.v1" and payload["source_language"].casefold() != plan.target_language.casefold() \
and text.strip().casefold() == payload["text"].strip().casefold():
issues.append("UNTRANSLATED_SOURCE_COPY")
# A number can be legitimately rendered as a word or in another numeral system.
# Flag changed digit strings for human review, not an automatic semantic rejection.
if plan.capability != "reply.v1" and re.findall(r"\d+(?:[.,:]\d+)*", payload["text"]) != re.findall(r"\d+(?:[.,:]\d+)*", text):
warnings.append("NUMERIC_RENDERING_NEEDS_HUMAN_REVIEW")
return {"decision": "repair" if issues else "pass_for_human_review", "issues": issues,
"warnings": warnings, "confidence": None, "semantic_accuracy_verified": False}
def run_workflow(capability, payload, *, raw_payload, max_steps, deadline, cancelled, provider):
def checkpoint():
if cancelled.is_set() or time.monotonic() >= deadline:
raise TimeoutError("The request ended before workflow completion.")
checkpoint()
started = time.monotonic()
plan = Coordinator().plan(capability, payload, max_steps)
trace = [{"agent": "coordinator", "action": "plan", "attempt_limit": plan.max_attempts,
"duration_ms": round((time.monotonic() - started) * 1000)}]
feedback = ()
last_candidate = None
verdict = None
for attempt in range(1, plan.max_attempts + 1):
checkpoint()
started = time.monotonic()
candidate = Interpreter().generate(provider, plan, payload, feedback)
checkpoint()
trace.append({"agent": "interpreter", "action": "generate", "attempt": attempt,
"duration_ms": round((time.monotonic() - started) * 1000)})
if not isinstance(candidate, dict) or candidate.get("ok") is not True:
code = candidate.get("error", {}).get("code") if isinstance(candidate, dict) and isinstance(candidate.get("error"), dict) else None
allowed = {"MODEL_UNAVAILABLE", "PROVIDER_UNAVAILABLE", "PROVIDER_AUTH_FAILED", "PROVIDER_ACCESS_DENIED", "PROVIDER_RATE_LIMITED", "PROVIDER_CONFIGURATION_ERROR", "PROVIDER_BUDGET_EXHAUSTED", "LANGUAGE_MISMATCH", "OUTPUT_TRUNCATED", "INVALID_OUTPUT", "INVALID_REQUEST"}
return {"ok": False, "error": {"code": code if code in allowed else "PROVIDER_UNAVAILABLE"}}
if not all(isinstance(candidate.get(field), str) and candidate[field].strip() for field in ("model", "route")):
return {"ok": False, "error": {"code": "INVALID_PROVIDER_PROVENANCE"}}
last_candidate = candidate
started = time.monotonic()
verdict = Critic().review(plan, payload, candidate)
trace.append({"agent": "critic", "action": verdict["decision"], "attempt": attempt,
"issues": verdict["issues"], "warnings": verdict["warnings"],
"duration_ms": round((time.monotonic() - started) * 1000)})
if verdict["decision"] == "pass_for_human_review":
break
feedback = tuple(verdict["issues"])
checkpoint()
workflow = {"version": VERSION, "mode": MODE, "policy": POLICY,
"input_sha256": input_fingerprint(capability, raw_payload), "steps": trace, "step_count": len(trace),
"attempts": attempt, "critic": verdict, "human_review_required": True,
"persistence": "request-scoped", "durable_replay": False}
if verdict["decision"] != "pass_for_human_review":
return {"ok": False, "escalated": True, "workflow": workflow,
"error": {"code": "HUMAN_REVIEW_REQUIRED", "message": "Edit the transcript or context and regenerate; the output did not pass technical checks."}}
return {**last_candidate, "workflow": workflow}
|