feat(voice): add bounded Realtime knowledge runtime
Connect OpenAI Realtime to the existing async StructuredTool and shared SearchToolRunner with backend-owned authority and per-turn source references. Add an operator-only smoke harness with persisted actor and provider opt-in. Enforce confirmed readiness delivery, strict function identity, canonical results and once-only continuations. Bound and pace generated audio, preserve turn correlation, and require acknowledged cleanup before response release. Handle Unicode arguments, UTF-8 replay budgets and user-ASR completion replays. Validate with 318 voice/runner/shutdown tests and 1563 provider-free tests. Three Windows symlink tests skip; 311 PostgreSQL tests are deselected. Real-provider, browser playback and PostgreSQL acceptance remain unrun.
This commit is contained in:
@@ -0,0 +1,174 @@
|
||||
"""Operator-only diagnostic Realtime/search smoke; no HTTP/text-chat route."""
|
||||
import argparse
|
||||
import asyncio
|
||||
from dataclasses import asdict
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import Field, SecretStr
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.infrastructure.database import create_database, check_compatibility
|
||||
from app.infrastructure.realtime import RealtimeAdapter, connect
|
||||
from app.modules.documents.settings import IngestionSettings
|
||||
from app.modules.knowledge.calibration import load_cutoff
|
||||
from app.modules.knowledge.langchain_tool import SearchToolRunner
|
||||
from app.modules.knowledge.service import SearchService, authority, transaction
|
||||
from app.modules.voice.runtime import VoiceRuntime
|
||||
from app.modules.voice.settings import RuntimeSettings
|
||||
from app.modules.voice.serialization import bounded_json
|
||||
|
||||
class VoiceSettings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file=".env", extra="ignore", hide_input_in_errors=True)
|
||||
openai_api_key: SecretStr
|
||||
openai_realtime_model: str = Field(default="gpt-realtime-mini", min_length=1)
|
||||
openai_proxy: str | None = None
|
||||
runtime_settings: RuntimeSettings = Field(default_factory=RuntimeSettings)
|
||||
search_calibration_report: Path
|
||||
|
||||
def preflight(engine, settings, actor, cutoff):
|
||||
if cutoff.profile != asdict(settings.embedding_profile):
|
||||
raise ValueError("Calibration profile mismatch")
|
||||
with transaction(engine) as conn:
|
||||
current, _ = authority(conn, actor)
|
||||
check_compatibility(conn, settings.embedding_profile, require_worker=True)
|
||||
count = conn.execute(text("""
|
||||
SELECT count(*) FROM documents WHERE organization_id=:org
|
||||
AND status='ready' AND is_active AND deleted_at IS NULL
|
||||
AND content_purged_at IS NULL
|
||||
AND processing_profile->'embedding'=CAST(:profile AS jsonb)
|
||||
"""), dict(org=current["organization_id"],
|
||||
profile=json.dumps(cutoff.profile))).scalar_one()
|
||||
if not count:
|
||||
raise ValueError("Eligible selected documents required")
|
||||
|
||||
async def run(service, runner, actor, config, query, seconds, max_calls):
|
||||
try:
|
||||
limits = getattr(config, "runtime_settings", None) or RuntimeSettings()
|
||||
if (not isinstance(limits, RuntimeSettings) or type(seconds) not in (int, float)
|
||||
or not 0 < seconds <= 600 or type(max_calls) is not int
|
||||
or not 1 <= max_calls <= min(10, limits.max_tool_calls)
|
||||
or not isinstance(query, str) or not query.strip() or len(query) > 2000):
|
||||
raise ValueError("Invalid smoke bounds")
|
||||
async with asyncio.timeout(seconds):
|
||||
return await _run(service, runner, actor, config, query, max_calls, limits)
|
||||
except TimeoutError:
|
||||
print(json.dumps(dict(error=dict(code="SMOKE_TIMEOUT"))), file=sys.stderr)
|
||||
return 1
|
||||
|
||||
async def _run(service, runner, actor, config, query, max_calls, limits):
|
||||
transport = await connect(config.openai_api_key.get_secret_value(),
|
||||
config.openai_realtime_model, config.openai_proxy,
|
||||
limits)
|
||||
async def emit(event):
|
||||
if isinstance(event, bytes):
|
||||
return # No playback assertion: diagnostic smoke never claims heard audio.
|
||||
print(bounded_json(event, limits.max_server_event_bytes), flush=True)
|
||||
runtime = VoiceRuntime(RealtimeAdapter(transport, model=config.openai_realtime_model, settings=limits),
|
||||
service, runner, actor, emit, max_calls=max_calls,
|
||||
settings=limits)
|
||||
receiver = None
|
||||
try:
|
||||
await runtime.start()
|
||||
receiver = asyncio.create_task(runtime.receive_loop())
|
||||
while not runtime.ready and runtime.usable:
|
||||
await asyncio.sleep(.01)
|
||||
if not runtime.usable:
|
||||
return 1
|
||||
turn_ref = await runtime.diagnostic_text(query)
|
||||
while runtime.usable:
|
||||
await asyncio.sleep(.01)
|
||||
async with runtime.lock:
|
||||
if not runtime.check_deadlines():
|
||||
return 1
|
||||
current = runtime.current
|
||||
if current is None or current.ref != turn_ref or current.superseded:
|
||||
return 1
|
||||
responses = [r for r in runtime.responses.values() if r.turn is current]
|
||||
answer = responses[-1] if responses else None
|
||||
if answer is None or not answer.terminal or answer.calls:
|
||||
continue
|
||||
if answer.status != "completed" or answer.interrupted:
|
||||
return 1
|
||||
if not answer.transcript_delivered:
|
||||
continue
|
||||
actual = [(cid, r, c) for cid, (r, c) in runtime.calls.items()
|
||||
if r.turn is current]
|
||||
if (not actual or any(not c["sent"] or c["result"] is None or
|
||||
not r.terminal or r.status != "completed" or r.interrupted
|
||||
for _, r, c in actual)):
|
||||
continue
|
||||
chain, cursor = set(), answer
|
||||
while cursor.parent_response is not None:
|
||||
chain.add(cursor.parent_response)
|
||||
cursor = runtime.responses[cursor.parent_response]
|
||||
if any(r.id not in chain for _, r, _ in actual):
|
||||
return 1
|
||||
report = dict(type="smoke_correlation", turn_ref=turn_ref,
|
||||
final_response_id=answer.id, transcript_delivered=True,
|
||||
calls=[dict(call_id=cid, response_id=r.id,
|
||||
continuation_response_id=next(child.id for child in responses
|
||||
if child.parent_response == r.id),
|
||||
status=c["result"]["status"],
|
||||
sources=[{k: s[k] for k in ("source_ref", "document_id", "chunk_id")}
|
||||
for s in c["result"]["sources"]]) for cid, r, c in actual],
|
||||
audio_playback_verified=False)
|
||||
print(json.dumps(report, ensure_ascii=True), flush=True)
|
||||
return 0 if all(c["result"]["status"] != "error" for _, _, c in actual) else 1
|
||||
return 1
|
||||
except TimeoutError:
|
||||
print(json.dumps(dict(error=dict(code="SMOKE_TIMEOUT"))), file=sys.stderr)
|
||||
return 1
|
||||
finally:
|
||||
if receiver:
|
||||
receiver.cancel()
|
||||
await asyncio.gather(receiver, return_exceptions=True)
|
||||
await runtime.close()
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--user-id", type=UUID, required=True)
|
||||
parser.add_argument("--query", required=True)
|
||||
parser.add_argument("--allow-provider-calls", action="store_true", required=True,
|
||||
help="Authorize Realtime plus up to --max-tool-calls query embeddings")
|
||||
parser.add_argument("--seconds", type=int, choices=range(1, 601), default=90, metavar="1..600")
|
||||
parser.add_argument("--max-tool-calls", type=int, choices=range(1, 11), default=4, metavar="1..10")
|
||||
args = parser.parse_args(argv)
|
||||
engine = runner = None
|
||||
try:
|
||||
# Validate everything before opening the provider connection.
|
||||
if not args.query.strip() or len(args.query) > 2000:
|
||||
raise ValueError("Bounded query required")
|
||||
settings, config = IngestionSettings(), VoiceSettings()
|
||||
cutoff = load_cutoff(json.loads(config.search_calibration_report.read_text(encoding="utf-8")))
|
||||
if settings.embedding_timeout_seconds > 75:
|
||||
raise ValueError("Smoke embedding timeout must not exceed 75 seconds")
|
||||
from sqlalchemy.engine import make_url
|
||||
url = make_url(settings.database_url.get_secret_value())
|
||||
options = url.query.get("options", "") + " -c statement_timeout=5000 -c lock_timeout=5000"
|
||||
url = url.update_query_dict(dict(connect_timeout="5", options=options))
|
||||
engine = create_database(url.render_as_string(hide_password=False))
|
||||
preflight(engine, settings, args.user_id, cutoff)
|
||||
from app.worker import factories
|
||||
_, provider_factory = factories(settings)
|
||||
provider, counter = provider_factory(settings.processing_profile())
|
||||
service = SearchService(engine, settings, provider, counter, cutoff=cutoff)
|
||||
runner = SearchToolRunner()
|
||||
return asyncio.run(run(service, runner, args.user_id, config, args.query,
|
||||
args.seconds, args.max_tool_calls))
|
||||
except Exception:
|
||||
print(json.dumps(dict(error=dict(code="SMOKE_FAILED",
|
||||
message="Verify actor, database/profile, measured calibration, provider access and configuration"))),
|
||||
file=sys.stderr)
|
||||
return 1
|
||||
finally:
|
||||
if runner:
|
||||
runner.close()
|
||||
if engine:
|
||||
engine.dispose()
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user