Download src/guardrails/self_reflective_loop.py from agenthinkmesh/manara: direct link, hf CLI and curl.
- Browser
- Download file 23.4 kB
-
https://huggingface.co/agenthinkmesh/manara/resolve/main/src/guardrails/self_reflective_loop.py
- Command line
-
hf download hf://agenthinkmesh/manara/src/guardrails/self_reflective_loop.py
-
curl -L -o self_reflective_loop.py https://huggingface.co/agenthinkmesh/manara/resolve/main/src/guardrails/self_reflective_loop.py
23.4 kB
| #!/usr/bin/env python3 | |
| # -*- coding: utf-8 -*- | |
| """ | |
| ============================================================================== | |
| Manara-3B | Step 3: Self-Reflective Guardrail Engine | |
| ============================================================================== | |
| Role : Senior AI Researcher & FinTech Engineer | |
| Project : Manara-3B — Sovereign SLM for Kuwaiti Banking Sector | |
| Author : Manus AI | |
| Version : 1.0.0 | |
| ============================================================================== | |
| This module implements the "Self-Reflective Loop" for Manara-3B. After the | |
| model generates a primary response, this engine runs a second "Critic Pass" | |
| to verify compliance with 12 internal domain guardrails. | |
| The 12 Guardrails: | |
| G-01 No Riba (Interest) Statements | |
| G-02 CBK Regulatory Accuracy | |
| G-03 Sharia Compliance Verification | |
| G-04 Boursa Kuwait Disclosure Standards | |
| G-05 No Fabricated Regulatory Citations | |
| G-06 No Harmful Financial Advice | |
| G-07 Currency & Jurisdiction Accuracy (KWD / Kuwait) | |
| G-08 AAOIFI Standard Alignment | |
| G-09 No Discriminatory Content | |
| G-10 Data Privacy & Confidentiality | |
| G-11 Kuwaiti Dialect & Register Appropriateness | |
| G-12 Factual Consistency & Internal Coherence | |
| All self-correction events are logged to a JSONL file for recursive retraining. | |
| Usage: | |
| from self_reflective_loop import ManaraGuardrailEngine | |
| engine = ManaraGuardrailEngine() | |
| result = engine.check(response_text, language="ar") | |
| ============================================================================== | |
| """ | |
| import os | |
| import re | |
| import json | |
| import logging | |
| from datetime import datetime | |
| from pathlib import Path | |
| from typing import Optional | |
| logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s") | |
| logger = logging.getLogger(__name__) | |
| # --------------------------------------------------------------------------- | |
| # Guardrail Definitions | |
| # --------------------------------------------------------------------------- | |
| # G-01: Riba (Interest) — Forbidden in Islamic finance | |
| RIBA_KEYWORDS_AR = [ | |
| "فائدة", "فوائد", "ربا", "سعر الفائدة", "فائدة مركبة", | |
| "عائد الفائدة", "فائدة بسيطة", "قرض بفائدة", | |
| ] | |
| RIBA_KEYWORDS_EN = [ | |
| "interest rate", "compound interest", "simple interest", | |
| "interest-bearing", "usury", "riba", "interest payment", | |
| ] | |
| # G-02: CBK Regulatory Accuracy — Detect hallucinated article numbers | |
| CBK_HALLUCINATION_PATTERNS = [ | |
| r"المادة\s+\d{3,}", # Article numbers > 99 (likely hallucinated) | |
| r"تعميم رقم\s+\d{5,}", # Circular numbers > 9999 (likely hallucinated) | |
| r"CBK Circular No\.\s+\d{5,}", | |
| r"Article\s+\d{3,}\s+of\s+the\s+CBK", | |
| ] | |
| # G-05: Fabricated citations — Common hallucination patterns | |
| FABRICATED_CITATION_PATTERNS = [ | |
| r"وفق المادة \d+ من قانون \d{4}", | |
| r"بموجب المرسوم رقم \d{5,}", | |
| r"per CBK Regulation \d{4}-\d{3}", | |
| r"Basel IV Article \d+", # Basel IV does not exist | |
| ] | |
| # G-06: Harmful financial advice patterns | |
| HARMFUL_ADVICE_PATTERNS_AR = [ | |
| "استثمر كل أموالك في", "ضمان ربح", "لا خسارة", "عائد مضمون", | |
| "يضمن ربح", "يضمن عائد", "مضمون الربح", | |
| "تهرب ضريبي", "إخفاء الأصول", | |
| ] | |
| HARMFUL_ADVICE_PATTERNS_EN = [ | |
| "guaranteed profit", "no risk investment", "invest all your money in", | |
| "tax evasion", "hide assets", "guaranteed return", | |
| ] | |
| # G-09: Discriminatory content patterns | |
| DISCRIMINATORY_PATTERNS = [ | |
| r"\b(نساء|رجال)\s+لا\s+يستطيعون", | |
| r"\b(women|men)\s+cannot\s+(open|access|apply)", | |
| r"based on (religion|nationality|gender)\s+are\s+(not|excluded)", | |
| ] | |
| # G-10: Data privacy — Detect if response contains what looks like real PII | |
| PII_PATTERNS = [ | |
| r"\b\d{12}\b", # Kuwaiti Civil ID (12 digits) | |
| r"\b[A-Z]{2}\d{6}[A-Z]\b", # Passport number pattern | |
| r"\b\d{4}[\s-]\d{4}[\s-]\d{4}[\s-]\d{4}\b", # Credit card number | |
| r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b", # Email | |
| ] | |
| # --------------------------------------------------------------------------- | |
| # Individual Guardrail Checkers | |
| # --------------------------------------------------------------------------- | |
| class GuardrailViolation: | |
| """Represents a single guardrail violation.""" | |
| def __init__(self, guardrail_id: str, guardrail_name: str, severity: str, | |
| description: str, evidence: Optional[str] = None): | |
| self.guardrail_id = guardrail_id | |
| self.guardrail_name = guardrail_name | |
| self.severity = severity # "critical", "warning", "info" | |
| self.description = description | |
| self.evidence = evidence | |
| def to_dict(self) -> dict: | |
| return { | |
| "guardrail_id": self.guardrail_id, | |
| "guardrail_name": self.guardrail_name, | |
| "severity": self.severity, | |
| "description": self.description, | |
| "evidence": self.evidence, | |
| } | |
| def check_g01_no_riba(text: str, language: str) -> Optional[GuardrailViolation]: | |
| """G-01: Detects statements that promote or normalize interest (Riba).""" | |
| keywords = RIBA_KEYWORDS_AR if language == "ar" else RIBA_KEYWORDS_EN | |
| for keyword in keywords: | |
| if keyword.lower() in text.lower(): | |
| # Check context — "riba is forbidden" is acceptable | |
| context_ok_patterns = [ | |
| "محظور", "محرم", "لا يجوز", "forbidden", "prohibited", "not allowed", | |
| "avoid", "تجنب", "بديل", | |
| ] | |
| is_contextually_ok = any(p in text.lower() for p in context_ok_patterns) | |
| if not is_contextually_ok: | |
| return GuardrailViolation( | |
| guardrail_id="G-01", | |
| guardrail_name="No Riba (Interest) Statements", | |
| severity="critical", | |
| description="Response contains interest-related terminology without prohibitory context.", | |
| evidence=keyword, | |
| ) | |
| return None | |
| def check_g02_cbk_accuracy(text: str) -> Optional[GuardrailViolation]: | |
| """G-02: Detects potentially hallucinated CBK article numbers.""" | |
| for pattern in CBK_HALLUCINATION_PATTERNS: | |
| match = re.search(pattern, text) | |
| if match: | |
| return GuardrailViolation( | |
| guardrail_id="G-02", | |
| guardrail_name="CBK Regulatory Accuracy", | |
| severity="warning", | |
| description="Response contains potentially hallucinated regulatory citation.", | |
| evidence=match.group(0), | |
| ) | |
| return None | |
| def check_g03_sharia_compliance(text: str, language: str) -> Optional[GuardrailViolation]: | |
| """G-03: Verifies that Sharia-compliant instruments are described correctly.""" | |
| # Check for incorrect Murabaha description (must not mention interest) | |
| murabaha_keywords = ["مرابحة", "murabaha"] | |
| for kw in murabaha_keywords: | |
| if kw.lower() in text.lower(): | |
| # Murabaha should never be described as "interest-based" | |
| incorrect_patterns = ["interest-based murabaha", "مرابحة بفائدة"] | |
| for pat in incorrect_patterns: | |
| if pat.lower() in text.lower(): | |
| return GuardrailViolation( | |
| guardrail_id="G-03", | |
| guardrail_name="Sharia Compliance Verification", | |
| severity="critical", | |
| description="Murabaha incorrectly described as interest-based.", | |
| evidence=pat, | |
| ) | |
| return None | |
| def check_g04_boursa_standards(text: str) -> Optional[GuardrailViolation]: | |
| """G-04: Checks that Boursa Kuwait disclosures are described accurately.""" | |
| # Detect incorrect claim that ESG reporting is mandatory for all companies | |
| # (as of 2026, it is mandatory only for Premier Market companies) | |
| incorrect_claims = [ | |
| "all listed companies must submit ESG", | |
| "جميع الشركات المدرجة ملزمة بتقرير ESG", | |
| ] | |
| for claim in incorrect_claims: | |
| if claim.lower() in text.lower(): | |
| return GuardrailViolation( | |
| guardrail_id="G-04", | |
| guardrail_name="Boursa Kuwait Disclosure Standards", | |
| severity="warning", | |
| description="Incorrect claim about mandatory ESG reporting scope.", | |
| evidence=claim, | |
| ) | |
| return None | |
| def check_g05_no_fabricated_citations(text: str) -> Optional[GuardrailViolation]: | |
| """G-05: Detects fabricated regulatory citations.""" | |
| for pattern in FABRICATED_CITATION_PATTERNS: | |
| match = re.search(pattern, text, re.IGNORECASE) | |
| if match: | |
| return GuardrailViolation( | |
| guardrail_id="G-05", | |
| guardrail_name="No Fabricated Regulatory Citations", | |
| severity="critical", | |
| description="Response contains a potentially fabricated regulatory citation.", | |
| evidence=match.group(0), | |
| ) | |
| return None | |
| def check_g06_no_harmful_advice(text: str, language: str) -> Optional[GuardrailViolation]: | |
| """G-06: Detects harmful or irresponsible financial advice.""" | |
| patterns = HARMFUL_ADVICE_PATTERNS_AR if language == "ar" else HARMFUL_ADVICE_PATTERNS_EN | |
| for pattern in patterns: | |
| if pattern.lower() in text.lower(): | |
| return GuardrailViolation( | |
| guardrail_id="G-06", | |
| guardrail_name="No Harmful Financial Advice", | |
| severity="critical", | |
| description="Response contains potentially harmful financial advice.", | |
| evidence=pattern, | |
| ) | |
| return None | |
| def check_g07_currency_jurisdiction(text: str) -> Optional[GuardrailViolation]: | |
| """G-07: Checks for incorrect currency or jurisdiction references.""" | |
| # Detect if response uses SAR/AED/USD as primary currency for Kuwait context | |
| incorrect_currency_patterns = [ | |
| r"\bSAR\s+\d+", # Saudi Riyal in Kuwait context | |
| r"\bAED\s+\d+", # UAE Dirham in Kuwait context | |
| r"الريال السعودي", | |
| r"الدرهم الإماراتي", | |
| ] | |
| for pattern in incorrect_currency_patterns: | |
| match = re.search(pattern, text) | |
| if match: | |
| return GuardrailViolation( | |
| guardrail_id="G-07", | |
| guardrail_name="Currency & Jurisdiction Accuracy", | |
| severity="warning", | |
| description="Response uses incorrect currency for Kuwait context (expected KWD).", | |
| evidence=match.group(0), | |
| ) | |
| return None | |
| def check_g08_aaoifi_alignment(text: str) -> Optional[GuardrailViolation]: | |
| """G-08: Checks for incorrect AAOIFI standard references.""" | |
| # Detect incorrect AAOIFI standard numbers (valid range: FAS 1-FAS 45, SS 1-SS 59) | |
| aaoifi_pattern = r"AAOIFI\s+(FAS|SS)\s+(\d+)" | |
| for match in re.finditer(aaoifi_pattern, text, re.IGNORECASE): | |
| standard_type = match.group(1).upper() | |
| standard_num = int(match.group(2)) | |
| if standard_type == "FAS" and standard_num > 45: | |
| return GuardrailViolation( | |
| guardrail_id="G-08", | |
| guardrail_name="AAOIFI Standard Alignment", | |
| severity="warning", | |
| description=f"AAOIFI FAS {standard_num} does not exist (max is FAS 45).", | |
| evidence=match.group(0), | |
| ) | |
| if standard_type == "SS" and standard_num > 59: | |
| return GuardrailViolation( | |
| guardrail_id="G-08", | |
| guardrail_name="AAOIFI Standard Alignment", | |
| severity="warning", | |
| description=f"AAOIFI SS {standard_num} does not exist (max is SS 59).", | |
| evidence=match.group(0), | |
| ) | |
| return None | |
| def check_g09_no_discrimination(text: str) -> Optional[GuardrailViolation]: | |
| """G-09: Detects discriminatory content.""" | |
| for pattern in DISCRIMINATORY_PATTERNS: | |
| match = re.search(pattern, text, re.IGNORECASE) | |
| if match: | |
| return GuardrailViolation( | |
| guardrail_id="G-09", | |
| guardrail_name="No Discriminatory Content", | |
| severity="critical", | |
| description="Response contains potentially discriminatory language.", | |
| evidence=match.group(0), | |
| ) | |
| return None | |
| def check_g10_data_privacy(text: str) -> Optional[GuardrailViolation]: | |
| """G-10: Detects potential PII in the response.""" | |
| for pattern in PII_PATTERNS: | |
| match = re.search(pattern, text) | |
| if match: | |
| return GuardrailViolation( | |
| guardrail_id="G-10", | |
| guardrail_name="Data Privacy & Confidentiality", | |
| severity="critical", | |
| description="Response contains potential personally identifiable information (PII).", | |
| evidence="[REDACTED]", # Do not log actual PII | |
| ) | |
| return None | |
| def check_g11_language_register(text: str, language: str) -> Optional[GuardrailViolation]: | |
| """G-11: Checks for inappropriate language register in Arabic responses.""" | |
| if language != "ar": | |
| return None | |
| # Detect overly colloquial terms that are inappropriate for banking context | |
| colloquial_terms = ["شلون", "وين", "ليش", "هاي", "ذيج", "چذي"] | |
| for term in colloquial_terms: | |
| if term in text: | |
| return GuardrailViolation( | |
| guardrail_id="G-11", | |
| guardrail_name="Kuwaiti Dialect & Register Appropriateness", | |
| severity="info", | |
| description="Response uses colloquial dialect terms inappropriate for formal banking context.", | |
| evidence=term, | |
| ) | |
| return None | |
| def check_g12_factual_consistency(text: str) -> Optional[GuardrailViolation]: | |
| """G-12: Checks for basic internal factual inconsistencies.""" | |
| # Example: Response claims both "mandatory" and "voluntary" for the same item | |
| contradiction_pairs = [ | |
| ("إلزامي", "اختياري"), | |
| ("mandatory", "voluntary"), | |
| ("required", "optional"), | |
| ] | |
| for pos, neg in contradiction_pairs: | |
| if pos.lower() in text.lower() and neg.lower() in text.lower(): | |
| # Only flag if they appear close together (within 200 chars) | |
| pos_idx = text.lower().find(pos.lower()) | |
| neg_idx = text.lower().find(neg.lower()) | |
| if abs(pos_idx - neg_idx) < 200: | |
| return GuardrailViolation( | |
| guardrail_id="G-12", | |
| guardrail_name="Factual Consistency & Internal Coherence", | |
| severity="warning", | |
| description="Response contains potentially contradictory statements.", | |
| evidence=f"'{pos}' and '{neg}' used in close proximity.", | |
| ) | |
| return None | |
| # --------------------------------------------------------------------------- | |
| # Main Guardrail Engine | |
| # --------------------------------------------------------------------------- | |
| class ManaraGuardrailEngine: | |
| """ | |
| The Manara-3B Self-Reflective Guardrail Engine. | |
| Runs all 12 domain guardrails against a generated response and logs | |
| any violations for recursive retraining. | |
| """ | |
| GUARDRAIL_CHECKERS = [ | |
| ("G-01", check_g01_no_riba), | |
| ("G-02", check_g02_cbk_accuracy), | |
| ("G-03", check_g03_sharia_compliance), | |
| ("G-04", check_g04_boursa_standards), | |
| ("G-05", check_g05_no_fabricated_citations), | |
| ("G-06", check_g06_no_harmful_advice), | |
| ("G-07", check_g07_currency_jurisdiction), | |
| ("G-08", check_g08_aaoifi_alignment), | |
| ("G-09", check_g09_no_discrimination), | |
| ("G-10", check_g10_data_privacy), | |
| ("G-11", check_g11_language_register), | |
| ("G-12", check_g12_factual_consistency), | |
| ] | |
| def __init__(self, log_dir: str = "../../logs"): | |
| self.log_dir = Path(log_dir) | |
| self.log_dir.mkdir(parents=True, exist_ok=True) | |
| self.correction_log_path = self.log_dir / "self_corrections.jsonl" | |
| self.stats = { | |
| "total_checked": 0, | |
| "total_passed": 0, | |
| "total_failed": 0, | |
| "violations_by_guardrail": {f"G-{i:02d}": 0 for i in range(1, 13)}, | |
| } | |
| logger.info(f"ManaraGuardrailEngine initialized. Log: {self.correction_log_path}") | |
| def check(self, response: str, language: str = "ar", context: Optional[dict] = None) -> dict: | |
| """ | |
| Runs all 12 guardrails against the given response. | |
| Args: | |
| response : The model-generated response text. | |
| language : Language of the response ("ar" or "en"). | |
| context : Optional dict with additional context (e.g., original prompt). | |
| Returns: | |
| A dict with: | |
| - 'passed': bool — True if all critical guardrails passed. | |
| - 'violations': list of violation dicts. | |
| - 'severity_summary': count of violations by severity. | |
| """ | |
| self.stats["total_checked"] += 1 | |
| violations = [] | |
| # Run all guardrail checkers | |
| for guardrail_id, checker_fn in self.GUARDRAIL_CHECKERS: | |
| try: | |
| # Some checkers take language, some don't | |
| import inspect | |
| sig = inspect.signature(checker_fn) | |
| if "language" in sig.parameters: | |
| violation = checker_fn(response, language) | |
| else: | |
| violation = checker_fn(response) | |
| if violation: | |
| violations.append(violation) | |
| self.stats["violations_by_guardrail"][guardrail_id] += 1 | |
| except Exception as e: | |
| logger.error(f"Error in guardrail {guardrail_id}: {e}") | |
| # Determine pass/fail based on critical violations | |
| critical_violations = [v for v in violations if v.severity == "critical"] | |
| passed = len(critical_violations) == 0 | |
| if passed: | |
| self.stats["total_passed"] += 1 | |
| else: | |
| self.stats["total_failed"] += 1 | |
| result = { | |
| "passed": passed, | |
| "violations": [v.to_dict() for v in violations], | |
| "severity_summary": { | |
| "critical": len(critical_violations), | |
| "warning": len([v for v in violations if v.severity == "warning"]), | |
| "info": len([v for v in violations if v.severity == "info"]), | |
| }, | |
| } | |
| # Log self-correction event if violations found | |
| if violations: | |
| self._log_correction_event(response, language, result, context) | |
| return result | |
| def _log_correction_event( | |
| self, | |
| response: str, | |
| language: str, | |
| check_result: dict, | |
| context: Optional[dict] = None, | |
| ): | |
| """Logs a self-correction event to the JSONL correction log.""" | |
| log_entry = { | |
| "timestamp": datetime.utcnow().isoformat(), | |
| "language": language, | |
| "response_preview": response[:500] + "..." if len(response) > 500 else response, | |
| "passed": check_result["passed"], | |
| "severity_summary": check_result["severity_summary"], | |
| "violations": check_result["violations"], | |
| "context": context or {}, | |
| } | |
| with open(self.correction_log_path, "a", encoding="utf-8") as f: | |
| f.write(json.dumps(log_entry, ensure_ascii=False) + "\n") | |
| logger.info( | |
| f"Self-correction logged: {len(check_result['violations'])} violation(s) " | |
| f"[critical={check_result['severity_summary']['critical']}]" | |
| ) | |
| def get_stats(self) -> dict: | |
| """Returns the current guardrail engine statistics.""" | |
| return self.stats | |
| def save_stats(self): | |
| """Saves guardrail statistics to a JSON file.""" | |
| stats_path = self.log_dir / "guardrail_stats.json" | |
| with open(stats_path, "w", encoding="utf-8") as f: | |
| json.dump(self.stats, f, indent=2, ensure_ascii=False) | |
| logger.info(f"Guardrail stats saved: {stats_path}") | |
| def generate_retraining_dataset(self, output_file: str) -> int: | |
| """ | |
| Generates a retraining dataset from logged self-correction events. | |
| This dataset can be used for recursive fine-tuning to improve compliance. | |
| Returns the number of retraining samples generated. | |
| """ | |
| if not self.correction_log_path.exists(): | |
| logger.warning("No correction log found. No retraining data generated.") | |
| return 0 | |
| retraining_samples = [] | |
| with open(self.correction_log_path, "r", encoding="utf-8") as f: | |
| for line in f: | |
| entry = json.loads(line.strip()) | |
| if not entry.get("passed") and entry.get("violations"): | |
| # Create a retraining sample: the original response + correction instructions | |
| violations_desc = "; ".join( | |
| [f"{v['guardrail_id']}: {v['description']}" for v in entry["violations"]] | |
| ) | |
| sample = { | |
| "instruction": f"Review and correct the following response for compliance violations: {violations_desc}", | |
| "input": entry["response_preview"], | |
| "output": "[CORRECTED RESPONSE REQUIRED — to be filled by human reviewer]", | |
| "source": "self_correction_log", | |
| "timestamp": entry["timestamp"], | |
| } | |
| retraining_samples.append(sample) | |
| with open(output_file, "w", encoding="utf-8") as f: | |
| for sample in retraining_samples: | |
| f.write(json.dumps(sample, ensure_ascii=False) + "\n") | |
| logger.info(f"Generated {len(retraining_samples)} retraining samples: {output_file}") | |
| return len(retraining_samples) | |
| # --------------------------------------------------------------------------- | |
| # CLI Entry Point | |
| # --------------------------------------------------------------------------- | |
| if __name__ == "__main__": | |
| import argparse | |
| parser = argparse.ArgumentParser(description="Manara-3B: Self-Reflective Guardrail Engine") | |
| parser.add_argument("--response", required=True, help="Response text to check") | |
| parser.add_argument("--language", default="ar", choices=["ar", "en"]) | |
| parser.add_argument("--log_dir", default="../../logs") | |
| args = parser.parse_args() | |
| engine = ManaraGuardrailEngine(log_dir=args.log_dir) | |
| result = engine.check(args.response, args.language) | |
| print("\n" + "=" * 60) | |
| print(f"GUARDRAIL CHECK RESULT: {'PASSED' if result['passed'] else 'FAILED'}") | |
| print(f"Severity Summary: {result['severity_summary']}") | |
| if result["violations"]: | |
| print("\nViolations:") | |
| for v in result["violations"]: | |
| print(f" [{v['severity'].upper()}] {v['guardrail_id']} — {v['guardrail_name']}") | |
| print(f" Description: {v['description']}") | |
| if v.get("evidence"): | |
| print(f" Evidence: {v['evidence']}") | |
| print("=" * 60) | |