Spaces:
Sleeping
Sleeping
Update src/utils/response_processor.py
Browse files- src/utils/response_processor.py +80 -29
src/utils/response_processor.py
CHANGED
|
@@ -3,25 +3,49 @@ import time
|
|
| 3 |
from ..knowledge_base.grounding_truth import GroundingTruth
|
| 4 |
|
| 5 |
# Try to import generic responder for multi-perspective optimization
|
|
|
|
| 6 |
try:
|
| 7 |
from codette_responder_generic import get_generic_responder
|
| 8 |
GENERIC_RESPONDER_AVAILABLE = True
|
| 9 |
except ImportError:
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
class ResponseProcessor:
|
| 13 |
"""
|
| 14 |
Processes and verifies AI responses using the grounding truth system
|
| 15 |
-
and optimizes perspective selection with the generic responder
|
|
|
|
|
|
|
|
|
|
| 16 |
"""
|
| 17 |
|
| 18 |
def __init__(self):
|
| 19 |
self.grounding_truth = GroundingTruth()
|
| 20 |
self.context_history = []
|
| 21 |
self.generic_responder = get_generic_responder() if GENERIC_RESPONDER_AVAILABLE else None
|
|
|
|
| 22 |
self.user_id = "anonymous" # Can be set per session
|
| 23 |
|
| 24 |
-
def process_response(self, query: str, response: str, context: Optional[str] = None
|
|
|
|
| 25 |
"""
|
| 26 |
Process and verify a response using grounding truth and multi-perspective optimization
|
| 27 |
|
|
@@ -29,11 +53,22 @@ class ResponseProcessor:
|
|
| 29 |
query: The original user query
|
| 30 |
response: The generated response
|
| 31 |
context: Optional context category
|
|
|
|
| 32 |
|
| 33 |
Returns:
|
| 34 |
-
Processed and verified response
|
| 35 |
"""
|
| 36 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
perspective_analysis = None
|
| 38 |
if self.generic_responder:
|
| 39 |
try:
|
|
@@ -47,33 +82,46 @@ class ResponseProcessor:
|
|
| 47 |
# Generic responder is optional; if it fails, continue processing
|
| 48 |
pass
|
| 49 |
|
| 50 |
-
# Split response into statements for verification
|
| 51 |
statements = self._split_into_statements(response)
|
| 52 |
|
| 53 |
verified_statements = []
|
| 54 |
uncertain_statements = []
|
| 55 |
|
| 56 |
-
# Verify each statement
|
| 57 |
for statement in statements:
|
| 58 |
verification = self.grounding_truth.verify_statement(statement, context)
|
| 59 |
|
| 60 |
if verification["verified"]:
|
| 61 |
verified_statements.append(statement)
|
| 62 |
else:
|
| 63 |
-
# Add confidence qualifier
|
| 64 |
qualified_statement = self._add_qualifier(statement, verification["confidence"])
|
| 65 |
uncertain_statements.append(qualified_statement)
|
| 66 |
|
| 67 |
-
# Reconstruct response with proper qualifiers
|
| 68 |
processed_response = self._construct_response(
|
| 69 |
query, verified_statements, uncertain_statements
|
| 70 |
)
|
| 71 |
|
| 72 |
return processed_response
|
| 73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
def _enhance_with_perspectives(self, response: str, perspectives: List[Dict]) -> str:
|
| 75 |
"""
|
| 76 |
-
Enhance response with multi-perspective
|
| 77 |
|
| 78 |
Args:
|
| 79 |
response: The original response
|
|
@@ -82,7 +130,7 @@ class ResponseProcessor:
|
|
| 82 |
Returns:
|
| 83 |
Response with perspective context (optional enhancement)
|
| 84 |
"""
|
| 85 |
-
# Optional: Add subtle perspective
|
| 86 |
# For now, just return original response; perspectives are used for learning
|
| 87 |
return response
|
| 88 |
|
|
@@ -105,17 +153,17 @@ class ResponseProcessor:
|
|
| 105 |
return statements
|
| 106 |
|
| 107 |
def _add_qualifier(self, statement: str, confidence: float) -> str:
|
| 108 |
-
"""Add appropriate qualifier based on confidence level"""
|
| 109 |
if confidence >= 0.8:
|
| 110 |
-
return f"{statement}
|
| 111 |
elif confidence >= 0.6:
|
| 112 |
-
return f"{statement} (
|
| 113 |
elif confidence >= 0.4:
|
| 114 |
return f"{statement} (possibly)"
|
| 115 |
elif confidence >= 0.2:
|
| 116 |
-
return f"
|
| 117 |
else:
|
| 118 |
-
return f"I'm not
|
| 119 |
|
| 120 |
def _construct_response(
|
| 121 |
self,
|
|
@@ -123,30 +171,24 @@ class ResponseProcessor:
|
|
| 123 |
verified_statements: List[str],
|
| 124 |
uncertain_statements: List[str]
|
| 125 |
) -> str:
|
| 126 |
-
"""Construct final response with proper structure and qualifiers"""
|
| 127 |
response_parts = []
|
| 128 |
|
| 129 |
# Add verified information first
|
| 130 |
if verified_statements:
|
| 131 |
-
response_parts.append("Here's what I know for certain:")
|
| 132 |
response_parts.extend(verified_statements)
|
| 133 |
|
| 134 |
# Add uncertain information with clear separation
|
| 135 |
if uncertain_statements:
|
| 136 |
if verified_statements:
|
| 137 |
-
response_parts.append("
|
| 138 |
-
else:
|
| 139 |
-
response_parts.append("Based on my current understanding:")
|
| 140 |
response_parts.extend(uncertain_statements)
|
| 141 |
|
| 142 |
-
# Add general
|
| 143 |
-
if uncertain_statements:
|
| 144 |
-
response_parts.
|
| 145 |
-
"\nNote: Some parts of this response are based on my current understanding "
|
| 146 |
-
"and might need verification. Feel free to ask for clarification on specific points."
|
| 147 |
-
)
|
| 148 |
|
| 149 |
-
return "\n".join(response_parts)
|
| 150 |
|
| 151 |
def update_context(self, query: str, response: str):
|
| 152 |
"""Update context history for better response processing"""
|
|
@@ -197,4 +239,13 @@ class ResponseProcessor:
|
|
| 197 |
return feedback_result
|
| 198 |
|
| 199 |
except Exception as e:
|
| 200 |
-
return {"status": "error", "message": str(e)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
from ..knowledge_base.grounding_truth import GroundingTruth
|
| 4 |
|
| 5 |
# Try to import generic responder for multi-perspective optimization
|
| 6 |
+
GENERIC_RESPONDER_AVAILABLE = False
|
| 7 |
try:
|
| 8 |
from codette_responder_generic import get_generic_responder
|
| 9 |
GENERIC_RESPONDER_AVAILABLE = True
|
| 10 |
except ImportError:
|
| 11 |
+
try:
|
| 12 |
+
# Fallback: Try importing from parent directory
|
| 13 |
+
import sys
|
| 14 |
+
import os
|
| 15 |
+
parent_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
|
| 16 |
+
if parent_dir not in sys.path:
|
| 17 |
+
sys.path.insert(0, parent_dir)
|
| 18 |
+
from codette_responder_generic import get_generic_responder
|
| 19 |
+
GENERIC_RESPONDER_AVAILABLE = True
|
| 20 |
+
except ImportError:
|
| 21 |
+
get_generic_responder = None
|
| 22 |
+
|
| 23 |
+
# Import natural response enhancer
|
| 24 |
+
try:
|
| 25 |
+
from ..components.natural_response_enhancer import get_natural_enhancer
|
| 26 |
+
NATURAL_ENHANCER_AVAILABLE = True
|
| 27 |
+
except ImportError:
|
| 28 |
+
NATURAL_ENHANCER_AVAILABLE = False
|
| 29 |
+
|
| 30 |
|
| 31 |
class ResponseProcessor:
|
| 32 |
"""
|
| 33 |
Processes and verifies AI responses using the grounding truth system
|
| 34 |
+
and optimizes perspective selection with the generic responder.
|
| 35 |
+
|
| 36 |
+
Now includes natural response enhancement to preserve Codette's identity
|
| 37 |
+
while improving conversational naturalness.
|
| 38 |
"""
|
| 39 |
|
| 40 |
def __init__(self):
|
| 41 |
self.grounding_truth = GroundingTruth()
|
| 42 |
self.context_history = []
|
| 43 |
self.generic_responder = get_generic_responder() if GENERIC_RESPONDER_AVAILABLE else None
|
| 44 |
+
self.natural_enhancer = get_natural_enhancer() if NATURAL_ENHANCER_AVAILABLE else None
|
| 45 |
self.user_id = "anonymous" # Can be set per session
|
| 46 |
|
| 47 |
+
def process_response(self, query: str, response: str, context: Optional[str] = None,
|
| 48 |
+
confidence: float = 0.85) -> str:
|
| 49 |
"""
|
| 50 |
Process and verify a response using grounding truth and multi-perspective optimization
|
| 51 |
|
|
|
|
| 53 |
query: The original user query
|
| 54 |
response: The generated response
|
| 55 |
context: Optional context category
|
| 56 |
+
confidence: How confident the system is in this response (0-1)
|
| 57 |
|
| 58 |
Returns:
|
| 59 |
+
Processed and verified response with natural enhancement
|
| 60 |
"""
|
| 61 |
+
# Step 1: Natural enhancement (removes unnatural markers)
|
| 62 |
+
if self.natural_enhancer:
|
| 63 |
+
try:
|
| 64 |
+
response = self.natural_enhancer.enhance_response(
|
| 65 |
+
response, confidence=confidence, context={'domain': self._detect_domain(query)}
|
| 66 |
+
)
|
| 67 |
+
except Exception as e:
|
| 68 |
+
# Natural enhancer is optional; if it fails, continue processing
|
| 69 |
+
pass
|
| 70 |
+
|
| 71 |
+
# Step 2: Analyze query with generic responder to understand domain and select perspectives
|
| 72 |
perspective_analysis = None
|
| 73 |
if self.generic_responder:
|
| 74 |
try:
|
|
|
|
| 82 |
# Generic responder is optional; if it fails, continue processing
|
| 83 |
pass
|
| 84 |
|
| 85 |
+
# Step 3: Split response into statements for verification
|
| 86 |
statements = self._split_into_statements(response)
|
| 87 |
|
| 88 |
verified_statements = []
|
| 89 |
uncertain_statements = []
|
| 90 |
|
| 91 |
+
# Step 4: Verify each statement
|
| 92 |
for statement in statements:
|
| 93 |
verification = self.grounding_truth.verify_statement(statement, context)
|
| 94 |
|
| 95 |
if verification["verified"]:
|
| 96 |
verified_statements.append(statement)
|
| 97 |
else:
|
| 98 |
+
# Add confidence qualifier naturally
|
| 99 |
qualified_statement = self._add_qualifier(statement, verification["confidence"])
|
| 100 |
uncertain_statements.append(qualified_statement)
|
| 101 |
|
| 102 |
+
# Step 5: Reconstruct response with proper qualifiers
|
| 103 |
processed_response = self._construct_response(
|
| 104 |
query, verified_statements, uncertain_statements
|
| 105 |
)
|
| 106 |
|
| 107 |
return processed_response
|
| 108 |
|
| 109 |
+
def _detect_domain(self, query: str) -> str:
|
| 110 |
+
"""Detect the domain of the query for better context"""
|
| 111 |
+
query_lower = query.lower()
|
| 112 |
+
|
| 113 |
+
if any(word in query_lower for word in ['mix', 'eq', 'compress', 'audio', 'track', 'bpm', 'daw']):
|
| 114 |
+
return 'music'
|
| 115 |
+
elif any(word in query_lower for word in ['code', 'program', 'software', 'function', 'class']):
|
| 116 |
+
return 'programming'
|
| 117 |
+
elif any(word in query_lower for word in ['data', 'analysis', 'statistics', 'metric']):
|
| 118 |
+
return 'data'
|
| 119 |
+
else:
|
| 120 |
+
return 'general'
|
| 121 |
+
|
| 122 |
def _enhance_with_perspectives(self, response: str, perspectives: List[Dict]) -> str:
|
| 123 |
"""
|
| 124 |
+
Enhance response with multi-perspective context subtly
|
| 125 |
|
| 126 |
Args:
|
| 127 |
response: The original response
|
|
|
|
| 130 |
Returns:
|
| 131 |
Response with perspective context (optional enhancement)
|
| 132 |
"""
|
| 133 |
+
# Optional: Add subtle perspective diversity hints without markers
|
| 134 |
# For now, just return original response; perspectives are used for learning
|
| 135 |
return response
|
| 136 |
|
|
|
|
| 153 |
return statements
|
| 154 |
|
| 155 |
def _add_qualifier(self, statement: str, confidence: float) -> str:
|
| 156 |
+
"""Add appropriate qualifier based on confidence level - naturally"""
|
| 157 |
if confidence >= 0.8:
|
| 158 |
+
return f"{statement}" # No qualifier needed for high confidence
|
| 159 |
elif confidence >= 0.6:
|
| 160 |
+
return f"{statement} (likely)"
|
| 161 |
elif confidence >= 0.4:
|
| 162 |
return f"{statement} (possibly)"
|
| 163 |
elif confidence >= 0.2:
|
| 164 |
+
return f"I'm uncertain, but {statement.lower()}"
|
| 165 |
else:
|
| 166 |
+
return f"I'm not sure about this, but {statement.lower()}"
|
| 167 |
|
| 168 |
def _construct_response(
|
| 169 |
self,
|
|
|
|
| 171 |
verified_statements: List[str],
|
| 172 |
uncertain_statements: List[str]
|
| 173 |
) -> str:
|
| 174 |
+
"""Construct final response with proper structure and qualifiers - naturally"""
|
| 175 |
response_parts = []
|
| 176 |
|
| 177 |
# Add verified information first
|
| 178 |
if verified_statements:
|
|
|
|
| 179 |
response_parts.extend(verified_statements)
|
| 180 |
|
| 181 |
# Add uncertain information with clear separation
|
| 182 |
if uncertain_statements:
|
| 183 |
if verified_statements:
|
| 184 |
+
response_parts.append("") # Add spacing
|
|
|
|
|
|
|
| 185 |
response_parts.extend(uncertain_statements)
|
| 186 |
|
| 187 |
+
# Add general note if there are uncertain statements (less obtrusive)
|
| 188 |
+
if uncertain_statements and not verified_statements:
|
| 189 |
+
response_parts.insert(0, "Based on my current understanding:")
|
|
|
|
|
|
|
|
|
|
| 190 |
|
| 191 |
+
return "\n".join(response_parts).strip()
|
| 192 |
|
| 193 |
def update_context(self, query: str, response: str):
|
| 194 |
"""Update context history for better response processing"""
|
|
|
|
| 239 |
return feedback_result
|
| 240 |
|
| 241 |
except Exception as e:
|
| 242 |
+
return {"status": "error", "message": str(e)}
|
| 243 |
+
|
| 244 |
+
def evaluate_response_quality(self, response: str) -> Dict[str, Any]:
|
| 245 |
+
"""Evaluate response quality and naturalness"""
|
| 246 |
+
if self.natural_enhancer:
|
| 247 |
+
try:
|
| 248 |
+
return self.natural_enhancer.evaluate_response_naturalness(response)
|
| 249 |
+
except Exception as e:
|
| 250 |
+
return {"error": str(e)}
|
| 251 |
+
return {}
|