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:
@@ -250,7 +250,7 @@ def factual_context_units(blocks):
|
||||
source_units.append([block.group_id, [block], True])
|
||||
else:
|
||||
source_units.append([None, [block], False])
|
||||
scopes, resolved = [], []
|
||||
scopes, resolved, preamble = [], [], []
|
||||
|
||||
def close_scope():
|
||||
scope = scopes.pop()
|
||||
@@ -263,7 +263,7 @@ def factual_context_units(blocks):
|
||||
raise ExtractionError("Unresolved non-FAQ source group")
|
||||
# Validate every group, including excluded groups, before selection.
|
||||
associate_dependencies([(group, unit, True)])
|
||||
context = [b for scope in scopes for b in scope["blocks"]]
|
||||
context = preamble + [b for scope in scopes for b in scope["blocks"]]
|
||||
for scope in scopes:
|
||||
scope["used"] = True
|
||||
resolved.append([group, context + unit, True])
|
||||
@@ -278,10 +278,13 @@ def factual_context_units(blocks):
|
||||
while scopes and scopes[-1]["level"] >= level:
|
||||
close_scope()
|
||||
scopes.append(dict(level=level, blocks=[block], used=False))
|
||||
elif not scopes and not resolved and block.parent_block_id is None:
|
||||
# Initial source prose is document-wide context, never pair-local.
|
||||
preamble.append(block)
|
||||
elif scopes and not scopes[-1]["used"] and block.parent_block_id is None:
|
||||
scopes[-1]["blocks"].append(block)
|
||||
else:
|
||||
# Unheaded preambles and prose between pairs have no reliable scope.
|
||||
# Prose after pairs still has no reliable association.
|
||||
raise ExtractionError("Ambiguous governing context for factual FAQ")
|
||||
while scopes:
|
||||
close_scope()
|
||||
|
||||
@@ -11,7 +11,7 @@ import unicodedata
|
||||
from uuid import UUID
|
||||
from zipfile import ZipFile
|
||||
|
||||
from .extraction_artifacts import extraction_profile_digest, validate_artifact, bounded_json_bytes, bounded_json_size, serialize_artifact
|
||||
from .extraction_artifacts import extraction_profile_digest, validate_artifact, bounded_json_bytes, bounded_json_size, serialize_artifact, ocr_review_required
|
||||
from .formats import DOCX_MIME, validate_docx, validate_image
|
||||
from .normalization import normalize_search_text, normalized_inputs
|
||||
from .types import ExtractedBlock, ExtractionEnvelope, ExtractionReviewAnnotation
|
||||
@@ -230,6 +230,7 @@ class PageBlockExtractor:
|
||||
self.owned()
|
||||
self.profile_digest = extraction_profile_digest(profile) # legacy fails before any provider
|
||||
self.original_hash, self.profile, self.reviewed = original_hash, profile, False
|
||||
self.automatic_ocr = False
|
||||
self.document_id, self.title = document_id, title
|
||||
self.annotations = []
|
||||
extraction = profile["extraction"]
|
||||
@@ -273,7 +274,8 @@ class PageBlockExtractor:
|
||||
blocks = tuple(b.model_copy(update={"ordinal": i}) for i, b in enumerate(blocks))
|
||||
envelope = ExtractionEnvelope(document_id=document_id, title=title, original_sha256=original_hash,
|
||||
extraction_profile_sha256=self.profile_digest, normalization_policy=profile["normalizer"],
|
||||
complete=True, quality_decision="reviewed" if self.reviewed else "passed",
|
||||
complete=True, quality_decision=("partially_reviewed" if self.reviewed and self.automatic_ocr
|
||||
else "reviewed" if self.reviewed else "passed"),
|
||||
review_annotations=tuple(self.annotations), blocks=blocks)
|
||||
normalized_inputs(envelope, profile)
|
||||
payload = serialize_artifact(envelope, profile)
|
||||
@@ -795,7 +797,8 @@ class PageBlockExtractor:
|
||||
data = {"artifact_schema": 1, "document_id": str(self.document_id), "title": self.title,
|
||||
"original_sha256": self.original_hash, "extraction_profile_sha256": self.profile_digest,
|
||||
"normalization_policy": self.profile["normalizer"], "complete": True,
|
||||
"quality_decision": "reviewed" if self.reviewed else "passed", "warnings": [],
|
||||
"quality_decision": ("partially_reviewed" if self.reviewed and getattr(self, "automatic_ocr", False)
|
||||
else "reviewed" if self.reviewed else "passed"), "warnings": [],
|
||||
"review_annotations": [a.model_dump(mode="json") for a in self.annotations],
|
||||
"blocks": [dict(b.model_dump(mode="json"), ordinal=i) for i, b in enumerate(blocks)]}
|
||||
bounded_json_size(data, self.profile["extraction"]["max_extraction_artifact_bytes"])
|
||||
@@ -824,11 +827,12 @@ class PageBlockExtractor:
|
||||
or b.page != page or not b.source_locator.startswith(locator + "/")
|
||||
or unreadable(b.text)):
|
||||
raise ExtractionError("Vision evidence identity, location or readability mismatch")
|
||||
if any("unreadable" in w.lower() or "ناخوانا" in w for w in b.warnings):
|
||||
raise ExtractionError("Vision reports unreadable source regions")
|
||||
# Validate local source relationships before manually attesting to the result.
|
||||
ExtractionEnvelope(document_id=UUID(int=0), title="validation", original_sha256=self.original_hash,
|
||||
extraction_profile_sha256=self.profile_digest, normalization_policy=self.profile["normalizer"],
|
||||
complete=True, quality_decision="passed",
|
||||
blocks=tuple(blocks))
|
||||
if not ocr_review_required(self.profile) and not any(b.warnings for b in blocks):
|
||||
self.automatic_ocr = True
|
||||
return blocks
|
||||
return self._review(blocks, image, locator, reasons + ("Vision completeness and critical fields inspected",))
|
||||
|
||||
@@ -11,6 +11,14 @@ class LegacyProcessingProfile(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def ocr_review_required(profile: Mapping) -> bool:
|
||||
"""Fail closed for legacy snapshots; deployment defaults never reinterpret jobs."""
|
||||
value = profile.get("extraction", {}).get("ocr_review_required", True)
|
||||
if type(value) is not bool:
|
||||
raise ValueError("Invalid frozen OCR review policy")
|
||||
return value
|
||||
|
||||
|
||||
def processing_profile_kind(profile: Mapping) -> str:
|
||||
if "profile_schema" not in profile and profile.get("extractor") == "pypdf-markdown-v1":
|
||||
return "legacy-v1"
|
||||
@@ -20,6 +28,7 @@ def processing_profile_kind(profile: Mapping) -> str:
|
||||
|
||||
|
||||
def extraction_profile_digest(profile: Mapping) -> str:
|
||||
ocr_review_required(profile)
|
||||
if processing_profile_kind(profile) == "legacy-v1":
|
||||
raise LegacyProcessingProfile("Legacy extractor requires explicit legacy dispatch; OCR reinterpretation is forbidden")
|
||||
# Faithful extraction is reusable across chunk/embedding/normalization changes.
|
||||
|
||||
@@ -22,9 +22,10 @@ def unsafe_display_character(character: str) -> bool:
|
||||
{"RLO", "LRO", "RLE", "LRE", "PDF", "LRI", "RLI", "FSI", "PDI"})
|
||||
|
||||
|
||||
def normalized_title(path: Path, title: str | None) -> str:
|
||||
filename = unicodedata.normalize("NFC", Path(path).name)
|
||||
value = unicodedata.normalize("NFC", title if title is not None else Path(filename).stem)
|
||||
def normalized_title(path: Path, title: str | None, *, filename: str | None = None) -> str:
|
||||
name = filename if filename is not None else Path(path).name
|
||||
nfc_name = unicodedata.normalize("NFC", name)
|
||||
value = unicodedata.normalize("NFC", title if title is not None else Path(nfc_name).stem)
|
||||
return " ".join(value.split())
|
||||
|
||||
|
||||
@@ -34,7 +35,7 @@ def payload_hash(sha: str, title: str) -> str:
|
||||
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def replay_payload_hash(path: Path, title: str | None, size_bytes: int) -> str:
|
||||
def replay_payload_hash(path: Path, title: str | None, size_bytes: int, *, filename: str | None = None) -> str:
|
||||
"""Stream at most the accepted length plus one byte, with constant memory."""
|
||||
path = Path(path)
|
||||
digest, total = hashlib.sha256(), 0
|
||||
@@ -54,12 +55,13 @@ def replay_payload_hash(path: Path, title: str | None, size_bytes: int) -> str:
|
||||
raise IntakeError("INVALID_FILE", "Cannot read input file") from None
|
||||
if total != size_bytes:
|
||||
raise IntakeError("IDEMPOTENCY_CONFLICT", "Key already used with a different payload")
|
||||
return payload_hash(digest.hexdigest(), normalized_title(path, title))
|
||||
return payload_hash(digest.hexdigest(), normalized_title(path, title, filename=filename))
|
||||
|
||||
|
||||
def prepare_file(path: Path, title: str | None, settings) -> dict:
|
||||
def prepare_file(path: Path, title: str | None, settings, *, filename: str | None = None) -> dict:
|
||||
path = Path(path)
|
||||
filename = unicodedata.normalize("NFC", path.name)
|
||||
display_name = filename if filename is not None else path.name
|
||||
filename = unicodedata.normalize("NFC", display_name)
|
||||
# Display names are portable and reject path delimiters, controls and bidi marks.
|
||||
if (not filename or len(filename) > 255 or filename.rstrip(" .") != filename
|
||||
or any(c in '<>:"/\\|?*' or unsafe_display_character(c)
|
||||
@@ -69,7 +71,7 @@ def prepare_file(path: Path, title: str | None, settings) -> dict:
|
||||
extension = Path(filename).suffix.lower()
|
||||
if extension not in settings.accepted_formats:
|
||||
raise IntakeError("UNSUPPORTED_FILE_TYPE", "Unsupported file format")
|
||||
canonical_title = normalized_title(path, title)
|
||||
canonical_title = normalized_title(path, title, filename=filename)
|
||||
if (not canonical_title or len(canonical_title) > 200
|
||||
or any(unsafe_display_character(c) for c in canonical_title)):
|
||||
raise IntakeError("INVALID_FILE", "Title must contain 1-200 display characters")
|
||||
@@ -96,16 +98,16 @@ def prepare_file(path: Path, title: str | None, settings) -> dict:
|
||||
|
||||
|
||||
def import_document(repository: IntakeRepository, store: FileStore, settings, *, path,
|
||||
administrator_id, request_id, title=None):
|
||||
administrator_id, request_id, title=None, filename=None):
|
||||
administrator_id, request_id = UUID(str(administrator_id)), UUID(str(request_id))
|
||||
org, previous = repository.lookup(settings, administrator_id, request_id)
|
||||
if previous is not None:
|
||||
# Existing requests compare payloads independently of current acceptance policy.
|
||||
# File I/O is outside database transactions and creates no candidate.
|
||||
submitted_hash = replay_payload_hash(path, title, previous["size_bytes"])
|
||||
submitted_hash = replay_payload_hash(path, title, previous["size_bytes"], filename=filename)
|
||||
result = repository.replay(org, administrator_id, previous, submitted_hash)
|
||||
return {"replayed": True, "document": result}
|
||||
prepared = prepare_file(path, title, settings)
|
||||
prepared = prepare_file(path, title, settings, filename=filename)
|
||||
key = store.put(prepared["content"])
|
||||
replayed, conflict, result = repository.create(
|
||||
settings, prepared, key, administrator_id, request_id, org)
|
||||
|
||||
@@ -58,6 +58,7 @@ class IngestionSettings(BaseSettings):
|
||||
vision_timeout_seconds: float = Field(default=60, gt=0, allow_inf_nan=False)
|
||||
fallback_policy: str = Field(default="affected-pages-v1", min_length=1)
|
||||
quality_policy: str = Field(default="bounded-checks-manual-review-v1", min_length=1)
|
||||
ocr_review_required: bool = True
|
||||
normalization_policy: str = Field(default="unicode-line-endings-v1", min_length=1)
|
||||
chunking_policy: str = Field(default="paragraph-v1", min_length=1)
|
||||
render_dpi: int = Field(default=144, gt=0, le=600)
|
||||
@@ -211,6 +212,7 @@ class IngestionSettings(BaseSettings):
|
||||
"vision": {"provider": self.vision_provider, "endpoint": self.vision_endpoint,
|
||||
"model": self.vision_model, "timeout_seconds": self.vision_timeout_seconds},
|
||||
"fallback_policy": self.fallback_policy, "quality_policy": self.quality_policy,
|
||||
"ocr_review_required": self.ocr_review_required,
|
||||
"render_dpi": self.render_dpi,
|
||||
"max_rendered_page_pixels": self.max_rendered_page_pixels,
|
||||
"max_pdf_pages": self.max_pdf_pages,
|
||||
|
||||
@@ -67,7 +67,7 @@ class ExtractionEnvelope(BaseModel):
|
||||
extraction_profile_sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
|
||||
normalization_policy: str = Field(min_length=1)
|
||||
complete: Literal[True]
|
||||
quality_decision: Literal["passed", "reviewed"]
|
||||
quality_decision: Literal["passed", "reviewed", "partially_reviewed"]
|
||||
warnings: tuple[str, ...] = ()
|
||||
review_annotations: tuple[ExtractionReviewAnnotation, ...] = ()
|
||||
blocks: tuple[ExtractedBlock, ...] = Field(min_length=1)
|
||||
|
||||
@@ -10,7 +10,7 @@ from threading import Event, Thread
|
||||
from .chunking import chunk_extraction
|
||||
from .embeddings import EmbeddingError, stage_document
|
||||
from .extraction import ExtractionError, ReviewRequired
|
||||
from .extraction_artifacts import extraction_profile_digest
|
||||
from .extraction_artifacts import extraction_profile_digest, ocr_review_required
|
||||
from .review import FactualReviewRequired, prepare_chunks
|
||||
from .operational_limits import validate_worker_durations
|
||||
|
||||
@@ -63,21 +63,36 @@ def validate_source(envelope, document, content):
|
||||
if envelope.title != document["title"]:
|
||||
raise ExtractionError("Extraction title differs from immutable source")
|
||||
warnings = (*envelope.warnings, *(w for b in envelope.blocks for w in b.warnings))
|
||||
if warnings and envelope.quality_decision != "reviewed":
|
||||
from .extraction import unreadable, PLACEHOLDER
|
||||
from .review import factual_groups
|
||||
groups = factual_groups(envelope)
|
||||
if any(unreadable(b.text) or (PLACEHOLDER.search(b.text) and b.group_id not in groups)
|
||||
for b in envelope.blocks):
|
||||
raise ExtractionError("Unreadable or placeholder extracted evidence")
|
||||
if warnings and envelope.quality_decision not in ("reviewed", "partially_reviewed"):
|
||||
raise ExtractionError("Unreviewed extraction warnings")
|
||||
if any("unreadable" in w.lower() or "\u0646\u0627\u062e\u0648\u0627\u0646\u0627" in w for w in warnings):
|
||||
raise ExtractionError("Unreadable retained evidence")
|
||||
mime = document["mime_type"]
|
||||
if envelope.quality_decision == "partially_reviewed":
|
||||
inspected = {annotation.locator for annotation in envelope.review_annotations}
|
||||
automatic = [b for b in envelope.blocks if not any(
|
||||
b.source_locator.startswith(locator + "/") for locator in inspected)]
|
||||
if (mime != "application/pdf" or ocr_review_required(document["processing_profile"])
|
||||
or not inspected or not automatic or envelope.warnings
|
||||
or any(b.method not in ("vision", "ocr") or b.warnings for b in automatic)):
|
||||
raise ExtractionError("Mixed extraction requires exact inspected non-automatic evidence")
|
||||
automatic_ocr = (not ocr_review_required(document["processing_profile"])
|
||||
and envelope.quality_decision == "passed" and not warnings
|
||||
and all(b.method in ("vision", "ocr") for b in envelope.blocks))
|
||||
if mime == "application/pdf":
|
||||
import pymupdf
|
||||
with pymupdf.open(stream=content, filetype="pdf") as source:
|
||||
if (source.page_count > document["processing_profile"]["extraction"]["max_pdf_pages"]
|
||||
or {b.page for b in envelope.blocks} != set(range(1, source.page_count + 1))):
|
||||
raise ExtractionError("Incomplete PDF source coverage")
|
||||
if envelope.quality_decision != "reviewed":
|
||||
if envelope.quality_decision not in ("reviewed", "partially_reviewed") and not automatic_ocr:
|
||||
raise ExtractionError("PDF extraction requires inspection")
|
||||
elif mime in ("image/jpeg", "image/png"):
|
||||
if envelope.quality_decision != "reviewed" or any(
|
||||
if (envelope.quality_decision != "reviewed" and not automatic_ocr) or any(
|
||||
b.page is not None or b.method not in ("vision", "ocr") for b in envelope.blocks):
|
||||
raise ExtractionError("Image extraction requires inspected complete evidence")
|
||||
elif mime in ("text/markdown", "text/plain",
|
||||
|
||||
@@ -183,9 +183,24 @@ class SearchToolRunner:
|
||||
self._lock.wait_for(lambda: self._admitted == 0)
|
||||
|
||||
|
||||
def prepare_search_tools():
|
||||
"""Resolve the optional framework before voice admission/tool deadlines."""
|
||||
try:
|
||||
from langchain_core.tools import StructuredTool
|
||||
except ModuleNotFoundError as exc:
|
||||
# Document-only API installations keep the existing optional boundary.
|
||||
if exc.name != 'langchain_core':
|
||||
raise
|
||||
return None
|
||||
# Importing StructuredTool resolves its callback/configuration dependencies.
|
||||
return StructuredTool
|
||||
|
||||
|
||||
def create_search_tool(service, context, runner):
|
||||
"""Build only on explicit opt-in; core imports do not require LangChain."""
|
||||
from langchain_core.tools import StructuredTool
|
||||
StructuredTool = prepare_search_tools()
|
||||
if StructuredTool is None:
|
||||
raise ModuleNotFoundError('Install the existing search/voice extra for LangChain tools')
|
||||
|
||||
trusted = context
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Fail closed without labelling unavailable authority as verified revocation."""
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from app.modules.knowledge.service import KnowledgeError
|
||||
|
||||
|
||||
def authority_failure_code(exc):
|
||||
if isinstance(exc, KnowledgeError) and exc.code in {'ACTOR_UNAVAILABLE', 'CONTEXT_REVOKED'}:
|
||||
return 'CONTEXT_REVOKED'
|
||||
if isinstance(exc, TimeoutError):
|
||||
return 'SEARCH_TIMEOUT'
|
||||
if isinstance(exc, SQLAlchemyError):
|
||||
return 'DEPENDENCY_UNAVAILABLE'
|
||||
if isinstance(exc, ValueError):
|
||||
if str(exc) == 'SERVICE_BUSY':
|
||||
return 'SEARCH_SATURATED'
|
||||
if str(exc) in {'AUTH_REQUIRED', 'USER_DISABLED', 'ACCOUNT_DISABLED', 'SESSION_REVOKED', 'SESSION_EXPIRED',
|
||||
'CONTEXT_REVOKED', 'CONVERSATION_STALE', 'CONVERSATION_CLOSED',
|
||||
'CONVERSATION_NOT_FOUND', 'SESSION_NOT_FOUND', 'LIVE_SESSION_EXPIRED',
|
||||
'LIVE_SESSION_UNUSABLE'}:
|
||||
return 'CONTEXT_REVOKED'
|
||||
return 'DEPENDENCY_UNAVAILABLE'
|
||||
@@ -2,39 +2,51 @@
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
from urllib.parse import urlsplit
|
||||
from pydantic import Field, SecretStr, field_validator, model_validator
|
||||
from pydantic import AliasChoices, Field, SecretStr, field_validator, model_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class VoiceSettings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file='.env', extra='ignore', hide_input_in_errors=True, frozen=True)
|
||||
provider: Literal['gemini'] = 'gemini'
|
||||
model_config = SettingsConfigDict(env_file='.env', extra='ignore', hide_input_in_errors=True, frozen=True, populate_by_name=True)
|
||||
provider: Literal['gemini', 'openai'] = Field(default='gemini', validation_alias=AliasChoices('VOICE_PROVIDER', 'PROVIDER', 'provider'))
|
||||
gemini_api_key: SecretStr = SecretStr('')
|
||||
gemini_model: str = Field(default='gemini-2.0-flash-exp', min_length=1, max_length=200)
|
||||
gemini_voice: str = Field(default='Aoede', min_length=1, max_length=80)
|
||||
gemini_proxy: str | None = None
|
||||
openai_realtime_api_key: SecretStr = SecretStr('')
|
||||
openai_realtime_model: str = Field(default='gpt-realtime-mini', min_length=1, max_length=200)
|
||||
openai_realtime_voice: str = Field(default='shimmer', min_length=1, max_length=80)
|
||||
openai_realtime_proxy: str | None = None
|
||||
trusted_origins: tuple[str, ...] = ('http://localhost:8000', 'http://127.0.0.1:8000')
|
||||
trusted_hosts: tuple[str, ...] = ('localhost:8000', '127.0.0.1:8000')
|
||||
cookie_secure: bool = True
|
||||
auth_session_seconds: int = Field(default=28800, ge=60, le=604800)
|
||||
live_session_seconds: int = Field(default=600, ge=10, le=3600)
|
||||
search_calibration_report: Path | None = None
|
||||
voice_transport_testing: bool = False
|
||||
max_provider_sessions: int = Field(default=4, ge=1, le=32)
|
||||
login_attempts_per_minute: int = Field(default=12, ge=1, le=120)
|
||||
|
||||
@field_validator('gemini_model', 'gemini_voice')
|
||||
def __init__(self, **values):
|
||||
# Settings sources normalize aliases and would otherwise discard conflicting init keys.
|
||||
aliases = [key for key in values if key.lower() in ('voice_provider', 'provider')]
|
||||
if len({values[key] for key in aliases}) > 1:
|
||||
raise ValueError('Conflicting voice provider aliases')
|
||||
super().__init__(**values)
|
||||
|
||||
@field_validator('gemini_model', 'gemini_voice', 'openai_realtime_model', 'openai_realtime_voice')
|
||||
@classmethod
|
||||
def identifier(cls, value):
|
||||
if not value.isascii() or any(c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._/' for c in value):
|
||||
raise ValueError('Invalid voice profile identifier')
|
||||
return value
|
||||
|
||||
@field_validator('trusted_origins', 'trusted_hosts', 'gemini_proxy')
|
||||
@field_validator('trusted_origins', 'trusted_hosts', 'gemini_proxy', 'openai_realtime_proxy')
|
||||
@classmethod
|
||||
def urls(cls, value, info):
|
||||
if info.field_name == 'gemini_proxy' and value is None:
|
||||
if info.field_name.endswith('_proxy') and value is None:
|
||||
return value
|
||||
values = (value,) if info.field_name == 'gemini_proxy' else value
|
||||
values = (value,) if info.field_name.endswith('_proxy') else value
|
||||
if not values or len(values) > 20:
|
||||
raise ValueError('Explicit bounded trusted endpoints required')
|
||||
for entry in values:
|
||||
@@ -43,7 +55,7 @@ class VoiceSettings(BaseSettings):
|
||||
port = p.port
|
||||
except ValueError:
|
||||
raise ValueError('Invalid endpoint configuration') from None
|
||||
schemes = ('http', 'https', 'socks5', 'socks5h') if info.field_name == 'gemini_proxy' else ('http', 'https')
|
||||
schemes = ('http', 'https', 'socks5', 'socks5h') if info.field_name.endswith('_proxy') else ('http', 'https')
|
||||
if (len(entry) > 512 or p.scheme not in schemes or not p.hostname or p.username
|
||||
or p.password or p.path or p.query or p.fragment or '*' in entry):
|
||||
raise ValueError('Invalid endpoint configuration')
|
||||
@@ -55,11 +67,49 @@ class VoiceSettings(BaseSettings):
|
||||
raise ValueError('Insecure cookies require loopback-only development origins')
|
||||
return self
|
||||
|
||||
@classmethod
|
||||
def settings_customise_sources(cls, settings_cls, init_settings, env_settings, dotenv_settings, file_secret_settings):
|
||||
# Normalize aliases before source merging; ordinary init > env > dotenv priority remains.
|
||||
deployed = {**dotenv_settings.env_vars, **env_settings.env_vars}
|
||||
if ('voice_provider' in deployed and 'provider' in deployed
|
||||
and deployed['voice_provider'] != deployed['provider']):
|
||||
raise ValueError('Conflicting VOICE_PROVIDER and PROVIDER')
|
||||
def normalized(source):
|
||||
def read():
|
||||
values = source()
|
||||
aliases = [key for key in ('VOICE_PROVIDER', 'PROVIDER', 'provider') if key in values]
|
||||
if len({values[key] for key in aliases}) > 1:
|
||||
raise ValueError('Conflicting voice provider aliases')
|
||||
if aliases:
|
||||
selected = values[aliases[0]]
|
||||
for key in aliases:
|
||||
del values[key]
|
||||
values['VOICE_PROVIDER'] = selected
|
||||
return values
|
||||
return read
|
||||
return tuple(normalized(source) for source in (init_settings, env_settings, dotenv_settings, file_secret_settings))
|
||||
|
||||
@property
|
||||
def selected_model(self):
|
||||
return self.gemini_model if self.provider == 'gemini' else self.openai_realtime_model
|
||||
|
||||
@property
|
||||
def selected_voice(self):
|
||||
return self.gemini_voice if self.provider == 'gemini' else self.openai_realtime_voice
|
||||
|
||||
@property
|
||||
def selected_proxy(self):
|
||||
return self.gemini_proxy if self.provider == 'gemini' else self.openai_realtime_proxy
|
||||
|
||||
@property
|
||||
def selected_key(self):
|
||||
return self.gemini_api_key if self.provider == 'gemini' else self.openai_realtime_api_key
|
||||
|
||||
def require_voice(self):
|
||||
key = self.gemini_api_key.get_secret_value()
|
||||
key = self.selected_key.get_secret_value()
|
||||
if not key or len(key) > 512 or not key.isascii() or any(c.isspace() for c in key):
|
||||
raise ValueError('LIVE_PROVIDER_UNAVAILABLE')
|
||||
|
||||
def profile(self):
|
||||
return dict(provider=self.provider, model=self.gemini_model, voice=self.gemini_voice,
|
||||
input_sample_rate=16000, output_sample_rate=24000)
|
||||
return dict(provider=self.provider, model=self.selected_model, voice=self.selected_voice,
|
||||
input_sample_rate=16000 if self.provider == 'gemini' else 24000, output_sample_rate=24000)
|
||||
|
||||
@@ -78,12 +78,18 @@ class LiveLifecycleService:
|
||||
raise ValueError('LIVE_SESSION_UNUSABLE')
|
||||
return row
|
||||
|
||||
@staticmethod
|
||||
def _calibration_status(row):
|
||||
search = (row["execution_profile"] or {}).get("search", {})
|
||||
return "calibrated" if search.get("calibration_id") else search.get("calibration_status", "unknown")
|
||||
|
||||
@staticmethod
|
||||
def _shape(row, *, replayed=False, eligible=True):
|
||||
sid = str(row['id'])
|
||||
return dict(session_id=sid, conversation_id=str(row['conversation_id']), status=row['status'],
|
||||
stream_path=f'/api/v1/voice/sessions/{sid}/stream' if eligible else None,
|
||||
expires_at=row['expires_at'].isoformat(), poll_url=f'/api/v1/voice/sessions/{sid}', replayed=replayed)
|
||||
expires_at=row['expires_at'].isoformat(), poll_url=f'/api/v1/voice/sessions/{sid}', replayed=replayed,
|
||||
calibration_status=LiveLifecycleService._calibration_status(row))
|
||||
|
||||
@staticmethod
|
||||
def _terminal(conn, sid, reason, *, failed=False):
|
||||
@@ -250,7 +256,8 @@ class LiveLifecycleService:
|
||||
error_code=c['error_code'], sources=self._sources(conn, user.organization_id, (c['result_json'] or {}).get('sources', [])))
|
||||
for c in reversed(calls)]
|
||||
return dict(session_id=str(row['id']), status=row['status'], close_reason=row['close_reason'],
|
||||
expires_at=row['expires_at'].isoformat(), error_code=row['error_code'], recent_tool_results=results)
|
||||
expires_at=row['expires_at'].isoformat(), error_code=row['error_code'], recent_tool_results=results,
|
||||
calibration_status=self._calibration_status(row))
|
||||
|
||||
def admit_tool(self, user, session_id, external_call_id, public_ref, arguments, execution):
|
||||
arguments = SearchInput.model_validate(arguments).model_dump()
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Bounded, session-local voice state machine. HTTP identity/persistence is Phase 2."""
|
||||
from app.modules.voice.authority import authority_failure_code
|
||||
import asyncio
|
||||
import base64
|
||||
from collections import deque
|
||||
@@ -235,7 +236,8 @@ class VoiceRuntime:
|
||||
try:
|
||||
valid = await asyncio.wait_for(self.authority_check(
|
||||
turn.execution if turn else self.session_execution), self.settings.authority_timeout_seconds)
|
||||
except Exception:
|
||||
except Exception as exc:
|
||||
self.fail(authority_failure_code(exc))
|
||||
valid = False
|
||||
return valid
|
||||
|
||||
|
||||
Reference in New Issue
Block a user