Files
rag-technical-docs-assistant/tests/unit/test_grounded_voice_regression.py
T
amirhosein mazaheri 42400495af feat(backend): integrate document deletion and grounded speech providers
Enable replay-safe document deletion and public deployment model identifiers with the forward voice-model schema revision.

Add GapGPT dialogue and ElevenLabs speech routing, strict extractive grounding, ten-source retrieval and regression coverage.

Validation: 199 targeted provider-free tests passed. The full provider-free run stalled and was interrupted; PostgreSQL acceptance was not run because TEST_DATABASE_URL is unset.
2026-10-20 09:00:37 +03:30

89 lines
5.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from app.infrastructure.realtime import RealtimeAdapter
from app.modules.voice.local_s2s import setup_session
from tests.unit.test_local_s2s_phase2 import local_config
from app.modules.knowledge.evidence import admit_candidates
from tests.unit.test_search_phase2 import row
def test_phone_evidence_at_rank_eight_is_now_delivered_and_budget_is_bounded():
candidates=[row(i,text="unrelated" if i!=8 else "phone evidence") for i in range(1,14)]
sources=admit_candidates(candidates,.2)
assert len(sources)==10
assert sources[7]['text']=='phone evidence'
assert sum(len(r['text']) for r in sources)<=12000
def test_local_and_openai_use_current_turn_evidence_only_policy():
for session in (RealtimeAdapter(None).setup()['session'],setup_session(local_config())):
instructions=session['instructions']
assert 'MANDATORY EVIDENCE-ONLY ANSWERING' in instructions
assert 'CURRENT turn' in instructions
assert 'Read all returned passages' in instructions
assert 'You cannot arrange or promise calls' in instructions
assert 'Never invent today' in instructions
assert 'Missing prices must not be guessed' in instructions
import json
import pytest
from services.local_s2s.grounding import safe_text,guard_response,FALLBACK
def grounded_messages(answer='شماره مرکز شرکت 031 - 3125 است.'):
return [{'role':'user','content':'شماره تماس شرکت؟'},
{'role':'assistant','tool_calls':[{'id':'search','function':{'name':'search_knowledge','arguments':'{}'}}]},
{'role':'tool','tool_call_id':'search','content':json.dumps({'status':'ok','sources':[{'source_ref':'S1','text':'سؤال: الان تعطیله؟\nپاسخ: '+answer}]})},
{'role':'assistant','tool_calls':[{'id':'report','function':{'name':'report_used_sources','arguments':json.dumps({'source_refs':['S1']})}}]},
{'role':'tool','tool_call_id':'report','content':'{"status":"ok"}'}]
def test_gate_admits_literal_answer_and_blocks_added_facts_and_question_premise():
messages=grounded_messages()
for invented in ('شماره شرکت 031-9999 است.','ساعت کاری ۷:۳۰ تا ۱۴:۳۰ است.','وقت ملاقات هماهنگ می‌کنم.','الان تعطیله؟','شماره مرکز شرکت 031 - 3125 است. پنجشنبه تعطیل است.'):
assert safe_text(invented,messages)=='شماره مرکز شرکت 031 - 3125 است.'
assert safe_text('شماره مرکز شرکت 031 - 3125 است.',messages)=='شماره مرکز شرکت 031 - 3125 است.'
def test_gate_refuses_old_turn_unreported_sources_and_prior_assistant_facts():
messages=grounded_messages()
text='شماره مرکز شرکت 031 - 3125 است.'
assert safe_text(text,messages+[{'role':'user','content':'موضوع جدید'}])==FALLBACK
assert safe_text(text,messages[:3])==FALLBACK
assert safe_text(text,[{'role':'user','content':'شماره؟'},{'role':'assistant','content':text}])==FALLBACK
def test_stream_is_buffered_and_replaced_before_unsupported_words_can_reach_tts():
events=[{'id':'fixture','choices':[{'index':0,'delta':{'content':part}}]} for part in ['ساعت کاری ','۷:۳۰ تا ۱۴:۳۰ است.']]
raw=(''.join('data: '+json.dumps(e)+'\n\n' for e in events)+'data: [DONE]\n\n').encode()
result=guard_response(raw,'text/event-stream',grounded_messages()).decode()
assert 'شماره مرکز شرکت 031 - 3125 است.' in result and '۷:۳۰' not in result
with pytest.raises(ValueError):guard_response(raw.replace(b'data: [DONE]\n\n',b''),'text/event-stream',grounded_messages())
def test_stream_tool_calls_survive_without_unverified_assistant_preface():
event={'choices':[{'delta':{'content':'unsupported preface','tool_calls':[{'index':0,'id':'a','function':{'name':'search_knowledge','arguments':'{}'}}]}}]}
raw=('data: '+json.dumps(event)+'\n\ndata: [DONE]\n\n').encode()
result=guard_response(raw,'text/event-stream',[])
assert b'unsupported preface' not in result and b'search_knowledge' in result
def test_gateway_applies_extractive_gate_to_stream_before_forwarding():
import asyncio,httpx
from services.local_s2s.components import ComponentServer
async def scenario():
class Writer:
def __init__(self):self.data=bytearray()
def write(self,data):self.data.extend(data)
async def drain(self):pass
event={'id':'fixture','choices':[{'index':0,'delta':{'content':'وقت ملاقات هماهنگ می‌کنم.'}}]}
raw=('data: '+json.dumps(event)+'\n\ndata: [DONE]\n\n').encode()
server=ComponentServer('fixture',port=0,provider='gapgpt',strict_grounding=True)
server.loop=asyncio.get_running_loop();responses=[];writer=Writer()
try:
async with httpx.AsyncClient(transport=httpx.MockTransport(lambda r:httpx.Response(200,headers={'content-type':'text/event-stream'},content=raw))) as client:
await server._forward(client,writer,'/v1/chat/completions',{'content-type':'application/json'},json.dumps({'model':'gpt-4.1-mini','messages':grounded_messages()}).encode(),responses)
assert 'وقت ملاقات'.encode() not in writer.data
assert 'شماره مرکز شرکت 031 - 3125 است.'.encode() in writer.data
finally:
for response in responses:await response.aclose()
server.server_close()
asyncio.run(scenario())