51 lines
2.5 KiB
Python
51 lines
2.5 KiB
Python
"""Fail-closed domain policy; the model is never given web or execution tools."""
|
|
import json
|
|
import re
|
|
|
|
# Structural & exploit denial only: prevent URLs/links and command/injection strings.
|
|
DENY = re.compile(r'https?[:/]|www\.|[a-z0-9-]+\.(?:com|net|org|ir|de|io)\b|\b(?:localhost|ssh|sql|shell|token|password|api[._-]?key)\b|رمز\s*عبور|توکن|دستور\s*سیستمی', re.I)
|
|
ERROR = re.compile(r'hermes|provider|api.?key|traceback|exception|authentication|rate.?limit|error|failed|ناموفق|خطای اتصال', re.I)
|
|
|
|
def validate_message(message):
|
|
if not isinstance(message, str):
|
|
raise ValueError('type')
|
|
stripped = message.strip()
|
|
if not (1 <= len(stripped) <= 1500):
|
|
raise ValueError('length')
|
|
if DENY.search(stripped):
|
|
raise ValueError('denied_pattern')
|
|
return stripped
|
|
|
|
def safe_answer(result):
|
|
if not isinstance(result, dict) or result.get('failed') or result.get('error') or result.get('partial') or result.get('completed') is False:
|
|
raise ValueError('unavailable')
|
|
text = result.get('final_response', '')
|
|
if not isinstance(text, str) or ERROR.search(text):
|
|
raise ValueError('unavailable')
|
|
if text.startswith('```'):
|
|
text = re.sub(r'^```(?:json)?\s*|\s*```$', '', text)
|
|
obj = json.loads(text)
|
|
answer = obj.get('answer')
|
|
if not isinstance(answer, str) or not (1 <= len(answer.strip()) <= 6000) or ERROR.search(answer):
|
|
raise ValueError('unavailable')
|
|
return answer.strip()
|
|
|
|
# Search input never contains raw customer prose: only fixed product-category terms
|
|
# and recognised pet-product brands. No extract/browser URL capability exists.
|
|
def research_query(message):
|
|
if not re.search(r'مقایسه|رقیب|جستجو|compare|research', message, re.I):
|
|
return None
|
|
validate_message(message)
|
|
brands = [name for pattern, name in [(r'رویال|royal', 'Royal Canin'), (r'بیفار|beaphar', 'Beaphar'), (r'وت.?اکسپرت|vet.?expert', 'VetExpert')] if re.search(pattern, message, re.I)]
|
|
return 'pet dog cat supplement product comparison Canina ' + ' '.join(brands)
|
|
|
|
|
|
|
|
def safe_intent(result):
|
|
if not isinstance(result, dict) or result.get('failed') or result.get('error') or result.get('partial') or result.get('completed') is False:
|
|
raise ValueError('unavailable')
|
|
obj = json.loads(result.get('final_response', ''))
|
|
if not isinstance(obj, dict) or set(obj) != {'intent'} or obj['intent'] not in ('public', 'orders', 'wallet'):
|
|
raise ValueError('intent')
|
|
return obj['intent']
|