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.
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
"""Administrator-only soft deletion, revision fencing and durable request replay."""
|
||||
import hashlib
|
||||
import json
|
||||
from uuid import UUID, uuid4
|
||||
from sqlalchemy import text
|
||||
from app.modules.knowledge.service import authority, transaction, KnowledgeError
|
||||
|
||||
|
||||
def delete_document(engine, administrator_id, document_id, request_id, expected_revision):
|
||||
if (not isinstance(document_id, UUID) or not isinstance(request_id, UUID)
|
||||
or type(expected_revision) is not int or expected_revision < 1):
|
||||
raise KnowledgeError('VALIDATION_ERROR', 'Invalid delete request', status=422)
|
||||
request_hash = hashlib.sha256(json.dumps({'expected_revision': expected_revision}, sort_keys=True).encode()).hexdigest()
|
||||
invalidate = False
|
||||
with transaction(engine) as conn:
|
||||
actor, settings = authority(conn, administrator_id, administrator=True, exclusive=True)
|
||||
params = dict(org=actor['organization_id'], actor=actor['id'], document=document_id, request=request_id)
|
||||
document = conn.execute(text('''SELECT id,is_active,deleted_at FROM documents
|
||||
WHERE organization_id=:org AND id=:document FOR UPDATE'''), params).mappings().one_or_none()
|
||||
if document is None:
|
||||
raise KnowledgeError('NOT_FOUND', 'Document not found', status=404)
|
||||
previous = conn.execute(text('''SELECT request_hash,response_json FROM audit_events
|
||||
WHERE organization_id=:org AND actor_user_id=:actor AND action='document_deleted'
|
||||
AND target_id=:document AND idempotency_key=:request'''), params).mappings().one_or_none()
|
||||
if previous is not None:
|
||||
if previous['request_hash'] != request_hash:
|
||||
raise KnowledgeError('IDEMPOTENCY_CONFLICT', 'Delete request changed')
|
||||
return dict(previous['response_json'], replayed=True)
|
||||
revision, epoch = settings['knowledge_revision'], settings['access_epoch']
|
||||
if document['deleted_at'] is None:
|
||||
if revision != expected_revision:
|
||||
raise KnowledgeError('REVISION_CONFLICT', 'Refresh knowledge selection before deleting')
|
||||
invalidate = bool(document['is_active'])
|
||||
revision += int(invalidate)
|
||||
epoch += int(invalidate)
|
||||
conn.execute(text('''UPDATE documents SET deleted_at=now(),is_active=false,updated_at=now()
|
||||
WHERE organization_id=:org AND id=:document'''), params)
|
||||
if invalidate:
|
||||
params.update(revision=revision, epoch=epoch)
|
||||
conn.execute(text('''UPDATE organization_settings SET knowledge_revision=:revision,
|
||||
access_epoch=:epoch,updated_by=:actor,updated_at=now() WHERE organization_id=:org'''), params)
|
||||
conn.execute(text("""UPDATE conversations SET status='stale',updated_at=now()
|
||||
WHERE organization_id=:org AND access_epoch<:epoch AND status='active'"""), params)
|
||||
conn.execute(text("""UPDATE live_sessions SET status='closed',closed_at=now(),
|
||||
close_reason='epoch_invalidated',updated_at=now() WHERE organization_id=:org
|
||||
AND access_epoch<:epoch AND status IN ('creating','connecting','connected')"""), params)
|
||||
conn.execute(text("""UPDATE tool_calls SET status='failed',completed_at=now(),error_code='CONTEXT_REVOKED'
|
||||
WHERE organization_id=:org AND access_epoch<:epoch AND status='running'"""), params)
|
||||
result = dict(document_id=str(document_id), deleted=True, knowledge_revision=revision,
|
||||
access_epoch=epoch, cleanup_status='pending_policy')
|
||||
conn.execute(text("""INSERT INTO audit_events(id,organization_id,actor_user_id,action,
|
||||
target_id,idempotency_key,request_hash,response_json) VALUES
|
||||
(:id,:org,:actor,'document_deleted',:document,:request,:hash,CAST(:response AS jsonb))"""),
|
||||
dict(params, id=uuid4(), hash=request_hash, response=json.dumps(result)))
|
||||
if invalidate:
|
||||
from app.modules.voice.registry import notify
|
||||
notify(organization_id=actor['organization_id'], new_epoch=epoch)
|
||||
return dict(result, replayed=False)
|
||||
@@ -11,7 +11,7 @@ from typing import Any
|
||||
from app.modules.knowledge.lexical import LEXICAL_POLICY
|
||||
|
||||
MAX_BRANCH_CANDIDATES = 50
|
||||
MAX_CHUNKS = 5
|
||||
MAX_CHUNKS = 10
|
||||
MAX_EVIDENCE_CHARACTERS = 12000
|
||||
RETRIEVAL_POLICY = f"exact-first-cosine-id-50x2-whole-5-12000/{LEXICAL_POLICY}"
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ from array import array
|
||||
from contextlib import ExitStack, contextmanager
|
||||
from dataclasses import asdict
|
||||
import json
|
||||
import re
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
|
||||
@@ -75,12 +76,28 @@ def sql_error(exc):
|
||||
and exc.connection_invalidated)))
|
||||
|
||||
|
||||
def clean_search_query(text: str) -> str:
|
||||
cleaned = text
|
||||
patterns = [
|
||||
r"شرکت\s+شهرک[\s]*های\s+صنعتی\s+(?:استان\s+)?اصفهان",
|
||||
r"شهرک[\s]*های\s+صنعتی\s+(?:استان\s+)?اصفهان",
|
||||
r"شرکت\s+شهرک[\s]*های\s+صنعتی",
|
||||
]
|
||||
for pat in patterns:
|
||||
sub = re.sub(pat, "", cleaned, flags=re.IGNORECASE).strip()
|
||||
sub = re.sub(r"^(در|از|به|برای)\s+", "", sub).strip()
|
||||
sub = re.sub(r"\s+(در|از|به|برای)$", "", sub).strip()
|
||||
if len(sub) >= 3:
|
||||
cleaned = sub
|
||||
return re.sub(r"\s+", " ", cleaned).strip()
|
||||
|
||||
|
||||
class SearchInput(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
query: str = Field(
|
||||
min_length=1,
|
||||
max_length=2000,
|
||||
description="Clean, concise search terms or entity names only (e.g. 'آقای دانش' or 'معاون برنامه ریزی'). Do NOT include conversational filler, meta-narration, or 'کاربر میپرسد'."
|
||||
description="Clean, concise search terms or entity names only (e.g. 'آقای دانش' or 'معاون برنامه ریزی'). Do NOT include conversational filler, meta-narration, or 'کاربر میپرسد'. Never append 'شهرکهای صنعتی اصفهان' or expand 'شرکت'."
|
||||
)
|
||||
context: str | None = Field(
|
||||
default=None,
|
||||
@@ -93,8 +110,10 @@ class SearchInput(BaseModel):
|
||||
def database_text(cls, value, info):
|
||||
if value is not None:
|
||||
validate_database_string(value)
|
||||
if info.field_name == "query" and not value.strip():
|
||||
raise ValueError("Search text cannot be blank")
|
||||
if info.field_name == "query":
|
||||
value = clean_search_query(value)
|
||||
if not value.strip():
|
||||
raise ValueError("Search text cannot be blank")
|
||||
return value
|
||||
|
||||
|
||||
|
||||
@@ -188,3 +188,15 @@ def terminal_failure_reason(response):
|
||||
if status == "incomplete":
|
||||
return "PROVIDER_RESPONSE_INCOMPLETE"
|
||||
return "PROVIDER_RESPONSE_UNEXPECTED_STATUS"
|
||||
|
||||
|
||||
def provider_error_summary(session_id, error):
|
||||
"""Only known signatures cross the diagnostic boundary, never provider messages."""
|
||||
allowed = {'response_failed', 'conversation_already_has_active_response',
|
||||
'invalid_request_error', 'response_cancel_not_active', 's2s_history_failed',
|
||||
'server_error', 'rate_limit_exceeded', 'insufficient_quota',
|
||||
'unknown_or_invalid_event', 'invalid_conversation_item'}
|
||||
signature = {key: value if isinstance(value, str) and value in allowed else 'other'
|
||||
for key in ('type', 'code') for value in (error.get(key),)}
|
||||
logger.warning('Voice provider error session=%s type=%s code=%s',
|
||||
session_id, signature['type'], signature['code'])
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
from hashlib import sha256
|
||||
from urllib.parse import urlsplit
|
||||
from typing import Literal
|
||||
from pydantic import BaseModel, Field, SecretStr, field_validator
|
||||
from pydantic import BaseModel, Field, SecretStr, field_validator, model_validator
|
||||
from app.modules.voice.provider import canonical_json
|
||||
|
||||
UPSTREAM_REVISION = '619e3fe4f71d1c6f35c15870d588a3638de34722'
|
||||
@@ -24,7 +24,11 @@ RESPONSIVE_ASR_PROMPT = 'Transcribe conversational Iranian Persian faithfully, i
|
||||
|
||||
class LocalS2SSettings(BaseModel):
|
||||
local_s2s_enabled: bool = False
|
||||
local_s2s_component_provider: Literal['split', 'gapgpt'] = 'split'
|
||||
local_s2s_tts_provider: Literal['upstream', 'elevenlabs'] = 'upstream'
|
||||
local_s2s_stt_provider: Literal['upstream', 'elevenlabs'] = 'upstream'
|
||||
local_s2s_tts_speed: float = Field(default=1.0, ge=0.25, le=4.0, allow_inf_nan=False)
|
||||
local_s2s_strict_grounding: bool = False
|
||||
local_s2s_responsive: bool = False
|
||||
local_s2s_retain_interrupted_answers: bool = False
|
||||
local_s2s_endpoint: str = 'ws://local-s2s-engine:8765/v1/realtime'
|
||||
@@ -58,6 +62,12 @@ class LocalS2SSettings(BaseModel):
|
||||
raise ValueError('Invalid local component identifier')
|
||||
return value
|
||||
|
||||
@model_validator(mode='after')
|
||||
def tts_provider_speed(self):
|
||||
if self.local_s2s_tts_provider == 'elevenlabs' and not 0.7 <= self.local_s2s_tts_speed <= 1.2:
|
||||
raise ValueError('ElevenLabs speed must be between 0.7 and 1.2')
|
||||
return self
|
||||
|
||||
def components(self):
|
||||
result = dict(stt=dict(backend='openai', model=self.local_s2s_stt_model,
|
||||
language='fa', response_format='json', final_only=True),
|
||||
@@ -66,10 +76,17 @@ class LocalS2SSettings(BaseModel):
|
||||
tts=dict(backend='openai', model=self.local_s2s_tts_model,
|
||||
voice=self.local_s2s_tts_voice, response_format='pcm', sample_rate=24000),
|
||||
request_timeout_seconds=self.local_s2s_request_timeout_seconds)
|
||||
if self.local_s2s_stt_provider != 'upstream':
|
||||
result['stt']['provider'] = self.local_s2s_stt_provider
|
||||
if self.local_s2s_tts_provider != 'upstream':
|
||||
result['tts']['provider'] = self.local_s2s_tts_provider
|
||||
if self.local_s2s_component_provider != 'split':
|
||||
result['upstream_provider'] = self.local_s2s_component_provider
|
||||
if self.local_s2s_tts_speed != 1.0:
|
||||
result['tts']['speed'] = self.local_s2s_tts_speed
|
||||
if self.local_s2s_responsive:
|
||||
result['stt'].update(temperature=0, prompt=RESPONSIVE_ASR_PROMPT)
|
||||
if self.local_s2s_stt_provider == 'upstream':
|
||||
result['stt'].update(temperature=0, prompt=RESPONSIVE_ASR_PROMPT)
|
||||
result['llm']['stream_batch_sentences'] = 1
|
||||
return result
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Public identifiers only; deployment owns the single model for each role."""
|
||||
|
||||
|
||||
def model_catalog(ingest, voice):
|
||||
rows = []
|
||||
for role, label, model in (
|
||||
('embedding', 'مدل امبدینگ', ingest.embedding_model),
|
||||
('ocr', 'مدل استخراج اسناد', ingest.vision_model),
|
||||
):
|
||||
if model:
|
||||
rows.append(dict(id=role, label=label, model=model))
|
||||
if 'local_s2s' in {voice.provider, *voice.voice_selectable_providers} and voice.local_s2s_enabled:
|
||||
for role, label, model in (
|
||||
('dialogue', 'مدل گفتگوی سرویس لوکال', voice.local_s2s_llm_model),
|
||||
('stt', 'تبدیل گفتار به متن سرویس لوکال', voice.local_s2s_stt_model),
|
||||
('tts', 'تبدیل متن به گفتار سرویس لوکال', voice.local_s2s_tts_model),
|
||||
):
|
||||
if model:
|
||||
rows.append(dict(id=role, label=label, model=model))
|
||||
for provider in ('openai', 'gemini'):
|
||||
if provider in {voice.provider, *voice.voice_selectable_providers}:
|
||||
model = voice.openai_realtime_model if provider == 'openai' else voice.gemini_model
|
||||
rows.append(dict(id=provider, label='مدل صوتی ' + provider, model=model))
|
||||
return rows
|
||||
@@ -1748,6 +1748,8 @@ class VoiceRuntime:
|
||||
error = event["error"]
|
||||
if not isinstance(error, dict):
|
||||
raise ValueError("Provider error object required")
|
||||
from app.modules.voice.diagnostics import provider_error_summary
|
||||
provider_error_summary(self.session_id, error)
|
||||
matches = [r for r in self.responses.values()
|
||||
if r.cancel_deadline is not None and r.cancel_event == error.get("event_id")]
|
||||
cleanup = next((a for a in self.audio.values()
|
||||
|
||||
Reference in New Issue
Block a user