feat(voice): implement local S2S retained history and provider selection
Add pinned CPU engine dependencies, retained interrupted-response history, provider admission, offline evaluation and isolated browser tooling. Record Phase 2 acceptance and Phase 3/4 preparation, bounded paid-test accounting and interruption incident findings. Human interruption acceptance, paired OpenAI evaluation and rollback remain pending.
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
"""Actual pinned Chat and SDK request inspection; HTTP is fixture-only."""
|
||||
import json
|
||||
from queue import Queue
|
||||
from threading import Event
|
||||
from types import SimpleNamespace
|
||||
import httpx
|
||||
from openai import OpenAI
|
||||
from openai.types.realtime import RealtimeConversationItemFunctionCall, RealtimeConversationItemFunctionCallOutput
|
||||
from services.local_s2s.history import RetainedHistory, MARKER
|
||||
from speech_to_speech.LLM.chat import Chat, make_user_message, make_assistant_message
|
||||
from speech_to_speech.LLM.chat_completions_language_model import ChatCompletionsApiModelHandler
|
||||
import speech_to_speech.LLM.base_openai_compatible_language_model as base
|
||||
from services.local_s2s.request_policy import install_client_policy
|
||||
|
||||
requests=[]
|
||||
def fixture(request):
|
||||
requests.append(json.loads(request.content))
|
||||
return httpx.Response(200,json={'id':'fixture','object':'chat.completion','created':0,
|
||||
'model':'fixture/llm','choices':[{'index':0,'message':{'role':'assistant','content':'fixture'},'finish_reason':'stop'}]})
|
||||
native_factory=base.OpenAI
|
||||
clients=[]
|
||||
def factory(*args,**kwargs):
|
||||
client=httpx.Client(transport=httpx.MockTransport(fixture),trust_env=False);clients.append(client)
|
||||
return OpenAI(*args,**kwargs,http_client=client)
|
||||
base.OpenAI=factory
|
||||
install_client_policy(base,SimpleNamespace(local_s2s_request_timeout_seconds=7,local_s2s_max_output_tokens=17))
|
||||
handler=ChatCompletionsApiModelHandler(Event(),Queue(),Queue(),setup_kwargs=dict(
|
||||
model_name='fixture/llm',device='cpu',base_url='http://127.0.0.1:9/v1',api_key='fixture',stream=False))
|
||||
try:
|
||||
for cancelled in (False,True):
|
||||
chat=Chat(10)
|
||||
previous=make_user_message('PRIOR_USER');chat.add_item(previous)
|
||||
valid=make_assistant_message('PRIOR_VALID_ANSWER');chat.add_item(valid)
|
||||
chat.add_item(RealtimeConversationItemFunctionCall(type='function_call',call_id='call_keep',name='search_knowledge',arguments='{}'))
|
||||
chat.add_item(RealtimeConversationItemFunctionCallOutput(type='function_call_output',call_id='call_keep',output='VALID_TOOL_RESULT'))
|
||||
question=make_user_message('SAME_QUESTION');chat.add_item(question)
|
||||
draft=make_assistant_message('UNHEARD_SENTINEL answer retained for repetition.');draft.id='native-draft'
|
||||
chat.add_provisional_generation_items('key',[draft],after_item_id=question.id)
|
||||
state=RetainedHistory();state.remember('response',[draft],['wire-item'],question.id)
|
||||
if cancelled:
|
||||
chat.rollback_provisional_generation('key')
|
||||
else:
|
||||
wire=make_assistant_message('wire');wire.id='wire-item'
|
||||
chat.bind_assistant_item_ids('key',[wire]);chat.finalize_provisional_generation('key')
|
||||
following=make_user_message('FOLLOWUP_USER');chat.add_item(following)
|
||||
request=dict(type='s2s.history.retain',event_id='op',session_id='backend',engine_session_id='native',
|
||||
generation=1,response_id='response',item_id='wire-item',content_index=0,audio_end_ms=100)
|
||||
before=chat.to_transformers_chat()
|
||||
for field,value in [('session_id',''),('engine_session_id','wrong'),('response_id','wrong'),('item_id','wrong'),('content_index',True),('audio_end_ms',-1)]:
|
||||
invalid=dict(request);invalid[field]=value
|
||||
try:state.apply(chat,invalid,'native')
|
||||
except ValueError:pass
|
||||
else:raise AssertionError('invalid repair accepted')
|
||||
assert chat.to_transformers_chat()==before
|
||||
receipt=state.apply(chat,request,'native')
|
||||
assert receipt['applied'] and receipt['history_revision']==1
|
||||
assert state.apply(chat,request,'native')==receipt
|
||||
messages=chat.to_transformers_chat()
|
||||
handler._request(messages,{})
|
||||
actual=requests[-1]['messages']
|
||||
serialized=json.dumps(actual)
|
||||
assert all(text in serialized for text in ('PRIOR_USER','PRIOR_VALID_ANSWER','SAME_QUESTION','FOLLOWUP_USER','VALID_TOOL_RESULT'))
|
||||
assert serialized.index('UNHEARD_SENTINEL')<serialized.index('FOLLOWUP_USER')
|
||||
retained=[m for m in actual if 'UNHEARD_SENTINEL' in str(m.get('content',''))]
|
||||
assert len(retained)==1 and MARKER in retained[0]['content']
|
||||
assert state.records['response']['items'][0].content[0].text.startswith('UNHEARD_SENTINEL')
|
||||
assert all(MARKER not in m['content'] for m in actual if m['role']=='user')
|
||||
print(json.dumps(dict(case='cancelled_active' if cancelled else 'completed_unplayed',
|
||||
next_actual_http_request_verified=True,raw_answer_retained=True,heard_delivery_claim=False,paid_calls=0)))
|
||||
# A new operation cannot attest an annotation that disappeared.
|
||||
with chat._lock:
|
||||
target=next(item for item in chat.buffer if getattr(item,'role',None)=='assistant' and any((part.text or '').startswith(MARKER) for part in item.content))
|
||||
target.content[0]=target.content[0].model_copy(update={'text':'CONTROLLED_STALE_REWRITE'})
|
||||
unchanged=chat.to_transformers_chat()
|
||||
try:state.apply(chat,dict(request,event_id='new-op'),'native')
|
||||
except ValueError:pass
|
||||
else:raise AssertionError('lost annotation attested')
|
||||
assert state.revision==1 and chat.to_transformers_chat()==unchanged
|
||||
chat.close()
|
||||
finally:
|
||||
handler.cleanup()
|
||||
for client in clients:client.close()
|
||||
Reference in New Issue
Block a user