Spaces:
Sleeping
Sleeping
Download src/hf_agent_workflow.py from toecm/PureVersation: direct link, hf CLI and curl.
- Browser
- Download file 6.27 kB
-
https://huggingface.co/spaces/toecm/PureVersation/resolve/main/src/hf_agent_workflow.py
- Command line
-
hf download hf://spaces/toecm/PureVersation/src/hf_agent_workflow.py
-
curl -L -o hf_agent_workflow.py https://huggingface.co/spaces/toecm/PureVersation/resolve/main/src/hf_agent_workflow.py
6.27 kB
| """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() | |
| 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} | |