Spaces:
Sleeping
Sleeping
File size: 15,593 Bytes
e5e36db | 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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 | """
explainability.py
=================
Structured reasoning objects and template-based explanation generation.
No API calls β fully deterministic. The explanation is built from the
agent's actual reasoning trace (claims verified, sources checked, decision)
so it aligns with every moderation decision and is auditable.
Enterprise platforms (Meta, Instagram, etc.) can:
- Replace `generate_explanation` with a call to their internal LLM
- Feed `ReasoningObject` into dashboards / audit logs
- Extend `DECISION_TEMPLATES` without touching engine code
"""
from __future__ import annotations
import os
import textwrap
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
import yaml
EXPLANATION_CONFIG_PATH = os.getenv("EXPLANATION_CONFIG", "explanation_templates.yaml")
# ---------------------------------------------------------------------------
# Structured reasoning object (what the agent built up during the episode)
# ---------------------------------------------------------------------------
@dataclass
class SourceEvidence:
source_id: str
title: str
stance: str # supporting | contradicting | neutral
reliability: float
key_snippet: str = ""
@dataclass
class ClaimAssessment:
claim_id: str
claim_text: str
verification_status: str # true | false | partially_true | unknown
confidence: float
supporting_sources: List[str] = field(default_factory=list)
contradicting_sources: List[str] = field(default_factory=list)
@dataclass
class ReasoningObject:
"""
Complete structured reasoning trace for one episode.
Produced by the agent or inference script; consumed by the explainer.
"""
content_summary: str
claims: List[ClaimAssessment]
sources_used: List[SourceEvidence]
decision: str # allow | flag | remove
confidence: float # 0β1
step_count: int
episode_id: str = ""
difficulty: str = ""
extra: Dict[str, Any] = field(default_factory=dict)
# Derived helpers
@property
def contradicting_sources(self) -> List[SourceEvidence]:
return [s for s in self.sources_used if s.stance == "contradicting"]
@property
def supporting_sources(self) -> List[SourceEvidence]:
return [s for s in self.sources_used if s.stance == "supporting"]
@property
def high_reliability_sources(self) -> List[SourceEvidence]:
return [s for s in self.sources_used if s.reliability >= 0.80]
@property
def false_claims(self) -> List[ClaimAssessment]:
return [c for c in self.claims if c.verification_status in ("false", "partially_true")]
@property
def verified_fraction(self) -> float:
if not self.claims:
return 0.0
verified = sum(
1 for c in self.claims
if c.verification_status != "unknown"
)
return verified / len(self.claims)
# ---------------------------------------------------------------------------
# Template engine
# ---------------------------------------------------------------------------
# Built-in templates β can be fully overridden by explanation_templates.yaml
_BUILTIN_TEMPLATES: Dict[str, str] = {
"remove": textwrap.dedent("""\
MODERATION DECISION: REMOVE
Content summary: {content_summary}
After examining {n_claims} claim(s) across {n_sources} source(s):
{claim_assessments}
KEY EVIDENCE
{evidence_list}
REASONING
{reasoning_narrative}
CONCLUSION
The content was removed because {removal_reason}.
Confidence: {confidence_pct}%. Sources consulted: {n_sources}.
"""),
"flag": textwrap.dedent("""\
MODERATION DECISION: FLAG FOR REVIEW
Content summary: {content_summary}
After examining {n_claims} claim(s) across {n_sources} source(s):
{claim_assessments}
KEY EVIDENCE
{evidence_list}
REASONING
{reasoning_narrative}
CONCLUSION
The content was flagged because {flag_reason}.
Confidence: {confidence_pct}%. Sources consulted: {n_sources}.
"""),
"allow": textwrap.dedent("""\
MODERATION DECISION: ALLOW
Content summary: {content_summary}
After examining {n_claims} claim(s) across {n_sources} source(s):
{claim_assessments}
KEY EVIDENCE
{evidence_list}
REASONING
{reasoning_narrative}
CONCLUSION
The content was allowed because {allow_reason}.
Confidence: {confidence_pct}%. Sources consulted: {n_sources}.
"""),
}
class ExplanationTemplates:
"""Loads templates from YAML; falls back to built-ins."""
def __init__(self, path: str = EXPLANATION_CONFIG_PATH) -> None:
self._templates = dict(_BUILTIN_TEMPLATES)
if os.path.exists(path):
with open(path, "r", encoding="utf-8") as fh:
loaded = yaml.safe_load(fh) or {}
self._templates.update(loaded.get("templates", {}))
def get(self, decision: str) -> str:
return self._templates.get(decision, self._templates["flag"])
# ---------------------------------------------------------------------------
# Explainability engine
# ---------------------------------------------------------------------------
class ExplainabilityEngine:
"""
Converts a ReasoningObject into a structured, human-readable explanation.
No ML or API calls. All text is derived deterministically from the
agent's actual evidence trace.
"""
def __init__(self, templates: Optional[ExplanationTemplates] = None) -> None:
self._tpl = templates or ExplanationTemplates()
def generate_explanation(self, reasoning: ReasoningObject) -> str:
"""Return a formatted explanation string."""
template = self._tpl.get(reasoning.decision)
variables = self._build_variables(reasoning)
try:
return template.format(**variables)
except KeyError as exc:
# Graceful fallback β missing template var
return self._fallback(reasoning) + f"\n[template key missing: {exc}]"
def generate_structured(self, reasoning: ReasoningObject) -> dict:
"""Return a machine-readable structured explanation for API responses."""
return {
"decision": reasoning.decision,
"confidence": round(reasoning.confidence, 3),
"content_summary": reasoning.content_summary,
"claims_assessed": [
{
"id": c.claim_id,
"text": c.claim_text,
"status": c.verification_status,
"conf": round(c.confidence, 3),
}
for c in reasoning.claims
],
"sources_used": [
{
"id": s.source_id,
"title": s.title,
"stance": s.stance,
"reliability": round(s.reliability, 3),
}
for s in reasoning.sources_used
],
"evidence_summary": {
"contradicting": len(reasoning.contradicting_sources),
"supporting": len(reasoning.supporting_sources),
"high_reliability": len(reasoning.high_reliability_sources),
},
"narrative": self.generate_explanation(reasoning),
"steps_taken": reasoning.step_count,
"episode_id": reasoning.episode_id,
}
# ------------------------------------------------------------------
# Template variable builder
# ------------------------------------------------------------------
def _build_variables(self, r: ReasoningObject) -> dict:
return {
"content_summary": r.content_summary or "(no summary)",
"n_claims": len(r.claims),
"n_sources": len(r.sources_used),
"confidence_pct": int(r.confidence * 100),
"claim_assessments": self._format_claims(r.claims),
"evidence_list": self._format_evidence(r.sources_used),
"reasoning_narrative":self._narrative(r),
"removal_reason": self._removal_reason(r),
"flag_reason": self._flag_reason(r),
"allow_reason": self._allow_reason(r),
}
@staticmethod
def _format_claims(claims: List[ClaimAssessment]) -> str:
if not claims:
return " (no claims assessed)"
lines = []
for c in claims:
status_icon = {
"true": "[TRUE]",
"false": "[FALSE]",
"partially_true": "[PARTIAL]",
"unknown": "[UNKNOWN]",
"unverified": "[NOT VERIFIED]",
}.get(c.verification_status, "[?]")
lines.append(
f" {status_icon} Claim: {c.claim_text}\n"
f" Status: {c.verification_status} "
f"(confidence {int(c.confidence * 100)}%)"
)
return "\n".join(lines)
@staticmethod
def _format_evidence(sources: List[SourceEvidence]) -> str:
if not sources:
return " (no sources checked)"
lines = []
for s in sorted(sources, key=lambda x: -x.reliability):
icon = {"contradicting": "β", "supporting": "β", "neutral": "Β·"}.get(
s.stance, "Β·"
)
rel_bar = "β" * int(s.reliability * 10) + "β" * (10 - int(s.reliability * 10))
snippet = (s.key_snippet[:100] + "β¦") if len(s.key_snippet) > 100 else s.key_snippet
lines.append(
f" {icon} [{s.stance.upper():<14}] rel={rel_bar} ({s.reliability:.2f})\n"
f" {s.title}\n"
+ (f" \"{snippet}\"" if snippet else "")
)
return "\n".join(lines)
def _narrative(self, r: ReasoningObject) -> str:
parts = []
n_false = len(r.false_claims)
n_total = len(r.claims)
parts.append(
f"{n_false} of {n_total} claim(s) were found to be false or partially false."
)
if r.contradicting_sources:
top = max(r.contradicting_sources, key=lambda s: s.reliability)
parts.append(
f"The strongest contradicting source was '{top.title}' "
f"(reliability {top.reliability:.2f}), which "
f"directly contradicts the claims made in the content."
)
if r.supporting_sources:
top = max(r.supporting_sources, key=lambda s: s.reliability)
parts.append(
f"One supporting source was found: '{top.title}' "
f"(reliability {top.reliability:.2f})."
)
else:
parts.append("No credible supporting sources were identified.")
if r.high_reliability_sources:
names = ", ".join(
f"'{s.title[:40]}'" for s in r.high_reliability_sources[:3]
)
parts.append(
f"High-reliability sources consulted: {names}."
)
parts.append(
f"The agent took {r.step_count} reasoning step(s) "
f"and verified {int(r.verified_fraction * 100)}% of claims before deciding."
)
return " " + "\n ".join(parts)
@staticmethod
def _removal_reason(r: ReasoningObject) -> str:
false_count = len(r.false_claims)
hi_rel = len(r.high_reliability_sources)
if false_count:
claim_texts = "; ".join(
f"'{c.claim_text[:50]}'" for c in r.false_claims[:2]
)
return (
f"{false_count} claim(s) were definitively false according to "
f"{hi_rel} high-reliability source(s), including: {claim_texts}"
)
return "overwhelming contradicting evidence from authoritative sources was found"
@staticmethod
def _flag_reason(r: ReasoningObject) -> str:
n_contra = len(r.contradicting_sources)
n_support = len(r.supporting_sources)
if n_contra > 0 and n_support > 0:
return (
f"evidence was mixed ({n_contra} contradicting, {n_support} supporting), "
"requiring human review to determine context and intent"
)
if n_contra > 0:
return (
f"{n_contra} contradicting source(s) were found but evidence is "
"insufficient for removal; human review is recommended"
)
return "the claim could not be fully verified with available sources"
@staticmethod
def _allow_reason(r: ReasoningObject) -> str:
n_support = len(r.supporting_sources)
hi_rel = len(r.high_reliability_sources)
return (
f"{n_support} supporting source(s) (including {hi_rel} high-reliability) "
"corroborate the claims and no significant contradicting evidence was found"
)
@staticmethod
def _fallback(r: ReasoningObject) -> str:
return (
f"MODERATION DECISION: {r.decision.upper()}\n"
f"Content: {r.content_summary}\n"
f"Claims verified: {len(r.claims)}. Sources checked: {len(r.sources_used)}.\n"
f"Decision confidence: {int(r.confidence * 100)}%."
)
# ---------------------------------------------------------------------------
# Factory helper used by inference.py and server.py
# ---------------------------------------------------------------------------
def build_reasoning_from_episode(
obs, # Final Observation object
decision: str,
episode_id: str = "",
difficulty: str = "",
) -> ReasoningObject:
"""
Convenience builder: converts a final Observation into a ReasoningObject.
Compatible with any agent that used verify_claim + check_source + decide.
"""
# Collect checked sources from interaction history
checked_source_ids = {
r.action_payload.get("source_id")
for r in obs.interaction_history
if r.action_type == "check_source"
}
sources_used = [
SourceEvidence(
source_id=s.id,
title=s.title,
stance=s.stance if isinstance(s.stance, str) else s.stance.value,
reliability=s.reliability,
key_snippet=s.text[:200],
)
for s in obs.available_sources
if s.id in checked_source_ids
]
claims_assessed = [
ClaimAssessment(
claim_id=c.id,
claim_text=c.text,
verification_status=(
c.verification_status
if isinstance(c.verification_status, str)
else c.verification_status.value
),
confidence=c.confidence,
)
for c in obs.claims
]
# Confidence = mean reliability of checked sources (or 0.5 fallback)
confidence = (
sum(s.reliability for s in sources_used) / len(sources_used)
if sources_used else 0.5
)
return ReasoningObject(
content_summary=obs.content[:200],
claims=claims_assessed,
sources_used=sources_used,
decision=decision,
confidence=confidence,
step_count=obs.step_count,
episode_id=episode_id,
difficulty=difficulty,
)
|