File size: 2,892 Bytes
95cc8f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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:
                # Read existing cases
                with open(self.yaml_path, 'r') as f:
                    cases = yaml.safe_load(f) or []
                
                # Add new case
                cases.append(new_case)
                
                # Write back to file
                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 []

# Singleton instance for easy import
casebase_updater = CasebaseUpdater('data/trm_cases.yaml')