Spaces:
Sleeping
Sleeping
Update utils/guardrails.py
Browse files- utils/guardrails.py +69 -0
utils/guardrails.py
CHANGED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Input and output validation for the Financial QA system.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
def validate_input(query: str) -> tuple[bool, str]:
|
| 6 |
+
"""
|
| 7 |
+
Validate user input query.
|
| 8 |
+
|
| 9 |
+
Args:
|
| 10 |
+
query: User's question
|
| 11 |
+
|
| 12 |
+
Returns:
|
| 13 |
+
Tuple of (is_valid, message)
|
| 14 |
+
"""
|
| 15 |
+
# Check if query is empty
|
| 16 |
+
if not query.strip():
|
| 17 |
+
return False, "Please enter a question."
|
| 18 |
+
|
| 19 |
+
# Check minimum length
|
| 20 |
+
if len(query.split()) < 2:
|
| 21 |
+
return False, "Please enter a complete question."
|
| 22 |
+
|
| 23 |
+
# Check if query is finance-related
|
| 24 |
+
financial_keywords = [
|
| 25 |
+
'revenue', 'profit', 'loss', 'income', 'expense',
|
| 26 |
+
'asset', 'liability', 'equity', 'cash', 'stock',
|
| 27 |
+
'share', 'dividend', 'market', 'financial', 'fiscal',
|
| 28 |
+
'quarter', 'annual', 'balance', 'statement', 'report',
|
| 29 |
+
'earnings', 'cost', 'price', 'allstate', 'insurance'
|
| 30 |
+
]
|
| 31 |
+
|
| 32 |
+
if not any(keyword.lower() in query.lower() for keyword in financial_keywords):
|
| 33 |
+
return False, "Please ask a finance-related question about Allstate."
|
| 34 |
+
|
| 35 |
+
return True, ""
|
| 36 |
+
|
| 37 |
+
def validate_output(answer: str, confidence: float) -> tuple[bool, str]:
|
| 38 |
+
"""
|
| 39 |
+
Validate model output.
|
| 40 |
+
|
| 41 |
+
Args:
|
| 42 |
+
answer: Generated answer
|
| 43 |
+
confidence: Model's confidence score
|
| 44 |
+
|
| 45 |
+
Returns:
|
| 46 |
+
Tuple of (is_valid, message)
|
| 47 |
+
"""
|
| 48 |
+
# Check if answer is empty
|
| 49 |
+
if not answer.strip():
|
| 50 |
+
return False, "No answer generated."
|
| 51 |
+
|
| 52 |
+
# Check if confidence is too low
|
| 53 |
+
if confidence < 0.3:
|
| 54 |
+
return False, "Low confidence in answer. Please rephrase your question."
|
| 55 |
+
|
| 56 |
+
# Check for potential hallucination markers
|
| 57 |
+
hallucination_markers = [
|
| 58 |
+
"I don't know",
|
| 59 |
+
"I'm not sure",
|
| 60 |
+
"I cannot",
|
| 61 |
+
"I don't have",
|
| 62 |
+
"not available",
|
| 63 |
+
"no information"
|
| 64 |
+
]
|
| 65 |
+
|
| 66 |
+
if any(marker.lower() in answer.lower() for marker in hallucination_markers):
|
| 67 |
+
return False, "Unable to find relevant information in the financial documents."
|
| 68 |
+
|
| 69 |
+
return True, ""
|