"""Fail-closed, extractive answer gate before any local answer reaches TTS.""" import json import unicodedata FALLBACK = 'اطلاعات کافی برای پاسخ به این سؤال در مدارک بازیابی‌شده ندارم.' SAFE = {FALLBACK, 'سلام، بفرمایید.', 'سلام.', 'لطفاً موضوع درخواستتان را مشخص کنید.', 'لطفاً نام شهرک و نوع قرارداد را مشخص کنید.'} def normalized(value): return ' '.join(unicodedata.normalize('NFC', value).split()).strip(' .،؛:!?؟«»"') def evidence(messages): # Prior turns and assistant prose are never current evidence. start=max((i for i,m in enumerate(messages) if m.get('role')=='user'),default=len(messages)) calls={};sources={};reported=[] for message in messages[start+1:]: if message.get('role')=='assistant': for call in message.get('tool_calls') or []: calls[call.get('id')]=call.get('function',{}) elif message.get('role')=='tool': function=calls.get(message.get('tool_call_id'),{}) try:result=json.loads(message.get('content','')) except (ValueError,TypeError):continue if not isinstance(result,dict) or result.get('status')!='ok':continue if function.get('name') in ('search_knowledge','reuse_last_evidence'): for source in result.get('sources',[]): if isinstance(source,dict) and isinstance(source.get('text'),str):sources[source.get('source_ref')]=source['text'] elif function.get('name')=='report_used_sources': try:reported=json.loads(function.get('arguments','{}')).get('source_refs',[]) except (ValueError,TypeError):reported=[] return [sources[ref] for ref in reported if isinstance(ref,str) and ref in sources] def safe_text(answer,messages): if answer in SAFE:return answer candidate=normalized(answer) if not candidate:return FALLBACK passages=evidence(messages) for passage in passages: # FAQ questions are not evidence of their own premise. answer_only=passage.split('پاسخ:',1)[-1] if 'سؤال:' in passage else passage if candidate in normalized(answer_only):return answer # For one cited FAQ, use its actual answer rather than a generated paraphrase. # Do not choose another source, infer relevance from rank, or synthesize facts. if len(passages)==1 and 'سؤال:' in passages[0] and 'پاسخ:' in passages[0]: literal=passages[0].split('پاسخ:',1)[1].strip() if literal and len(literal)<=1200:return literal return FALLBACK def guard_response(raw,media,messages): if media=='application/json': data=json.loads(raw) for choice in data.get('choices',[]): message=choice['message'] message['content']=None if message.get('tool_calls') else safe_text(message.get('content') or '',messages) return json.dumps(data,ensure_ascii=False).encode() packets=[];done=False for line in raw.decode('utf-8').splitlines(): if not line.startswith('data:'):continue payload=line[5:].strip() if payload=='[DONE]':done=True;continue packets.append(json.loads(payload)) if not done or not packets:raise ValueError('Incomplete grounded response') choices=[c for p in packets for c in p.get('choices',[])] if any(c.get('delta',{}).get('tool_calls') for c in choices): for c in choices:c.get('delta',{}).pop('content',None) return (''.join('data: '+json.dumps(p,ensure_ascii=False)+'\n\n' for p in packets)+'data: [DONE]\n\n').encode() answer=''.join(c.get('delta',{}).get('content') or '' for c in choices) safe=safe_text(answer,messages) first=packets[0] base={key:first[key] for key in ('id','object','created','model') if key in first} content=dict(base,choices=[dict(index=0,delta=dict(role='assistant',content=safe),finish_reason=None)]) finish=dict(base,choices=[dict(index=0,delta={},finish_reason='stop')]) return ('data: '+json.dumps(content,ensure_ascii=False)+'\n\ndata: '+json.dumps(finish)+'\n\ndata: [DONE]\n\n').encode()