File size: 23,422 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 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 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 | """
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)
# Ensure data directory exists
os.makedirs(os.path.dirname(casebase_path), exist_ok=True)
# Load or initialize casebase
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}")
# If we get here, YAML loading failed
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
"""
# Check for duplicates
existing_idx, _ = self._find_most_similar(question)
if existing_idx is not None:
# Update existing case if it's very similar
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
# Create new 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
# Get candidate indices based on category filter
candidate_indices = range(len(self.casebase))
if category and category in self.category_index:
candidate_indices = self.category_index[category]
# If no candidates, return None
if not candidate_indices:
return None, 0.0
# Try semantic similarity first if embeddings are available
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
# Fall back to basic string similarity
max_sim = 0.0
max_idx = None
for idx in candidate_indices:
case = self.casebase[idx]
# Check keyword matches first (faster than string comparison)
keyword_match = any(kw in query.lower() for kw in case.keywords)
if keyword_match:
return idx, 0.8 # High confidence for keyword matches
# If no keyword match, use string similarity
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
# No good match found
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 []
# Get candidate indices based on category filter
candidate_indices = range(len(self.casebase))
if category and category in self.category_index:
candidate_indices = self.category_index[category]
results = []
# Try semantic search if embeddings are available
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'
})
# Add keyword matches
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, # Fixed score for keyword matches
'match_type': 'keyword',
'matched_keywords': keyword_matches
})
# Sort by similarity (descending)
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
"""
# Check if a similar case already exists
existing_idx, _ = self._find_most_similar(question)
if existing_idx is not None:
# Update existing case if it's very similar
existing_case = self.casebase[existing_idx]
existing_case.response = response # Update response
existing_case.tags = list(set(existing_case.tags + (tags or []))) # Merge tags
if metadata:
existing_case.metadata.update(metadata)
self._save_casebase()
return existing_case
# Create new 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
# First try semantic similarity if embeddings are available
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
# Fall back to basic string similarity
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
# No good match found
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)
}
}
# Example usage
if __name__ == "__main__":
# Initialize the recursive learner
learner = RecursiveLearner()
# Example query
query = "Is lying ever justified?"
response, metadata = learner.get_response(query)
print(f"Query: {query}")
print(f"Response: {response}")
print(f"Metadata: {metadata}")
# Provide feedback
if 'case_id' in metadata:
learner.provide_feedback(metadata['case_id'], was_helpful=True)
# Add a new case
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"]
)
# Get stats
print("\nCasebase statistics:")
print(learner.get_stats())
|