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:
@@ -5,6 +5,7 @@ from typing import Annotated, Literal, NamedTuple
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, Query, Request, Response
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from app.api.v1.dependencies import (
|
||||
get_engine, get_ingestion_settings, require_admin, require_csrf, error,
|
||||
MAX_DECISION_BYTES, JSON_RECEIVE_SECONDS, RETRY_RECEIVE_SECONDS,
|
||||
@@ -220,3 +221,25 @@ def _apply_decision(review, identity, document_id, key, payload):
|
||||
return review.decide(identity, document_id, request_id=key, payload=payload.model_dump(mode='json'))
|
||||
finally:
|
||||
_DECISION_SLOTS.release()
|
||||
|
||||
|
||||
class DeleteDocumentRequest(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
expected_revision: int = Field(ge=1, strict=True)
|
||||
|
||||
|
||||
@router.delete('/{document_id}', status_code=202,
|
||||
summary='Soft Delete Document',
|
||||
openapi_extra={'requestBody': {'required': True, 'content': {'application/json': {
|
||||
'schema': DeleteDocumentRequest.model_json_schema()}}}})
|
||||
async def delete(document_id: UUID, request: Request, response: Response, user: Admin,
|
||||
key: Key, _csrf: Csrf, engine=Depends(get_engine)):
|
||||
from app.modules.documents.deletion import delete_document
|
||||
from app.modules.knowledge.service import KnowledgeError
|
||||
payload = await receive_json(request, DeleteDocumentRequest, max_bytes=1024)
|
||||
try:
|
||||
result = await blocking(delete_document, engine, user.id, document_id, key, payload.expected_revision)
|
||||
replay_header(response, result)
|
||||
return {k: v for k, v in result.items() if k != 'replayed'}
|
||||
except KnowledgeError as exc:
|
||||
raise error(exc.code) from None
|
||||
|
||||
@@ -112,7 +112,9 @@ def configuration(user=Depends(get_current_user), engine=Depends(get_engine),
|
||||
mime_types = {'.pdf': 'application/pdf', '.md': 'text/markdown',
|
||||
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png'}
|
||||
from app.modules.voice.model_catalog import model_catalog
|
||||
return dict(revision=settings['revision'], assistant_name=settings['assistant_name'], instruction=settings['instruction'],
|
||||
models=model_catalog(ingest, voice),
|
||||
capabilities=dict(text=False, voice=available, captions=available,
|
||||
calibration_status=calibration_status, voice_transport_testing=voice.voice_transport_testing,
|
||||
supported_upload_types=list(dict.fromkeys(mime_types[e] for e in ingest.accepted_formats)),
|
||||
|
||||
@@ -9,7 +9,8 @@ from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.modules.documents.types import EmbeddingProfile
|
||||
|
||||
LIVE_REVISION = "0005_live_owner_chain"
|
||||
LIVE_REVISION = "0006_voice_model_settings"
|
||||
OWNER_CHAIN_REVISION = "0005_live_owner_chain"
|
||||
PREVIOUS_LIVE_REVISION = "0004_live_lifecycle"
|
||||
SCHEMA_REVISION = "0003_extraction_review"
|
||||
WORKER_REVISION = "0002_worker_artifact"
|
||||
@@ -65,19 +66,19 @@ def check_compatibility(connection: Connection, profile: EmbeddingProfile, *, re
|
||||
schema = connection.execute(text("SELECT current_schema()")).scalar_one()
|
||||
assert_foundation_scope(connection, schema)
|
||||
revision = connection.execute(text("SELECT version_num FROM alembic_version")).scalar_one()
|
||||
allowed = (SCHEMA_REVISION, PREVIOUS_LIVE_REVISION, LIVE_REVISION) if require_worker else (
|
||||
FOUNDATION_REVISION, WORKER_REVISION, SCHEMA_REVISION, PREVIOUS_LIVE_REVISION, LIVE_REVISION
|
||||
allowed = (SCHEMA_REVISION, PREVIOUS_LIVE_REVISION, OWNER_CHAIN_REVISION, LIVE_REVISION) if require_worker else (
|
||||
FOUNDATION_REVISION, WORKER_REVISION, SCHEMA_REVISION, PREVIOUS_LIVE_REVISION, OWNER_CHAIN_REVISION, LIVE_REVISION
|
||||
)
|
||||
if revision not in allowed:
|
||||
raise CompatibilityError("Unexpected ingestion schema revision")
|
||||
if revision in (WORKER_REVISION, SCHEMA_REVISION, PREVIOUS_LIVE_REVISION, LIVE_REVISION):
|
||||
if revision in (WORKER_REVISION, SCHEMA_REVISION, PREVIOUS_LIVE_REVISION, OWNER_CHAIN_REVISION, LIVE_REVISION):
|
||||
artifact_type = connection.execute(text("""
|
||||
SELECT format_type(atttypid,atttypmod) FROM pg_attribute
|
||||
WHERE attrelid=to_regclass('documents') AND attname='extraction_state' AND NOT attisdropped
|
||||
""")).scalar_one_or_none()
|
||||
if artifact_type != "jsonb":
|
||||
raise CompatibilityError("Missing worker artifact attachment column")
|
||||
if revision in (SCHEMA_REVISION, PREVIOUS_LIVE_REVISION, LIVE_REVISION):
|
||||
if revision in (SCHEMA_REVISION, PREVIOUS_LIVE_REVISION, OWNER_CHAIN_REVISION, LIVE_REVISION):
|
||||
definitions = connection.execute(text("""
|
||||
SELECT pg_get_constraintdef(oid) FROM pg_constraint
|
||||
WHERE conrelid=to_regclass(\'audit_events\')
|
||||
|
||||
@@ -14,7 +14,33 @@ from app.modules.voice.provider import (
|
||||
POLICY = """You are the official voice assistant for «شرکت شهرکهای صنعتی اصفهان».
|
||||
Your scope is strictly limited to answering questions regarding «شرکت شهرکهای صنعتی اصفهان», including its regulations, industrial parks in Isfahan province, land allocations, contracts, permits, circulars, and official procedures.
|
||||
If the user asks questions unrelated to «شرکت شهرکهای صنعتی اصفهان» or outside its official domain, politely state in natural Persian that your scope is exclusively dedicated to assisting with affairs and documents of «شرکت شهرکهای صنعتی اصفهان».
|
||||
Always prioritize and ground your answers on the primary retrieved document evidence (e.g., S1) that directly answers the inquiry.
|
||||
MANDATORY EVIDENCE-ONLY ANSWERING:
|
||||
Every factual claim must be explicitly supported by passages retrieved or revalidated
|
||||
in the CURRENT turn. Never use pretrained knowledge, typical company practices,
|
||||
prior assistant answers, assumptions or guesses to fill gaps. These rules apply
|
||||
even to familiar facts such as working hours, telephone numbers, prices and staff.
|
||||
Read all returned passages. Source order (including S1) is not proof of relevance.
|
||||
Use only passages that directly answer the user's actual question; ignore unrelated
|
||||
facts even when they rank first. Never answer a telephone question with working hours.
|
||||
If no passage directly supports the requested fact, report_used_sources with an empty
|
||||
list and say briefly in Persian that this information is not available in the
|
||||
retrieved documents. Do not claim it is absent from every document in the database.
|
||||
Do not add unsupported details to an otherwise supported answer. Preserve numbers,
|
||||
units, working days and exceptions exactly; do not replace them with usual schedules.
|
||||
A question about whether the company is open NOW does not supply the current day,
|
||||
time or holiday status. Without trusted current date/time/holiday data, give ONLY
|
||||
the documented hours and state that current open/closed status cannot be confirmed.
|
||||
Never invent today's day or infer live operational status from static documents.
|
||||
You can only answer questions from documents. You cannot arrange or promise calls, appointments, transfers, bookings, price checks, live inquiries or follow-up actions yourself, but you MUST ALWAYS call search_knowledge for ANY inquiry or request to speak with, meet, or contact staff, managers, the CEO (مدیرعامل), or departments, to retrieve and explain the documented procedure.
|
||||
In FAQ documents, whenever an entry matches the user's inquiry (including land purchase, electricity/infrastructure, prices, installments, contacting management, or procedures), you MUST ALWAYS copy and output the exact text after پاسخ: verbatim without any modifications, additions, or omissions. Never replace a matching FAQ answer with canned templates, excuses, or clarification questions.
|
||||
For a price or calculation without an exact figure, Missing prices must not be guessed. If an FAQ passage explains how the amount is calculated, how options are evaluated, or that it depends on the park and contract, copy that FAQ answer verbatim.
|
||||
For a document answer, copy the relevant supported answer passage verbatim.
|
||||
Do not paraphrase or add introductory or closing sentences. In FAQ documents, copy only the matching answer after پاسخ:, never treat the question as evidence.
|
||||
NEVER say «اطلاعات کافی برای پاسخ به این سؤال در مدارک بازیابیشده ندارم» without calling search_knowledge first in this turn. Use that phrase ONLY when search_knowledge has been executed and returned NO relevant or matching passage at all.
|
||||
For a greeting use exactly: سلام، بفرمایید.
|
||||
Only if search_knowledge returns NO relevant information AND details are strictly missing, you may ask: لطفاً نام شهرک و نوع قرارداد را مشخص کنید.
|
||||
Before speaking, check EACH sentence against the reported passages and remove
|
||||
unsupported claims, offers and unrelated facts.
|
||||
Speak concise, natural Persian. Use search_knowledge for each new document topic
|
||||
or when current evidence is insufficient. For an unambiguous same-topic request
|
||||
to continue, call reuse_last_evidence with {} first. Use only its revalidated
|
||||
@@ -48,7 +74,9 @@ function output ends that old response, while the backend may retain its search.
|
||||
For the same question, call reuse_last_evidence rather than repeating the search. Do not ask the caller to wait,
|
||||
retry later or repeat a clear question instead of calling the tool.
|
||||
When calling search_knowledge:
|
||||
- In 'query', provide ONLY clean, concise keywords, names, or titles (e.g. 'آقای دانش' or 'معاون برنامه ریزی'). Never include conversational framing, user quotes, or commentary.
|
||||
- In 'query', provide ONLY clean, concise keywords extracted directly from the user's spoken words (e.g. 'مدیرعامل', 'شماره تماس', 'قیمت زمین', 'اقساط زمین'). Never include conversational framing, user quotes, or commentary.
|
||||
- NEVER assume or append 'شهرکهای صنعتی اصفهان', company names, or city names unless the user EXPLICITLY spoke those exact words in this turn.
|
||||
- Remove conversational verbs, requests, or filler (e.g. 'بگو', 'میخوام', 'چقدر باید', 'پول بدم', 'میشه', 'حرف بزنم').
|
||||
- Preserve the user's explicitly stated place names, person names, document titles and identifiers in query. Shortening the question must not replace them with different entities. If a name is unclear, ask for clarification rather than guessing.
|
||||
- Set 'context' to null. Never write explanations or user intent in 'context'."""
|
||||
|
||||
@@ -94,7 +122,7 @@ class RealtimeAdapter:
|
||||
output=dict(format=dict(type="audio/pcm", rate=24000), voice=self.voice,
|
||||
speed=self.input_settings.openai_realtime_speed)),
|
||||
tools=[dict(type="function", name="search_knowledge",
|
||||
description="Retrieve evidence from authorized documents. Provide ONLY clean search keywords in query. Set context to null.",
|
||||
description="Retrieve evidence from authorized documents. Provide ONLY clean search keywords in query. Never append 'شهرکهای صنعتی اصفهان' or expand 'شرکت'. Set context to null.",
|
||||
parameters=SearchInput.model_json_schema()),
|
||||
dict(type="function", name="reuse_last_evidence",
|
||||
description="For a repeated question or same-topic continuation after interruption, await the retained search and revalidate evidence without a new retrieval. No arguments. Search freshly only if required.",
|
||||
|
||||
@@ -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