File size: 35,552 Bytes
20d720d c5514db b28635c 6d99a60 b73fa18 20d720d c537b15 20d720d c537b15 20d720d c537b15 20d720d c537b15 10453f3 71150b1 c537b15 961a175 d39c478 c5514db 961a175 c5514db c537b15 d0f6de1 c537b15 564cd14 c537b15 961a175 c537b15 20d720d |
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 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 |
"""
Response validation tools for ensuring safe and appropriate responses
"""
import re
from typing import Dict, List, Tuple, Optional, Any
from dataclasses import dataclass
import json
from transformers import pipeline
import torch
from pydantic import PrivateAttr
from crewai.tools import BaseTool
#from .base_tool import BaseTool
# @dataclass
class ValidationResult:
"""Result of validation check"""
is_valid: bool
issues: List[str]
warnings: List[str]
suggestions: List[str]
confidence: float
refined_text: Optional[str] = None
# class ValidationTools:
# """Tools for validating responses and ensuring safety"""
# def __init__(self, config):
# self.config = config
# # Initialize sentiment analyzer for tone checking
# self.sentiment_analyzer = pipeline(
# "sentiment-analysis",
# model="nlptown/bert-base-multilingual-uncased-sentiment",
# device=0 if torch.cuda.is_available() else -1
# )
# # Prohibited patterns for different categories
# self.prohibited_patterns = {
# 'medical': [
# r'\b(?:diagnos|prescrib|medicat|cure|treat|therap)\w*\b',
# r'\b(?:disease|illness|disorder|syndrome)\s+(?:is|are|can be)\b',
# r'\b(?:take|consume|dose|dosage)\s+\d+\s*(?:mg|ml|pill|tablet)',
# r'\b(?:medical|clinical|physician|doctor)\s+(?:advice|consultation|opinion)',
# ],
# 'legal': [
# r'\b(?:legal advice|lawsuit|sue|court|litigation)\b',
# r'\b(?:illegal|unlawful|crime|criminal|prosecut)\w*\b',
# r'\b(?:you should|must|have to)\s+(?:sign|agree|consent|contract)',
# r'\b(?:rights|obligations|liability|damages)\s+(?:are|include)\b',
# ],
# 'financial': [
# r'\b(?:invest|buy|sell|trade)\s+(?:stock|crypto|bitcoin|forex)\b',
# r'\b(?:guaranteed|promise)\s+(?:return|profit|income|earnings)\b',
# r'\b(?:financial advisor|investment advice|trading strategy)\b',
# r'\b(?:tax|accounting|financial planning)\s+(?:advice|consultation)',
# ],
# 'harmful': [
# r'\b(?:suicide|suicidal|kill\s+(?:your|my)self|end\s+(?:it|life))\b',
# r'\b(?:self[\-\s]?harm|hurt\s+(?:your|my)self|cutting)\b',
# r'\b(?:violence|violent|weapon|attack|assault)\b',
# r'\b(?:hate|discriminat|racist|sexist|homophobic)\b',
# ],
# 'absolute': [
# r'\b(?:always|never|every|all|none|no one|everyone)\s+(?:will|must|should|is|are)\b',
# r'\b(?:definitely|certainly|guaranteed|assured|promise)\b',
# r'\b(?:only way|only solution|must do|have to)\b',
# ]
# }
# # Required elements for supportive responses
# self.supportive_elements = {
# 'empathy': [
# 'understand', 'hear', 'feel', 'acknowledge', 'recognize',
# 'appreciate', 'empathize', 'relate', 'comprehend'
# ],
# 'validation': [
# 'valid', 'normal', 'understandable', 'natural', 'okay',
# 'reasonable', 'makes sense', 'legitimate'
# ],
# 'support': [
# 'support', 'help', 'here for you', 'together', 'alongside',
# 'assist', 'guide', 'accompany', 'with you'
# ],
# 'hope': [
# 'can', 'possible', 'able', 'capable', 'potential',
# 'opportunity', 'growth', 'improve', 'better', 'progress'
# ],
# 'empowerment': [
# 'choice', 'decide', 'control', 'power', 'strength',
# 'agency', 'capable', 'resource', 'ability'
# ]
# }
# # Crisis indicators
# self.crisis_indicators = [
# r'\b(?:want|going|plan)\s+to\s+(?:die|kill|end)\b',
# r'\b(?:no reason|point|hope)\s+(?:to|in)\s+(?:live|living|life)\b',
# r'\b(?:better off|world)\s+without\s+me\b',
# r'\bsuicide\s+(?:plan|method|attempt)\b',
# r'\b(?:final|last)\s+(?:goodbye|letter|message)\b'
# ]
# # Tone indicators
# self.negative_tone_words = [
# 'stupid', 'idiot', 'dumb', 'pathetic', 'worthless',
# 'loser', 'failure', 'weak', 'incompetent', 'useless'
# ]
# self.dismissive_phrases = [
# 'just get over it', 'stop complaining', 'not a big deal',
# 'being dramatic', 'overreacting', 'too sensitive'
# ]
# def validate_response(self, response: str, context: Dict[str, Any] = None) -> ValidationResult:
# """Comprehensive validation of response"""
# issues = []
# warnings = []
# suggestions = []
# # Check for prohibited content
# prohibited_check = self._check_prohibited_content(response)
# if prohibited_check["found"]:
# issues.extend(prohibited_check["violations"])
# suggestions.extend(prohibited_check["suggestions"])
# # Check tone and sentiment
# tone_check = self._check_tone(response)
# if not tone_check["appropriate"]:
# warnings.extend(tone_check["issues"])
# suggestions.extend(tone_check["suggestions"])
# # Check for supportive elements
# support_check = self._check_supportive_elements(response)
# if support_check["missing"]:
# warnings.append(f"Missing supportive elements: {', '.join(support_check['missing'])}")
# suggestions.extend(support_check["suggestions"])
# # Check for crisis content in context
# if context and context.get("user_input"):
# crisis_check = self._check_crisis_indicators(context["user_input"])
# if crisis_check["is_crisis"] and "crisis" not in response.lower():
# warnings.append("User may be in crisis but response doesn't address this")
# suggestions.append("Include crisis resources and immediate support options")
# # Calculate overall confidence
# confidence = self._calculate_confidence(issues, warnings)
# # Generate refined response if needed
# refined_text = None
# if issues or (warnings and confidence < 0.7):
# refined_text = self._refine_response(response, issues, warnings, suggestions)
# return ValidationResult(
# is_valid=len(issues) == 0,
# issues=issues,
# warnings=warnings,
# suggestions=suggestions,
# confidence=confidence,
# refined_text=refined_text
# )
# def _check_prohibited_content(self, text: str) -> Dict[str, Any]:
# """Check for prohibited content patterns"""
# found_violations = []
# suggestions = []
# for category, patterns in self.prohibited_patterns.items():
# for pattern in patterns:
# if re.search(pattern, text, re.IGNORECASE):
# found_violations.append(f"Contains {category} advice/content")
# # Add specific suggestions
# if category == "medical":
# suggestions.append("Replace with: 'Consider speaking with a healthcare professional'")
# elif category == "legal":
# suggestions.append("Replace with: 'For legal matters, consult with a qualified attorney'")
# elif category == "financial":
# suggestions.append("Replace with: 'For financial decisions, consider consulting a financial advisor'")
# elif category == "harmful":
# suggestions.append("Include crisis resources and express immediate concern for safety")
# elif category == "absolute":
# suggestions.append("Use qualifying language like 'often', 'might', 'could' instead of absolutes")
# break
# return {
# "found": len(found_violations) > 0,
# "violations": found_violations,
# "suggestions": suggestions
# }
# def _check_tone(self, text: str) -> Dict[str, Any]:
# """Check the tone and sentiment of the response"""
# issues = []
# suggestions = []
# # Check sentiment
# try:
# sentiment_result = self.sentiment_analyzer(text[:512])[0] # Limit length for model
# sentiment_score = sentiment_result['score']
# sentiment_label = sentiment_result['label']
# # Check if too negative
# if '1' in sentiment_label or '2' in sentiment_label: # 1-2 stars = negative
# issues.append("Response tone is too negative")
# suggestions.append("Add more supportive and hopeful language")
# except:
# pass
# # Check for negative words
# text_lower = text.lower()
# found_negative = [word for word in self.negative_tone_words if word in text_lower]
# if found_negative:
# issues.append(f"Contains negative/judgmental language: {', '.join(found_negative)}")
# suggestions.append("Replace judgmental terms with supportive language")
# # Check for dismissive phrases
# found_dismissive = [phrase for phrase in self.dismissive_phrases if phrase in text_lower]
# if found_dismissive:
# issues.append("Contains dismissive language")
# suggestions.append("Acknowledge and validate the person's feelings instead")
# return {
# "appropriate": len(issues) == 0,
# "issues": issues,
# "suggestions": suggestions
# }
# def _check_supportive_elements(self, text: str) -> Dict[str, Any]:
# """Check for presence of supportive elements"""
# text_lower = text.lower()
# missing_elements = []
# suggestions = []
# element_scores = {}
# for element, keywords in self.supportive_elements.items():
# found = any(keyword in text_lower for keyword in keywords)
# element_scores[element] = found
# if not found:
# missing_elements.append(element)
# # Generate suggestions for missing elements
# if 'empathy' in missing_elements:
# suggestions.append("Add empathetic language like 'I understand how difficult this must be'")
# if 'validation' in missing_elements:
# suggestions.append("Validate their feelings with phrases like 'Your feelings are completely valid'")
# if 'support' in missing_elements:
# suggestions.append("Express support with 'I'm here to support you through this'")
# if 'hope' in missing_elements:
# suggestions.append("Include hopeful elements about growth and positive change")
# if 'empowerment' in missing_elements:
# suggestions.append("Emphasize their agency and ability to make choices")
# return {
# "missing": missing_elements,
# "present": [k for k, v in element_scores.items() if v],
# "suggestions": suggestions
# }
# def _check_crisis_indicators(self, text: str) -> Dict[str, Any]:
# """Check for crisis indicators in text"""
# for pattern in self.crisis_indicators:
# if re.search(pattern, text, re.IGNORECASE):
# return {
# "is_crisis": True,
# "pattern_matched": pattern,
# "action": "Immediate crisis response needed"
# }
# return {"is_crisis": False}
# def _calculate_confidence(self, issues: List[str], warnings: List[str]) -> float:
# """Calculate confidence score for validation"""
# if issues:
# return 0.3 - (0.1 * len(issues)) # Major issues severely impact confidence
# confidence = 1.0
# confidence -= 0.1 * len(warnings) # Each warning reduces confidence
# return max(0.0, confidence)
# def _refine_response(self, response: str, issues: List[str], warnings: List[str], suggestions: List[str]) -> str:
# """Attempt to refine the response based on issues found"""
# refined = response
# # Add disclaimer for professional advice
# if any('advice' in issue for issue in issues):
# disclaimer = "\n\n*Please note: I'm here to provide support and guidance, but for specific professional matters, it's important to consult with qualified professionals.*"
# if disclaimer not in refined:
# refined += disclaimer
# # Add crisis resources if needed
# if any('crisis' in warning for warning in warnings):
# crisis_text = "\n\n**If you're in crisis, please reach out for immediate help:**\n- Crisis Hotline: 988 (US)\n- Crisis Text Line: Text HOME to 741741\n- International: findahelpline.com"
# if crisis_text not in refined:
# refined += crisis_text
# # Add supportive closing if missing hope
# if any('hope' in warning for warning in warnings):
# hopeful_closing = "\n\nRemember, you have the strength to navigate this challenge, and positive change is possible. I'm here to support you on this journey."
# if not any(phrase in refined.lower() for phrase in ['journey', 'strength', 'possible']):
# refined += hopeful_closing
# return refined
# def validate_user_input(self, text: str) -> ValidationResult:
# """Validate user input for safety and process-ability"""
# issues = []
# warnings = []
# suggestions = []
# # Check if empty
# if not text or not text.strip():
# issues.append("Empty input received")
# suggestions.append("Please share what's on your mind")
# return ValidationResult(False, issues, warnings, suggestions, 0.0)
# # Check length
# if len(text) > 5000:
# warnings.append("Input is very long")
# suggestions.append("Consider breaking this into smaller parts")
# # Check for crisis indicators
# crisis_check = self._check_crisis_indicators(text)
# if crisis_check["is_crisis"]:
# warnings.append("Crisis indicators detected")
# suggestions.append("Prioritize safety and provide crisis resources")
# # Check for spam/repetition
# if self._is_spam(text):
# issues.append("Input appears to be spam or repetitive")
# suggestions.append("Please share genuine thoughts or concerns")
# confidence = self._calculate_confidence(issues, warnings)
# return ValidationResult(
# is_valid=len(issues) == 0,
# issues=issues,
# warnings=warnings,
# suggestions=suggestions,
# confidence=confidence
# )
# def _is_spam(self, text: str) -> bool:
# """Simple spam detection"""
# # Check for excessive repetition
# words = text.lower().split()
# if len(words) > 10:
# unique_ratio = len(set(words)) / len(words)
# if unique_ratio < 0.3: # Less than 30% unique words
# return True
# # Check for common spam patterns
# spam_patterns = [
# r'(?:buy|sell|click|visit)\s+(?:now|here|this)',
# r'(?:congratulations|winner|prize|lottery)',
# r'(?:viagra|pills|drugs|pharmacy)',
# r'(?:$$|money\s+back|guarantee)'
# ]
# for pattern in spam_patterns:
# if re.search(pattern, text, re.IGNORECASE):
# return True
# return False
# def get_crisis_resources(self, location: str = "global") -> Dict[str, Any]:
# """Get crisis resources based on location"""
# resources = {
# "global": {
# "name": "International Association for Suicide Prevention",
# "url": "https://www.iasp.info/resources/Crisis_Centres/",
# "text": "Find crisis centers worldwide"
# },
# "us": {
# "name": "988 Suicide & Crisis Lifeline",
# "phone": "988",
# "text": "Text HOME to 741741",
# "url": "https://988lifeline.org/"
# },
# "uk": {
# "name": "Samaritans",
# "phone": "116 123",
# "email": "jo@samaritans.org",
# "url": "https://www.samaritans.org/"
# },
# "india": {
# "name": "National Suicide Prevention Helpline",
# "phone": "91-9820466726",
# "additional": "Vandrevala Foundation: 9999666555"
# },
# "australia": {
# "name": "Lifeline",
# "phone": "13 11 14",
# "text": "Text 0477 13 11 14",
# "url": "https://www.lifeline.org.au/"
# }
# }
# return resources.get(location.lower(), resources["global"])
#from .base_tool import BaseTool
#from crewai_tools import BaseTool
class ValidateResponseTool(BaseTool):
name: str = "validate_response"
description: str = "Validates safety and helpfulness."
model_config = {"arbitrary_types_allowed": True}
_config: object = PrivateAttr()
def __init__(self, config=None, **data):
super().__init__(**data)
self._config = config
# ... any required initialization ...
def _run(self, response: str, context: dict = None):
# Place your actual validation logic here, include dummy for illustration
# For full validation logic, use your own code!
# """Result of validation check"""
is_valid: bool
issues: List[str]
warnings: List[str]
suggestions: List[str]
confidence: float
refined_text: Optional[str] = None
return {"is_valid", "issues", "warnings", "suggestions","confidence","refined_text"}
class ValidationTools:
#_model: ValidateResponseTool = PrivateAttr()
def __init__(self, config=None):
self._validate_response = ValidateResponseTool(config)
# Add more tools as needed (check_safety, refine_response, etc.)
# # Initialize sentiment analyzer for tone checking
self.sentiment_analyzer = pipeline(
"sentiment-analysis",
model="nlptown/bert-base-multilingual-uncased-sentiment",
device=0 if torch.cuda.is_available() else -1
)
# Prohibited patterns for different categories
self.prohibited_patterns = {
'medical': [
r'\b(?:diagnos|prescrib|medicat|cure|treat|therap)\w*\b',
r'\b(?:disease|illness|disorder|syndrome)\s+(?:is|are|can be)\b',
r'\b(?:take|consume|dose|dosage)\s+\d+\s*(?:mg|ml|pill|tablet)',
r'\b(?:medical|clinical|physician|doctor)\s+(?:advice|consultation|opinion)',
],
'legal': [
r'\b(?:legal advice|lawsuit|sue|court|litigation)\b',
r'\b(?:illegal|unlawful|crime|criminal|prosecut)\w*\b',
r'\b(?:you should|must|have to)\s+(?:sign|agree|consent|contract)',
r'\b(?:rights|obligations|liability|damages)\s+(?:are|include)\b',
],
'financial': [
r'\b(?:invest|buy|sell|trade)\s+(?:stock|crypto|bitcoin|forex)\b',
r'\b(?:guaranteed|promise)\s+(?:return|profit|income|earnings)\b',
r'\b(?:financial advisor|investment advice|trading strategy)\b',
r'\b(?:tax|accounting|financial planning)\s+(?:advice|consultation)',
],
'harmful': [
r'\b(?:suicide|suicidal|kill\s+(?:your|my)self|end\s+(?:it|life))\b',
r'\b(?:self[\-\s]?harm|hurt\s+(?:your|my)self|cutting)\b',
r'\b(?:violence|violent|weapon|attack|assault)\b',
r'\b(?:hate|discriminat|racist|sexist|homophobic)\b',
],
'absolute': [
r'\b(?:always|never|every|all|none|no one|everyone)\s+(?:will|must|should|is|are)\b',
r'\b(?:definitely|certainly|guaranteed|assured|promise)\b',
r'\b(?:only way|only solution|must do|have to)\b',
]
}
# Required elements for supportive responses
self.supportive_elements = {
'empathy': [
'understand', 'hear', 'feel', 'acknowledge', 'recognize',
'appreciate', 'empathize', 'relate', 'comprehend'
],
'validation': [
'valid', 'normal', 'understandable', 'natural', 'okay',
'reasonable', 'makes sense', 'legitimate'
],
'support': [
'support', 'help', 'here for you', 'together', 'alongside',
'assist', 'guide', 'accompany', 'with you'
],
'hope': [
'can', 'possible', 'able', 'capable', 'potential',
'opportunity', 'growth', 'improve', 'better', 'progress'
],
'empowerment': [
'choice', 'decide', 'control', 'power', 'strength',
'agency', 'capable', 'resource', 'ability'
]
}
# Crisis indicators
self.crisis_indicators = [
r'\b(?:want|going|plan)\s+to\s+(?:die|kill|end)\b',
r'\b(?:no reason|point|hope)\s+(?:to|in)\s+(?:live|living|life)\b',
r'\b(?:better off|world)\s+without\s+me\b',
r'\bsuicide\s+(?:plan|method|attempt)\b',
r'\b(?:final|last)\s+(?:goodbye|letter|message)\b'
]
# Tone indicators
self.negative_tone_words = [
'stupid', 'idiot', 'dumb', 'pathetic', 'worthless',
'loser', 'failure', 'weak', 'incompetent', 'useless'
]
self.dismissive_phrases = [
'just get over it', 'stop complaining', 'not a big deal',
'being dramatic', 'overreacting', 'too sensitive'
]
def validate_response(self, response: str, context: Dict[str, Any] = None) -> ValidationResult:
"""Comprehensive validation of response"""
issues = []
warnings = []
suggestions = []
# Check for prohibited content
prohibited_check = self._check_prohibited_content(response)
if prohibited_check["found"]:
issues.extend(prohibited_check["violations"])
suggestions.extend(prohibited_check["suggestions"])
# Check tone and sentiment
tone_check = self._check_tone(response)
if not tone_check["appropriate"]:
warnings.extend(tone_check["issues"])
suggestions.extend(tone_check["suggestions"])
# Check for supportive elements
support_check = self._check_supportive_elements(response)
if support_check["missing"]:
warnings.append(f"Missing supportive elements: {', '.join(support_check['missing'])}")
suggestions.extend(support_check["suggestions"])
# Check for crisis content in context
if context and context.get("user_input"):
crisis_check = self._check_crisis_indicators(context["user_input"])
if crisis_check["is_crisis"] and "crisis" not in response.lower():
warnings.append("User may be in crisis but response doesn't address this")
suggestions.append("Include crisis resources and immediate support options")
# Calculate overall confidence
confidence = self._calculate_confidence(issues, warnings)
# Generate refined response if needed
refined_text = None
if issues or (warnings and confidence < 0.7):
refined_text = self._refine_response(response, issues, warnings, suggestions)
return ValidationResult(
is_valid=len(issues) == 0,
issues=issues,
warnings=warnings,
suggestions=suggestions,
confidence=confidence,
refined_text=refined_text
)
def _check_prohibited_content(self, text: str) -> Dict[str, Any]:
"""Check for prohibited content patterns"""
found_violations = []
suggestions = []
for category, patterns in self.prohibited_patterns.items():
for pattern in patterns:
if re.search(pattern, text, re.IGNORECASE):
found_violations.append(f"Contains {category} advice/content")
# Add specific suggestions
if category == "medical":
suggestions.append("Replace with: 'Consider speaking with a healthcare professional'")
elif category == "legal":
suggestions.append("Replace with: 'For legal matters, consult with a qualified attorney'")
elif category == "financial":
suggestions.append("Replace with: 'For financial decisions, consider consulting a financial advisor'")
elif category == "harmful":
suggestions.append("Include crisis resources and express immediate concern for safety")
elif category == "absolute":
suggestions.append("Use qualifying language like 'often', 'might', 'could' instead of absolutes")
break
return {
"found": len(found_violations) > 0,
"violations": found_violations,
"suggestions": suggestions
}
def _check_tone(self, text: str) -> Dict[str, Any]:
"""Check the tone and sentiment of the response"""
issues = []
suggestions = []
# Check sentiment
try:
sentiment_result = self.sentiment_analyzer(text[:512])[0] # Limit length for model
sentiment_score = sentiment_result['score']
sentiment_label = sentiment_result['label']
# Check if too negative
if '1' in sentiment_label or '2' in sentiment_label: # 1-2 stars = negative
issues.append("Response tone is too negative")
suggestions.append("Add more supportive and hopeful language")
except:
pass
# Check for negative words
text_lower = text.lower()
found_negative = [word for word in self.negative_tone_words if word in text_lower]
if found_negative:
issues.append(f"Contains negative/judgmental language: {', '.join(found_negative)}")
suggestions.append("Replace judgmental terms with supportive language")
# Check for dismissive phrases
found_dismissive = [phrase for phrase in self.dismissive_phrases if phrase in text_lower]
if found_dismissive:
issues.append("Contains dismissive language")
suggestions.append("Acknowledge and validate the person's feelings instead")
return {
"appropriate": len(issues) == 0,
"issues": issues,
"suggestions": suggestions
}
def _check_supportive_elements(self, text: str) -> Dict[str, Any]:
"""Check for presence of supportive elements"""
text_lower = text.lower()
missing_elements = []
suggestions = []
element_scores = {}
for element, keywords in self.supportive_elements.items():
found = any(keyword in text_lower for keyword in keywords)
element_scores[element] = found
if not found:
missing_elements.append(element)
# Generate suggestions for missing elements
if 'empathy' in missing_elements:
suggestions.append("Add empathetic language like 'I understand how difficult this must be'")
if 'validation' in missing_elements:
suggestions.append("Validate their feelings with phrases like 'Your feelings are completely valid'")
if 'support' in missing_elements:
suggestions.append("Express support with 'I'm here to support you through this'")
if 'hope' in missing_elements:
suggestions.append("Include hopeful elements about growth and positive change")
if 'empowerment' in missing_elements:
suggestions.append("Emphasize their agency and ability to make choices")
return {
"missing": missing_elements,
"present": [k for k, v in element_scores.items() if v],
"suggestions": suggestions
}
def _check_crisis_indicators(self, text: str) -> Dict[str, Any]:
"""Check for crisis indicators in text"""
for pattern in self.crisis_indicators:
if re.search(pattern, text, re.IGNORECASE):
return {
"is_crisis": True,
"pattern_matched": pattern,
"action": "Immediate crisis response needed"
}
return {"is_crisis": False}
def _calculate_confidence(self, issues: List[str], warnings: List[str]) -> float:
"""Calculate confidence score for validation"""
if issues:
return 0.3 - (0.1 * len(issues)) # Major issues severely impact confidence
confidence = 1.0
confidence -= 0.1 * len(warnings) # Each warning reduces confidence
return max(0.0, confidence)
def _refine_response(self, response: str, issues: List[str], warnings: List[str], suggestions: List[str]) -> str:
"""Attempt to refine the response based on issues found"""
refined = response
# Add disclaimer for professional advice
if any('advice' in issue for issue in issues):
disclaimer = "\n\n*Please note: I'm here to provide support and guidance, but for specific professional matters, it's important to consult with qualified professionals.*"
if disclaimer not in refined:
refined += disclaimer
# Add crisis resources if needed
if any('crisis' in warning for warning in warnings):
crisis_text = "\n\n**If you're in crisis, please reach out for immediate help:**\n- Crisis Hotline: 988 (US)\n- Crisis Text Line: Text HOME to 741741\n- International: findahelpline.com"
if crisis_text not in refined:
refined += crisis_text
# Add supportive closing if missing hope
if any('hope' in warning for warning in warnings):
hopeful_closing = "\n\nRemember, you have the strength to navigate this challenge, and positive change is possible. I'm here to support you on this journey."
if not any(phrase in refined.lower() for phrase in ['journey', 'strength', 'possible']):
refined += hopeful_closing
return refined
def validate_user_input(self, text: str) -> ValidationResult:
"""Validate user input for safety and process-ability"""
issues = []
warnings = []
suggestions = []
# Check if empty
if not text or not text.strip():
issues.append("Empty input received")
suggestions.append("Please share what's on your mind")
return ValidationResult(False, issues, warnings, suggestions, 0.0)
# Check length
if len(text) > 5000:
warnings.append("Input is very long")
suggestions.append("Consider breaking this into smaller parts")
# Check for crisis indicators
crisis_check = self._check_crisis_indicators(text)
if crisis_check["is_crisis"]:
warnings.append("Crisis indicators detected")
suggestions.append("Prioritize safety and provide crisis resources")
# Check for spam/repetition
if self._is_spam(text):
issues.append("Input appears to be spam or repetitive")
suggestions.append("Please share genuine thoughts or concerns")
confidence = self._calculate_confidence(issues, warnings)
return ValidationResult(
is_valid=len(issues) == 0,
issues=issues,
warnings=warnings,
suggestions=suggestions,
confidence=confidence
)
def _is_spam(self, text: str) -> bool:
"""Simple spam detection"""
# Check for excessive repetition
words = text.lower().split()
if len(words) > 10:
unique_ratio = len(set(words)) / len(words)
if unique_ratio < 0.3: # Less than 30% unique words
return True
# Check for common spam patterns
spam_patterns = [
r'(?:buy|sell|click|visit)\s+(?:now|here|this)',
r'(?:congratulations|winner|prize|lottery)',
r'(?:viagra|pills|drugs|pharmacy)',
r'(?:$$|money\s+back|guarantee)'
]
for pattern in spam_patterns:
if re.search(pattern, text, re.IGNORECASE):
return True
return False
def get_crisis_resources(self, location: str = "global") -> Dict[str, Any]:
"""Get crisis resources based on location"""
resources = {
"global": {
"name": "International Association for Suicide Prevention",
"url": "https://www.iasp.info/resources/Crisis_Centres/",
"text": "Find crisis centers worldwide"
},
"us": {
"name": "988 Suicide & Crisis Lifeline",
"phone": "988",
"text": "Text HOME to 741741",
"url": "https://988lifeline.org/"
},
"uk": {
"name": "Samaritans",
"phone": "116 123",
"email": "jo@samaritans.org",
"url": "https://www.samaritans.org/"
},
"india": {
"name": "National Suicide Prevention Helpline",
"phone": "91-9820466726",
"additional": "Vandrevala Foundation: 9999666555"
},
"australia": {
"name": "Lifeline",
"phone": "13 11 14",
"text": "Text 0477 13 11 14",
"url": "https://www.lifeline.org.au/"
}
}
return resources.get(location.lower(), resources["global"]) |