| """ |
| TRuCAL Oracle Module |
| |
| A generalized learning system that stores and retrieves knowledge from a YAML casebase. |
| Uses semantic similarity and keyword matching to provide relevant responses. |
| """ |
|
|
| import json |
| import os |
| import yaml |
| import numpy as np |
| from typing import Dict, List, Optional, Tuple, Any |
| from difflib import SequenceMatcher |
| from sentence_transformers import SentenceTransformer |
| from collections import Counter, defaultdict |
|
|
| class Case: |
| """Represents a single case in the knowledge base.""" |
| |
| def __init__(self, |
| question: str, |
| response: str, |
| category: str = "general", |
| keywords: List[str] = None, |
| metadata: Optional[Dict] = None): |
| self.question = question |
| self.response = response |
| self.category = category |
| self.keywords = keywords or [] |
| self.metadata = metadata or {} |
| self.usage_count = 0 |
| self.success_count = 0 |
| |
| def to_dict(self) -> Dict: |
| """Convert case to dictionary for serialization.""" |
| return { |
| 'question': self.question, |
| 'response': self.response, |
| 'category': self.category, |
| 'keywords': self.keywords, |
| 'metadata': self.metadata, |
| 'usage_count': self.usage_count, |
| 'success_count': self.success_count |
| } |
| |
| @classmethod |
| def from_dict(cls, data: Dict) -> 'Case': |
| """Create a Case from a dictionary.""" |
| case = cls( |
| question=data['question'], |
| response=data['response'], |
| category=data.get('category', 'general'), |
| keywords=data.get('keywords', []), |
| metadata=data.get('metadata', {}) |
| ) |
| case.usage_count = data.get('usage_count', 0) |
| case.success_count = data.get('success_count', 0) |
| return case |
|
|
|
|
| class TRuCALOracle: |
| """ |
| TRuCAL's knowledge core - a learning system that grows with each interaction. |
| |
| Features: |
| - Semantic and keyword-based matching |
| - Category-based organization |
| - Continuous learning from user feedback |
| - YAML-based case storage |
| - Performance metrics and analytics |
| """ |
| |
| def __init__(self, |
| casebase_path: str = 'data/casebase.json', |
| yaml_path: str = 'data/trm_cases.yaml', |
| similarity_threshold: float = 0.45, |
| model_name: str = 'all-MiniLM-L6-v2'): |
| """ |
| Initialize the TRuCAL oracle. |
| |
| Args: |
| casebase_path: Path to save/load the casebase |
| yaml_path: Path to the YAML case file |
| similarity_threshold: Minimum similarity score (0-1) to consider a match |
| model_name: Name of the sentence transformer model for embeddings |
| """ |
| self.casebase_path = casebase_path |
| self.yaml_path = yaml_path |
| self.similarity_threshold = similarity_threshold |
| self.casebase: List[Case] = [] |
| self.model = SentenceTransformer(model_name) |
| self.embeddings = None |
| self.category_index = defaultdict(list) |
| |
| |
| os.makedirs(os.path.dirname(casebase_path), exist_ok=True) |
| |
| |
| self._load_or_initialize() |
| |
| def _load_or_initialize(self): |
| """Load existing casebase or initialize with YAML cases.""" |
| if os.path.exists(self.casebase_path): |
| self._load_casebase() |
| else: |
| self._load_from_yaml() |
| self._build_indices() |
| |
| def _load_from_yaml(self): |
| """Load cases from the YAML file.""" |
| try: |
| yaml_path = os.path.join( |
| os.path.dirname(os.path.dirname(__file__)), |
| self.yaml_path |
| ) |
| |
| if os.path.exists(yaml_path): |
| with open(yaml_path, 'r', encoding='utf-8') as f: |
| cases = yaml.safe_load(f) or [] |
| |
| for case_data in cases: |
| self.add_case( |
| question=case_data['question'], |
| response=case_data['response'], |
| category=case_data.get('category', 'general'), |
| keywords=case_data.get('keywords', []), |
| metadata={'source': 'yaml_import'} |
| ) |
| |
| print(f"Loaded {len(cases)} cases from {yaml_path}") |
| self._save_casebase() |
| return True |
| |
| except Exception as e: |
| print(f"Error loading from YAML: {e}") |
| |
| |
| print("Falling back to minimal default cases") |
| self._add_default_cases() |
| return False |
| |
| def _add_default_cases(self): |
| """Add minimal default cases if no others are available.""" |
| default_cases = [ |
| { |
| 'question': 'How does TRuCAL work?', |
| 'response': 'I learn from interactions and stored knowledge to provide thoughtful responses. The more we talk, the better I become!', |
| 'category': 'meta', |
| 'keywords': ['help', 'how', 'trucal'] |
| }, |
| { |
| 'question': 'Can you help me with an ethical dilemma?', |
| 'response': 'I can help you think through ethical questions by considering different perspectives. What would you like to discuss?', |
| 'category': 'ethics', |
| 'keywords': ['help', 'ethics', 'dilemma'] |
| } |
| ] |
| |
| for case_data in default_cases: |
| self.add_case(**case_data) |
| |
| def _build_indices(self): |
| """Build search indices for faster lookups.""" |
| self.category_index = defaultdict(list) |
| for idx, case in enumerate(self.casebase): |
| self.category_index[case.category].append(idx) |
| |
| def _load_casebase(self): |
| """Load the casebase from disk.""" |
| try: |
| with open(self.casebase_path, 'r', encoding='utf-8') as f: |
| case_data = json.load(f) |
| self.casebase = [Case.from_dict(case_dict) for case_dict in case_data] |
| self._update_embeddings() |
| print(f"Loaded {len(self.casebase)} cases from {self.casebase_path}") |
| except Exception as e: |
| print(f"Error loading casebase: {e}") |
| self.casebase = [] |
| |
| def _update_embeddings(self): |
| """Update embeddings for semantic search.""" |
| if not self.casebase: |
| self.embeddings = None |
| return |
| |
| questions = [case.question for case in self.casebase] |
| self.embeddings = self.model.encode(questions, convert_to_tensor=True) |
| |
| def _save_casebase(self): |
| """Save the casebase to disk.""" |
| try: |
| with open(self.casebase_path, 'w', encoding='utf-8') as f: |
| case_data = [case.to_dict() for case in self.casebase] |
| json.dump(case_data, f, indent=2, ensure_ascii=False) |
| except Exception as e: |
| print(f"Error saving casebase: {e}") |
| |
| def add_case(self, question: str, response: str, category: str = "general", |
| keywords: List[str] = None, metadata: Optional[Dict] = None) -> Case: |
| """ |
| Add a new case to the knowledge base. |
| |
| Args: |
| question: The question or prompt |
| response: The response or answer |
| category: Category for organization |
| keywords: List of relevant keywords |
| metadata: Additional metadata |
| |
| Returns: |
| The created Case object |
| """ |
| |
| existing_idx, _ = self._find_most_similar(question) |
| if existing_idx is not None: |
| |
| existing_case = self.casebase[existing_idx] |
| existing_case.response = response |
| existing_case.category = category |
| existing_case.keywords = list(set(existing_case.keywords + (keywords or []))) |
| if metadata: |
| existing_case.metadata.update(metadata) |
| self._save_casebase() |
| return existing_case |
| |
| |
| new_case = Case( |
| question=question, |
| response=response, |
| category=category, |
| keywords=keywords or [], |
| metadata=metadata or {} |
| ) |
| self.casebase.append(new_case) |
| self._update_embeddings() |
| self._save_casebase() |
| return new_case |
| |
| def _find_most_similar(self, query: str, category: str = None) -> Tuple[Optional[int], float]: |
| """ |
| Find the most similar case to the query. |
| |
| Args: |
| query: The query string |
| category: Optional category to filter by |
| |
| Returns: |
| Tuple of (index, similarity_score) of the most similar case |
| """ |
| if not self.casebase: |
| return None, 0.0 |
| |
| |
| candidate_indices = range(len(self.casebase)) |
| if category and category in self.category_index: |
| candidate_indices = self.category_index[category] |
| |
| |
| if not candidate_indices: |
| return None, 0.0 |
| |
| |
| if self.embeddings is not None: |
| query_embedding = self.model.encode(query, convert_to_tensor=True) |
| similarities = torch.nn.functional.cosine_similarity( |
| query_embedding.unsqueeze(0), |
| self.embeddings[list(candidate_indices)] |
| ) |
| max_sim, max_idx = torch.max(similarities, dim=0) |
| max_sim = max_sim.item() |
| max_global_idx = candidate_indices[max_idx.item()] |
| |
| if max_sim >= self.similarity_threshold: |
| return max_global_idx, max_sim |
| |
| |
| max_sim = 0.0 |
| max_idx = None |
| |
| for idx in candidate_indices: |
| case = self.casebase[idx] |
| |
| keyword_match = any(kw in query.lower() for kw in case.keywords) |
| if keyword_match: |
| return idx, 0.8 |
| |
| |
| similarity = SequenceMatcher(None, query.lower(), case.question.lower()).ratio() |
| if similarity > max_sim: |
| max_sim = similarity |
| max_idx = idx |
| |
| return (max_idx, max_sim) if max_sim >= self.similarity_threshold else (None, 0.0) |
| |
| def get_response(self, query: str, category: str = None) -> Tuple[str, Dict]: |
| """ |
| Get a response for the given query. |
| |
| Args: |
| query: The user's question or prompt |
| category: Optional category to filter by |
| |
| Returns: |
| Tuple of (response, metadata) where metadata contains info about the match |
| """ |
| if not self.casebase: |
| return "I'm still learning. Could you be the first to teach me something new?", {} |
| |
| idx, similarity = self._find_most_similar(query, category) |
| |
| if idx is not None: |
| case = self.casebase[idx] |
| case.usage_count += 1 |
| self._save_casebase() |
| |
| metadata = { |
| 'match_type': 'semantic' if similarity >= 0.7 else 'keyword', |
| 'similarity': float(similarity), |
| 'case_id': id(case), |
| 'category': case.category, |
| 'keywords': case.keywords, |
| 'usage_count': case.usage_count, |
| 'success_rate': case.success_count / case.usage_count if case.usage_count > 0 else 0 |
| } |
| |
| return case.response, metadata |
| |
| |
| return ( |
| "That's an interesting question. I'm still learning and don't have a perfect answer yet. " |
| "Could you share your thoughts or rephrase your question?", |
| {'match_type': 'none', 'similarity': 0.0} |
| ) |
| |
| def provide_feedback(self, case_id: int, was_helpful: bool = True): |
| """ |
| Provide feedback on a case's helpfulness. |
| |
| Args: |
| case_id: The ID of the case |
| was_helpful: Whether the response was helpful |
| """ |
| for case in self.casebase: |
| if id(case) == case_id: |
| if was_helpful: |
| case.success_count += 1 |
| self._save_casebase() |
| break |
| |
| def get_stats(self) -> Dict[str, Any]: |
| """Get statistics about the knowledge base.""" |
| if not self.casebase: |
| return { |
| 'total_cases': 0, |
| 'total_usage': 0, |
| 'categories': {} |
| } |
| |
| categories = {} |
| for category, indices in self.category_index.items(): |
| cases = [self.casebase[i] for i in indices] |
| categories[category] = { |
| 'count': len(cases), |
| 'usage': sum(c.usage_count for c in cases) |
| } |
| |
| total_usage = sum(c.usage_count for c in self.casebase) |
| |
| return { |
| 'total_cases': len(self.casebase), |
| 'total_usage': total_usage, |
| 'categories': categories, |
| 'avg_usage_per_case': total_usage / len(self.casebase) if self.casebase else 0 |
| } |
| |
| def get_cases_by_category(self, category: str) -> List[Dict]: |
| """Get all cases in a specific category.""" |
| return [ |
| case.to_dict() |
| for case in self.casebase |
| if case.category == category |
| ] |
| |
| def search(self, query: str, category: str = None, min_similarity: float = 0.3) -> List[Dict]: |
| """ |
| Search for cases matching the query. |
| |
| Args: |
| query: The search query |
| category: Optional category filter |
| min_similarity: Minimum similarity score (0-1) |
| |
| Returns: |
| List of matching cases with similarity scores |
| """ |
| if not self.casebase: |
| return [] |
| |
| |
| candidate_indices = range(len(self.casebase)) |
| if category and category in self.category_index: |
| candidate_indices = self.category_index[category] |
| |
| results = [] |
| |
| |
| if self.embeddings is not None: |
| query_embedding = self.model.encode(query, convert_to_tensor=True) |
| similarities = torch.nn.functional.cosine_similarity( |
| query_embedding.unsqueeze(0), |
| self.embeddings[list(candidate_indices)] |
| ) |
| |
| for idx, sim in zip(candidate_indices, similarities): |
| sim = sim.item() |
| if sim >= min_similarity: |
| case = self.casebase[idx] |
| results.append({ |
| **case.to_dict(), |
| 'similarity': sim, |
| 'match_type': 'semantic' |
| }) |
| |
| |
| query_terms = set(query.lower().split()) |
| for idx in candidate_indices: |
| case = self.casebase[idx] |
| keyword_matches = [kw for kw in case.keywords if kw.lower() in query_terms] |
| if keyword_matches and idx not in [r['id'] for r in results]: |
| results.append({ |
| **case.to_dict(), |
| 'similarity': 0.7, |
| 'match_type': 'keyword', |
| 'matched_keywords': keyword_matches |
| }) |
| |
| |
| results.sort(key=lambda x: x['similarity'], reverse=True) |
| return results |
| |
| def __call__(self, query: str, category: str = None) -> str: |
| """Convenience method to get just the response text.""" |
| return self.get_response(query, category)[0] |
| |
| """Update the embeddings for all cases.""" |
| if not self.casebase: |
| self.embeddings = None |
| return |
| |
| questions = [case.question for case in self.casebase] |
| self.embeddings = self.model.encode(questions, convert_to_tensor=True) |
| |
| def add_case(self, question: str, response: str, tags: List[str] = None, |
| metadata: Optional[Dict] = None) -> Case: |
| """ |
| Add a new case to the casebase. |
| |
| Args: |
| question: The ethical question or scenario |
| response: The response or analysis |
| tags: Optional list of tags for categorization |
| metadata: Additional metadata about the case |
| |
| Returns: |
| The newly created Case object |
| """ |
| |
| existing_idx, _ = self._find_most_similar(question) |
| if existing_idx is not None: |
| |
| existing_case = self.casebase[existing_idx] |
| existing_case.response = response |
| existing_case.tags = list(set(existing_case.tags + (tags or []))) |
| if metadata: |
| existing_case.metadata.update(metadata) |
| self._save_casebase() |
| return existing_case |
| |
| |
| new_case = Case( |
| question=question, |
| response=response, |
| tags=tags or [], |
| metadata=metadata or {} |
| ) |
| self.casebase.append(new_case) |
| self._update_embeddings() |
| self._save_casebase() |
| return new_case |
| |
| def _find_most_similar(self, query: str) -> Tuple[Optional[int], float]: |
| """ |
| Find the most similar case to the query. |
| |
| Args: |
| query: The query string |
| |
| Returns: |
| Tuple of (index, similarity_score) of the most similar case, or (None, 0) if no cases |
| """ |
| if not self.casebase: |
| return None, 0.0 |
| |
| |
| if self.embeddings is not None: |
| query_embedding = self.model.encode(query, convert_to_tensor=True) |
| similarities = torch.nn.functional.cosine_similarity( |
| query_embedding.unsqueeze(0), |
| self.embeddings |
| ) |
| max_sim, max_idx = torch.max(similarities, dim=0) |
| max_sim = max_sim.item() |
| max_idx = max_idx.item() |
| |
| if max_sim >= self.similarity_threshold: |
| return max_idx, max_sim |
| |
| |
| max_sim = 0.0 |
| max_idx = None |
| |
| for i, case in enumerate(self.casebase): |
| similarity = SequenceMatcher(None, query.lower(), case.question.lower()).ratio() |
| if similarity > max_sim: |
| max_sim = similarity |
| max_idx = i |
| |
| return (max_idx, max_sim) if max_sim >= self.similarity_threshold else (None, 0.0) |
| |
| def get_response(self, query: str) -> Tuple[str, Dict]: |
| """ |
| Get a response for the given query. |
| |
| Args: |
| query: The user's question or scenario |
| |
| Returns: |
| Tuple of (response, metadata) where metadata contains info about the match |
| """ |
| if not self.casebase: |
| return "I'm still learning about ethical reasoning. Could you provide more context?", {} |
| |
| idx, similarity = self._find_most_similar(query) |
| |
| if idx is not None: |
| case = self.casebase[idx] |
| case.usage_count += 1 |
| self._save_casebase() |
| |
| metadata = { |
| 'match_type': 'semantic' if similarity >= self.similarity_threshold else 'keyword', |
| 'similarity': similarity, |
| 'case_id': id(case), |
| 'tags': case.tags, |
| 'usage_count': case.usage_count, |
| 'success_rate': case.success_count / case.usage_count if case.usage_count > 0 else 0 |
| } |
| |
| return case.response, metadata |
| |
| |
| return ( |
| "This is a nuanced ethical question. I'm still learning and would appreciate " |
| "your perspective. How would you approach this situation?", |
| {'match_type': 'none', 'similarity': similarity} |
| ) |
| |
| def provide_feedback(self, case_id: int, was_helpful: bool): |
| """ |
| Provide feedback on a case's helpfulness. |
| |
| Args: |
| case_id: The ID of the case (returned in get_response metadata) |
| was_helpful: Whether the response was helpful |
| """ |
| for case in self.casebase: |
| if id(case) == case_id: |
| if was_helpful: |
| case.success_count += 1 |
| self._save_casebase() |
| break |
| |
| def get_stats(self) -> Dict[str, Any]: |
| """Get statistics about the casebase.""" |
| return { |
| 'total_cases': len(self.casebase), |
| 'total_usage': sum(c.usage_count for c in self.casebase), |
| 'avg_success_rate': ( |
| sum(c.success_count for c in self.casebase) / |
| sum(max(1, c.usage_count) for c in self.casebase) |
| if self.casebase else 0 |
| ), |
| 'tags': { |
| tag: sum(1 for c in self.casebase if tag in c.tags) |
| for tag in set(tag for c in self.casebase for tag in c.tags) |
| } |
| } |
|
|
|
|
| |
| if __name__ == "__main__": |
| |
| learner = RecursiveLearner() |
| |
| |
| query = "Is lying ever justified?" |
| response, metadata = learner.get_response(query) |
| print(f"Query: {query}") |
| print(f"Response: {response}") |
| print(f"Metadata: {metadata}") |
| |
| |
| if 'case_id' in metadata: |
| learner.provide_feedback(metadata['case_id'], was_helpful=True) |
| |
| |
| print("\nAdding new case...") |
| learner.add_case( |
| question="What are the ethics of AI decision-making?", |
| response="AI decision-making raises important ethical considerations including transparency, accountability, bias, and the potential for unintended consequences. It's crucial to ensure AI systems are designed with ethical principles in mind and that humans remain ultimately responsible for decisions with significant impact.", |
| tags=["AI", "ethics", "decision-making"] |
| ) |
| |
| |
| print("\nCasebase statistics:") |
| print(learner.get_stats()) |
|
|