| """ |
| Auto-updating casebase for TRuCAL's ethical case management. |
| Handles thread-safe addition of new cases to the YAML casebase. |
| """ |
| import yaml |
| import threading |
| from pathlib import Path |
| from typing import Optional, List, Dict, Any |
|
|
| class CasebaseUpdater: |
| """ |
| Thread-safe casebase management for TRuCAL's ethical case storage. |
| |
| Args: |
| yaml_path: Path to the YAML file storing the cases |
| """ |
| def __init__(self, yaml_path: str): |
| self.yaml_path = Path(yaml_path) |
| self.yaml_path.parent.mkdir(parents=True, exist_ok=True) |
| self.lock = threading.Lock() |
| self._ensure_casebase_exists() |
| |
| def _ensure_casebase_exists(self) -> None: |
| """Ensure the YAML file exists with an empty list if it doesn't exist.""" |
| if not self.yaml_path.exists(): |
| with self.lock: |
| with open(self.yaml_path, 'w') as f: |
| yaml.safe_dump([], f) |
| |
| def add_case( |
| self, |
| question: str, |
| answer: str, |
| keywords: Optional[List[str]] = None, |
| metadata: Optional[Dict[str, Any]] = None |
| ) -> bool: |
| """ |
| Add a new case to the casebase in a thread-safe manner. |
| |
| Args: |
| question: The user's question or prompt |
| answer: The system's response |
| keywords: List of keywords for matching |
| metadata: Additional metadata for the case |
| |
| Returns: |
| bool: True if case was added successfully |
| """ |
| new_case = { |
| "question": question, |
| "response": answer, |
| "keywords": keywords or [], |
| "metadata": metadata or {} |
| } |
| |
| with self.lock: |
| try: |
| |
| with open(self.yaml_path, 'r') as f: |
| cases = yaml.safe_load(f) or [] |
| |
| |
| cases.append(new_case) |
| |
| |
| with open(self.yaml_path, 'w') as f: |
| yaml.safe_dump(cases, f, default_flow_style=False) |
| |
| return True |
| |
| except Exception as e: |
| print(f"Error adding case to casebase: {e}") |
| return False |
| |
| def get_cases(self) -> List[Dict[str, Any]]: |
| """ |
| Retrieve all cases from the casebase. |
| |
| Returns: |
| List of case dictionaries |
| """ |
| with self.lock: |
| try: |
| with open(self.yaml_path, 'r') as f: |
| return yaml.safe_load(f) or [] |
| except Exception as e: |
| print(f"Error reading casebase: {e}") |
| return [] |
|
|
| |
| casebase_updater = CasebaseUpdater('data/trm_cases.yaml') |
|
|