fix(support-chat): allow safe Canina research and contact links
Deploy Canina / deploy (push) Failing after 31s
Deploy Canina / deploy (push) Failing after 31s
This commit is contained in:
1 parent
f292195edf
commit
043488fe55
3 files changed
+83
-56
No files matched your search
@@ -9,6 +9,8 @@ import hmac
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import urllib.request
|
||||
import uuid
|
||||
from aiohttp import web
|
||||
from policy import validate_message, safe_answer, research_query, safe_intent
|
||||
@@ -29,18 +31,28 @@ async def catalog(request):
|
||||
UNAVAILABLE = 'پشتیبان هوشمند فعلاً در دسترس نیست. لطفاً کمی بعد دوباره تلاش کنید یا تیکت پشتیبانی ثبت کنید.'
|
||||
DOMAIN = 'فقط درباره محصولات و سلامت حیوانات خانگی و خدمات کنینا پاسخ میدهم. پیوند دلخواه یا موضوع خارج از این حوزه پذیرفته نمیشود.'
|
||||
LIMIT = asyncio.Semaphore(2)
|
||||
|
||||
def live_contact_context():
|
||||
request = urllib.request.Request('https://canina.ir/contact', headers={'User-Agent': 'CaninaSupport/1.0'})
|
||||
with urllib.request.urlopen(request, timeout=8) as response:
|
||||
html = response.read(300000).decode('utf-8', 'ignore')
|
||||
phones = sorted(set(re.findall(r'(?:tel:|\b0?21[ -]?\d{4}[ -]?\d{4})', html, re.I)))
|
||||
phones = [re.sub(r'^tel:\s*', '', p, flags=re.I).replace(' ', '').replace('-', '') for p in phones]
|
||||
return {'source': 'https://canina.ir/contact', 'phones': phones[:5]}
|
||||
logging.disable(logging.CRITICAL)
|
||||
|
||||
def answer_once(message, catalog, selection):
|
||||
def answer_once(message, catalog, selection, page_context=None, conversation_history=None):
|
||||
model, runtime = selected_runtime(selection)
|
||||
research = None
|
||||
query = research_query(message)
|
||||
if query:
|
||||
# No model-chosen tool arguments, raw queries, URL extraction or fetch.
|
||||
from tools.web_tools import web_search_tool
|
||||
payload = json.loads(web_search_tool(query, limit=3))
|
||||
if payload.get('success') is not True or payload.get('error'): raise ValueError('research unavailable')
|
||||
research = [{k: str(row.get(k, ''))[:1800] for k in ['title', 'description', 'url']} for row in payload.get('data', {}).get('web', [])[:3]]
|
||||
if query == 'Canina official contact phone address':
|
||||
research = [live_contact_context()]
|
||||
else:
|
||||
from tools.web_tools import web_search_tool
|
||||
payload = json.loads(web_search_tool(query, limit=3))
|
||||
if payload.get('success') is not True or payload.get('error'): raise ValueError('research unavailable')
|
||||
research = [{k: str(row.get(k, ''))[:1800] for k in ['title', 'description', 'url']} for row in payload.get('data', {}).get('web', [])[:3]]
|
||||
agent = AIAgent(model=model.get('default'), provider=runtime.get('provider'), base_url=runtime.get('base_url'), api_key=runtime.get('api_key'), api_mode=runtime.get('api_mode'), enabled_toolsets=[], disabled_toolsets=['all'], skip_memory=True, skip_context_files=True, skip_background_review=True, load_soul_identity=False, session_id=str(uuid.uuid4()), session_db=None, save_trajectories=False, quiet_mode=True, max_iterations=2, max_tokens=1800, run_budget_seconds=35, checkpoints_enabled=False)
|
||||
agent._persist_disabled = True
|
||||
# Runtime assertion protects against future changes to empty toolset defaults.
|
||||
@@ -56,7 +68,7 @@ def answer_once(message, catalog, selection):
|
||||
'۵. ساختار خروجی: فقط و فقط یک شیء JSON با دقیقاً یک کلید "answer" برگردانید و هیچ متن اضافی قبل یا بعد از JSON نیاورید.'
|
||||
)
|
||||
try:
|
||||
result = agent.run_conversation(json.dumps({'question': message, 'catalog': catalog, 'untrusted_research': research}, ensure_ascii=False), system_message=prompt, conversation_history=[])
|
||||
result = agent.run_conversation(json.dumps({'question': message, 'catalog': catalog, 'untrusted_research': research, 'page_context': page_context or {}, 'conversation_history': (conversation_history or [])[-20:]}, ensure_ascii=False), system_message=prompt, conversation_history=[])
|
||||
return safe_answer(result)
|
||||
finally:
|
||||
with contextlib.suppress(Exception): agent.close()
|
||||
@@ -83,7 +95,7 @@ async def classify(request):
|
||||
return web.json_response({'answer': UNAVAILABLE}, status=401)
|
||||
try:
|
||||
data = await request.json()
|
||||
if not isinstance(data, dict) or set(data) != {'message', 'selection'}: raise ValueError('payload')
|
||||
if not isinstance(data, dict) or set(data) - {'message', 'selection', 'conversation_history'} or not {'message', 'selection'} <= set(data): raise ValueError('payload')
|
||||
message = validate_message(data['message'])
|
||||
except Exception:
|
||||
return web.json_response({'answer': DOMAIN}, status=400)
|
||||
@@ -101,14 +113,14 @@ async def ask(request):
|
||||
return web.json_response({'answer': UNAVAILABLE}, status=401)
|
||||
try:
|
||||
data = await request.json()
|
||||
if set(data) != {'message','catalog', 'selection'} or not isinstance(data['catalog'], list) or len(data['catalog']) > 80: raise ValueError('payload')
|
||||
if set(data) - {'message','catalog','selection','page_context','conversation_history'} or not {'message','catalog','selection'} <= set(data) or not isinstance(data['catalog'], list) or len(data['catalog']) > 80: raise ValueError('payload')
|
||||
message = validate_message(data['message'])
|
||||
except Exception:
|
||||
return web.json_response({'answer': DOMAIN}, status=400)
|
||||
if LIMIT.locked(): return web.json_response({'answer': UNAVAILABLE}, status=503)
|
||||
try:
|
||||
async with LIMIT:
|
||||
answer = await asyncio.to_thread(answer_once, message, data['catalog'], data['selection'])
|
||||
answer = await asyncio.to_thread(answer_once, message, data['catalog'], data['selection'], data.get('page_context'), data.get('conversation_history'))
|
||||
return web.json_response({'answer': answer}, headers={'Cache-Control':'no-store'})
|
||||
except Exception:
|
||||
return web.json_response({'answer': UNAVAILABLE}, status=503)
|
||||
|
||||
Reference in new issue
Block a user