feat(backend): deliver Phase 3 document and voice integration
Add authenticated upload, review, retry and knowledge-selection HTTP flows with bounded JSON processing and frozen OCR policy. Preserve Gemini/OpenAI provider selection and fenced lifecycle semantics; retain FAQ preambles and uncertain vision candidates, and expose opt-in uncalibrated voice transport diagnostics. Include frontend integration examples, aligned contracts and deterministic regressions. Validation: 1767 provider-free tests passed; all 404 PostgreSQL scenarios have passing evidence across the documented runs.
This commit is contained in:
+52
-27
@@ -1,9 +1,9 @@
|
||||
"""V01-V04 and supervised, cookie-authenticated Gemini stream."""
|
||||
"""V01-V04 and supervised, cookie-authenticated selected-provider stream."""
|
||||
import asyncio
|
||||
from dataclasses import asdict
|
||||
import json
|
||||
import logging
|
||||
from typing import Annotated
|
||||
from typing import Annotated, Literal
|
||||
from uuid import UUID
|
||||
from fastapi import APIRouter, Depends, Response, WebSocket, WebSocketDisconnect
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
@@ -17,7 +17,8 @@ from app.modules.voice.runtime import VoiceRuntime
|
||||
from app.modules.voice.settings import RuntimeSettings
|
||||
from app.modules.voice.durable_tools import DurableTools
|
||||
from app.modules.voice import registry
|
||||
from app.infrastructure.gemini_live import GeminiLiveAdapter, connect_gemini
|
||||
from app.infrastructure.voice_provider import create_adapter
|
||||
from app.modules.voice.authority import authority_failure_code
|
||||
from app.modules.knowledge.calibration import load_cutoff
|
||||
from app.modules.knowledge.evidence import RETRIEVAL_POLICY
|
||||
from app.modules.documents.settings import IngestionSettings
|
||||
@@ -42,6 +43,7 @@ class LiveSessionResponse(BaseModel):
|
||||
stream_path: str | None
|
||||
expires_at: str
|
||||
poll_url: str
|
||||
calibration_status: Literal["calibrated", "uncalibrated", "unknown"] = "unknown"
|
||||
|
||||
class CloseLiveSessionResponse(BaseModel):
|
||||
session_id: str
|
||||
@@ -59,14 +61,25 @@ def capability(config):
|
||||
or cutoff.retrieval_policy != RETRIEVAL_POLICY):
|
||||
raise ValueError('CALIBRATION_REQUIRED')
|
||||
except (OSError, ValueError, KeyError, TypeError, AttributeError):
|
||||
if config.voice_transport_testing:
|
||||
return None
|
||||
raise ValueError('CALIBRATION_REQUIRED') from None
|
||||
return cutoff
|
||||
|
||||
def search_profile(cutoff, settings=None):
|
||||
if cutoff is None:
|
||||
return dict(embedding=asdict((settings or IngestionSettings()).embedding_profile),
|
||||
calibration_status='uncalibrated', mode='transport_testing',
|
||||
retrieval_policy=RETRIEVAL_POLICY)
|
||||
return dict(embedding=cutoff.profile, calibration_id=cutoff.calibration_id,
|
||||
retrieval_policy=cutoff.retrieval_policy, distance=cutoff.distance)
|
||||
|
||||
@router.post('', response_model=LiveSessionResponse, status_code=201)
|
||||
def create_voice_session(req: CreateLiveSessionRequest, response: Response,
|
||||
user: Annotated[UserContext, Depends(get_current_user)],
|
||||
lifecycle: Annotated[LiveLifecycleService, Depends(get_lifecycle_service)],
|
||||
config: Annotated[VoiceSettings, Depends(get_voice_settings)],
|
||||
engine: Annotated[object, Depends(get_engine)],
|
||||
_csrf: Annotated[None, Depends(require_csrf)] = None):
|
||||
try:
|
||||
# Recover replay before capability checks: a configuration change cannot alter identity.
|
||||
@@ -84,10 +97,12 @@ def create_voice_session(req: CreateLiveSessionRequest, response: Response,
|
||||
return result
|
||||
cutoff = capability(config)
|
||||
profile = config.profile()
|
||||
profile["search"] = {"embedding": cutoff.profile, "calibration_id": cutoff.calibration_id,
|
||||
"retrieval_policy": cutoff.retrieval_policy, "distance": cutoff.distance}
|
||||
# Construct configured embedding transport only after replay recovery.
|
||||
# Construction validates identity/limits/credentials without inference.
|
||||
search_settings = get_search_service(engine).settings if cutoff is None else None
|
||||
profile["search"] = search_profile(cutoff, search_settings)
|
||||
result = lifecycle.create_live_session(user, req.conversation_id, req.client_request_id,
|
||||
provider=config.provider, model=config.gemini_model, execution_profile=profile)
|
||||
provider=config.provider, model=config.selected_model, execution_profile=profile)
|
||||
except ValueError as exc:
|
||||
raise error(str(exc)) from None
|
||||
if result['replayed']:
|
||||
@@ -131,13 +146,11 @@ async def handle_stream_websocket(websocket, session_id, auth_service, lifecycle
|
||||
user = await blocking(auth_service.get_current_user, websocket.cookies.get(COOKIE_NAME))
|
||||
info = await blocking(lifecycle_service.validate_stream, user, session_id, initial=True)
|
||||
config.require_voice()
|
||||
if search_service.cutoff is None:
|
||||
if search_service.cutoff is None and not config.voice_transport_testing:
|
||||
raise ValueError('CALIBRATION_REQUIRED')
|
||||
if (info['provider'] != 'gemini' or info['model'] != config.gemini_model
|
||||
if (info['provider'] != config.provider or info['model'] != config.selected_model
|
||||
or any(info['execution_profile'].get(k) != v for k,v in config.profile().items())
|
||||
or info['execution_profile'].get('search') != {
|
||||
'embedding': search_service.cutoff.profile, 'calibration_id': search_service.cutoff.calibration_id,
|
||||
'retrieval_policy': search_service.cutoff.retrieval_policy, 'distance': search_service.cutoff.distance}):
|
||||
or info['execution_profile'].get('search') != search_profile(search_service.cutoff, search_service.settings)):
|
||||
raise ValueError('LIVE_SESSION_UNUSABLE')
|
||||
except Exception as exc:
|
||||
logger.info('Stream admission rejected: %s', type(exc).__name__)
|
||||
@@ -164,17 +177,10 @@ async def handle_stream_websocket(websocket, session_id, auth_service, lifecycle
|
||||
# Guard is released even if accept fails.
|
||||
await websocket.accept()
|
||||
limits = RuntimeSettings()
|
||||
transport = await asyncio.wait_for(connect_gemini(config.gemini_api_key.get_secret_value(),
|
||||
config.gemini_model, config.gemini_proxy, limits), limits.connect_timeout_seconds)
|
||||
adapter = GeminiLiveAdapter(transport, model=config.gemini_model, voice=config.gemini_voice, settings=limits)
|
||||
adapter = await create_adapter(config, limits)
|
||||
async def authority_check(execution):
|
||||
nonlocal outcome
|
||||
try:
|
||||
await blocking(lifecycle_service.validate_stream, user, session_id, runtime.session_execution)
|
||||
await blocking(lifecycle_service.validate_stream, user, session_id, execution)
|
||||
except ValueError as exc:
|
||||
outcome = str(exc)
|
||||
raise
|
||||
await blocking(lifecycle_service.validate_stream, user, session_id, runtime.session_execution)
|
||||
await blocking(lifecycle_service.validate_stream, user, session_id, execution)
|
||||
return True
|
||||
store = DurableTools(lifecycle_service, user, session_id)
|
||||
async def emit(event):
|
||||
@@ -198,8 +204,20 @@ async def handle_stream_websocket(websocket, session_id, auth_service, lifecycle
|
||||
await runtime.start()
|
||||
async def browser():
|
||||
while runtime.usable:
|
||||
# Keep the delivered binary message in the transport budget until
|
||||
# its provider send completes. Don't add a second runtime backlog
|
||||
# on top of the parser's eight queued + one assembling messages.
|
||||
while runtime.usable and runtime.input_transport_count:
|
||||
await asyncio.sleep(.001)
|
||||
if not runtime.usable:
|
||||
return
|
||||
message = await websocket.receive()
|
||||
if message['type'] == 'websocket.disconnect':
|
||||
code = {1009: 'LIVE_FRAME_TOO_LARGE', 1002: 'LIVE_PROTOCOL_ERROR',
|
||||
1007: 'LIVE_PROTOCOL_ERROR'}.get(message.get('code'))
|
||||
if code:
|
||||
async with runtime.lock:
|
||||
runtime.fail(code, writable=False)
|
||||
return
|
||||
if not runtime.ready and ready_sent.is_set():
|
||||
await asyncio.wait_for(runtime.ready_signal.wait(), limits.send_timeout_seconds)
|
||||
@@ -208,15 +226,13 @@ async def handle_stream_websocket(websocket, session_id, auth_service, lifecycle
|
||||
elif message.get('text') is not None:
|
||||
await runtime.client_control(message['text'].encode('utf-8'))
|
||||
async def monitor():
|
||||
nonlocal outcome
|
||||
while runtime.usable:
|
||||
await asyncio.sleep(.25)
|
||||
try:
|
||||
await blocking(lifecycle_service.validate_stream, user, session_id)
|
||||
except ValueError as exc:
|
||||
outcome = str(exc)
|
||||
except Exception as exc:
|
||||
async with runtime.lock:
|
||||
runtime.fail('CONTEXT_REVOKED')
|
||||
runtime.fail(authority_failure_code(exc))
|
||||
return
|
||||
children = [asyncio.create_task(browser()), asyncio.create_task(runtime.receive_loop()),
|
||||
asyncio.create_task(monitor()), asyncio.create_task(runtime.failure_signal.wait())]
|
||||
@@ -232,7 +248,7 @@ async def handle_stream_websocket(websocket, session_id, auth_service, lifecycle
|
||||
await asyncio.wait_for(runtime.error_delivered.wait(), limits.send_timeout_seconds)
|
||||
except TimeoutError:
|
||||
pass
|
||||
outcome = outcome if outcome not in ('connection_closed', 'LIVE_TRANSPORT_FAILED') else runtime.failure
|
||||
outcome = runtime.failure
|
||||
failed = outcome.startswith('LIVE_') or outcome in ('SEARCH_TIMEOUT','SEARCH_SATURATED','DEPENDENCY_UNAVAILABLE','SEARCH_CANCELLED')
|
||||
except WebSocketDisconnect:
|
||||
outcome = 'LIVE_TRANSPORT_FAILED'
|
||||
@@ -257,7 +273,16 @@ async def handle_stream_websocket(websocket, session_id, auth_service, lifecycle
|
||||
except Exception:
|
||||
logger.warning('Bounded provider cleanup incomplete')
|
||||
try:
|
||||
await blocking(lifecycle_service.finish_session, user, session_id, outcome, failed=failed)
|
||||
# Saturation must not strand the durable terminal outcome once admission frees.
|
||||
deadline = asyncio.get_running_loop().time() + 6
|
||||
while True:
|
||||
try:
|
||||
await blocking(lifecycle_service.finish_session, user, session_id, outcome, failed=failed)
|
||||
break
|
||||
except ValueError as exc:
|
||||
if str(exc) != 'SERVICE_BUSY' or asyncio.get_running_loop().time() >= deadline:
|
||||
raise
|
||||
await asyncio.sleep(.025)
|
||||
except Exception:
|
||||
logger.warning('Live terminal persistence unavailable')
|
||||
await asyncio.wait_for(close_client(runtime.close_code or 1000 if runtime else 1011), 5)
|
||||
|
||||
Reference in New Issue
Block a user