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:
@@ -176,3 +176,21 @@ LOCAL_S2S_TOKEN=
|
|||||||
# LOCAL_S2S_NLTK_SOURCE=<local-unpacked-nltk-data>
|
# LOCAL_S2S_NLTK_SOURCE=<local-unpacked-nltk-data>
|
||||||
# LOCAL_S2S_ASSET_MANIFEST_SOURCE=<local-assets.json>
|
# LOCAL_S2S_ASSET_MANIFEST_SOURCE=<local-assets.json>
|
||||||
# LOCAL_S2S_ASSET_MANIFEST_SHA256=<reviewed-manifest-sha256>
|
# LOCAL_S2S_ASSET_MANIFEST_SHA256=<reviewed-manifest-sha256>
|
||||||
|
|
||||||
|
# Local S2S components only: split (existing OpenRouter/OpenAI routes) or gapgpt.
|
||||||
|
# Set LOCAL_S2S_COMPONENT_PROVIDER in both API and engine for frozen profile identity.
|
||||||
|
LOCAL_S2S_COMPONENT_PROVIDER=split
|
||||||
|
GAPGPT_API_KEY=
|
||||||
|
# Engine-only alternative to GAPGPT_API_KEY; never mount the key into the browser/API.
|
||||||
|
# GAPGPT_API_KEY_FILE=/run/secrets/gapgpt_api_key
|
||||||
|
|
||||||
|
# Optional engine-only TTS override. STT/LLM keep LOCAL_S2S_COMPONENT_PROVIDER.
|
||||||
|
LOCAL_S2S_TTS_PROVIDER=upstream
|
||||||
|
ELEVENLABS_API_KEY=
|
||||||
|
# ELEVENLABS_API_KEY_FILE=/run/secrets/elevenlabs_api_key
|
||||||
|
|
||||||
|
# Optional engine-only STT override; uses the same ELEVENLABS_API_KEY(_FILE).
|
||||||
|
LOCAL_S2S_STT_PROVIDER=upstream
|
||||||
|
|
||||||
|
# Local engine: validate extractive current-turn answers before TTS.
|
||||||
|
LOCAL_S2S_STRICT_GROUNDING=false
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ from typing import Annotated, Literal, NamedTuple
|
|||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, Header, Query, Request, Response
|
from fastapi import APIRouter, Depends, Header, Query, Request, Response
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field
|
||||||
from app.api.v1.dependencies import (
|
from app.api.v1.dependencies import (
|
||||||
get_engine, get_ingestion_settings, require_admin, require_csrf, error,
|
get_engine, get_ingestion_settings, require_admin, require_csrf, error,
|
||||||
MAX_DECISION_BYTES, JSON_RECEIVE_SECONDS, RETRY_RECEIVE_SECONDS,
|
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'))
|
return review.decide(identity, document_id, request_id=key, payload=payload.model_dump(mode='json'))
|
||||||
finally:
|
finally:
|
||||||
_DECISION_SLOTS.release()
|
_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',
|
mime_types = {'.pdf': 'application/pdf', '.md': 'text/markdown',
|
||||||
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||||
'.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png'}
|
'.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'],
|
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,
|
capabilities=dict(text=False, voice=available, captions=available,
|
||||||
calibration_status=calibration_status, voice_transport_testing=voice.voice_transport_testing,
|
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)),
|
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
|
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"
|
PREVIOUS_LIVE_REVISION = "0004_live_lifecycle"
|
||||||
SCHEMA_REVISION = "0003_extraction_review"
|
SCHEMA_REVISION = "0003_extraction_review"
|
||||||
WORKER_REVISION = "0002_worker_artifact"
|
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()
|
schema = connection.execute(text("SELECT current_schema()")).scalar_one()
|
||||||
assert_foundation_scope(connection, schema)
|
assert_foundation_scope(connection, schema)
|
||||||
revision = connection.execute(text("SELECT version_num FROM alembic_version")).scalar_one()
|
revision = connection.execute(text("SELECT version_num FROM alembic_version")).scalar_one()
|
||||||
allowed = (SCHEMA_REVISION, PREVIOUS_LIVE_REVISION, LIVE_REVISION) if require_worker else (
|
allowed = (SCHEMA_REVISION, PREVIOUS_LIVE_REVISION, OWNER_CHAIN_REVISION, LIVE_REVISION) if require_worker else (
|
||||||
FOUNDATION_REVISION, WORKER_REVISION, SCHEMA_REVISION, PREVIOUS_LIVE_REVISION, LIVE_REVISION
|
FOUNDATION_REVISION, WORKER_REVISION, SCHEMA_REVISION, PREVIOUS_LIVE_REVISION, OWNER_CHAIN_REVISION, LIVE_REVISION
|
||||||
)
|
)
|
||||||
if revision not in allowed:
|
if revision not in allowed:
|
||||||
raise CompatibilityError("Unexpected ingestion schema revision")
|
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("""
|
artifact_type = connection.execute(text("""
|
||||||
SELECT format_type(atttypid,atttypmod) FROM pg_attribute
|
SELECT format_type(atttypid,atttypmod) FROM pg_attribute
|
||||||
WHERE attrelid=to_regclass('documents') AND attname='extraction_state' AND NOT attisdropped
|
WHERE attrelid=to_regclass('documents') AND attname='extraction_state' AND NOT attisdropped
|
||||||
""")).scalar_one_or_none()
|
""")).scalar_one_or_none()
|
||||||
if artifact_type != "jsonb":
|
if artifact_type != "jsonb":
|
||||||
raise CompatibilityError("Missing worker artifact attachment column")
|
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("""
|
definitions = connection.execute(text("""
|
||||||
SELECT pg_get_constraintdef(oid) FROM pg_constraint
|
SELECT pg_get_constraintdef(oid) FROM pg_constraint
|
||||||
WHERE conrelid=to_regclass(\'audit_events\')
|
WHERE conrelid=to_regclass(\'audit_events\')
|
||||||
|
|||||||
@@ -14,7 +14,33 @@ from app.modules.voice.provider import (
|
|||||||
POLICY = """You are the official voice assistant for «شرکت شهرکهای صنعتی اصفهان».
|
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.
|
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 «شرکت شهرکهای صنعتی اصفهان».
|
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
|
Speak concise, natural Persian. Use search_knowledge for each new document topic
|
||||||
or when current evidence is insufficient. For an unambiguous same-topic request
|
or when current evidence is insufficient. For an unambiguous same-topic request
|
||||||
to continue, call reuse_last_evidence with {} first. Use only its revalidated
|
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,
|
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.
|
retry later or repeat a clear question instead of calling the tool.
|
||||||
When calling search_knowledge:
|
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.
|
- 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'."""
|
- 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,
|
output=dict(format=dict(type="audio/pcm", rate=24000), voice=self.voice,
|
||||||
speed=self.input_settings.openai_realtime_speed)),
|
speed=self.input_settings.openai_realtime_speed)),
|
||||||
tools=[dict(type="function", name="search_knowledge",
|
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()),
|
parameters=SearchInput.model_json_schema()),
|
||||||
dict(type="function", name="reuse_last_evidence",
|
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.",
|
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
|
from app.modules.knowledge.lexical import LEXICAL_POLICY
|
||||||
|
|
||||||
MAX_BRANCH_CANDIDATES = 50
|
MAX_BRANCH_CANDIDATES = 50
|
||||||
MAX_CHUNKS = 5
|
MAX_CHUNKS = 10
|
||||||
MAX_EVIDENCE_CHARACTERS = 12000
|
MAX_EVIDENCE_CHARACTERS = 12000
|
||||||
RETRIEVAL_POLICY = f"exact-first-cosine-id-50x2-whole-5-12000/{LEXICAL_POLICY}"
|
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 contextlib import ExitStack, contextmanager
|
||||||
from dataclasses import asdict
|
from dataclasses import asdict
|
||||||
import json
|
import json
|
||||||
|
import re
|
||||||
from uuid import UUID, uuid4
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
|
from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
|
||||||
@@ -75,12 +76,28 @@ def sql_error(exc):
|
|||||||
and exc.connection_invalidated)))
|
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):
|
class SearchInput(BaseModel):
|
||||||
model_config = ConfigDict(extra="forbid", strict=True)
|
model_config = ConfigDict(extra="forbid", strict=True)
|
||||||
query: str = Field(
|
query: str = Field(
|
||||||
min_length=1,
|
min_length=1,
|
||||||
max_length=2000,
|
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(
|
context: str | None = Field(
|
||||||
default=None,
|
default=None,
|
||||||
@@ -93,7 +110,9 @@ class SearchInput(BaseModel):
|
|||||||
def database_text(cls, value, info):
|
def database_text(cls, value, info):
|
||||||
if value is not None:
|
if value is not None:
|
||||||
validate_database_string(value)
|
validate_database_string(value)
|
||||||
if info.field_name == "query" and not value.strip():
|
if info.field_name == "query":
|
||||||
|
value = clean_search_query(value)
|
||||||
|
if not value.strip():
|
||||||
raise ValueError("Search text cannot be blank")
|
raise ValueError("Search text cannot be blank")
|
||||||
return value
|
return value
|
||||||
|
|
||||||
|
|||||||
@@ -188,3 +188,15 @@ def terminal_failure_reason(response):
|
|||||||
if status == "incomplete":
|
if status == "incomplete":
|
||||||
return "PROVIDER_RESPONSE_INCOMPLETE"
|
return "PROVIDER_RESPONSE_INCOMPLETE"
|
||||||
return "PROVIDER_RESPONSE_UNEXPECTED_STATUS"
|
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 hashlib import sha256
|
||||||
from urllib.parse import urlsplit
|
from urllib.parse import urlsplit
|
||||||
from typing import Literal
|
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
|
from app.modules.voice.provider import canonical_json
|
||||||
|
|
||||||
UPSTREAM_REVISION = '619e3fe4f71d1c6f35c15870d588a3638de34722'
|
UPSTREAM_REVISION = '619e3fe4f71d1c6f35c15870d588a3638de34722'
|
||||||
@@ -24,7 +24,11 @@ RESPONSIVE_ASR_PROMPT = 'Transcribe conversational Iranian Persian faithfully, i
|
|||||||
|
|
||||||
class LocalS2SSettings(BaseModel):
|
class LocalS2SSettings(BaseModel):
|
||||||
local_s2s_enabled: bool = False
|
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_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_responsive: bool = False
|
||||||
local_s2s_retain_interrupted_answers: bool = False
|
local_s2s_retain_interrupted_answers: bool = False
|
||||||
local_s2s_endpoint: str = 'ws://local-s2s-engine:8765/v1/realtime'
|
local_s2s_endpoint: str = 'ws://local-s2s-engine:8765/v1/realtime'
|
||||||
@@ -58,6 +62,12 @@ class LocalS2SSettings(BaseModel):
|
|||||||
raise ValueError('Invalid local component identifier')
|
raise ValueError('Invalid local component identifier')
|
||||||
return value
|
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):
|
def components(self):
|
||||||
result = dict(stt=dict(backend='openai', model=self.local_s2s_stt_model,
|
result = dict(stt=dict(backend='openai', model=self.local_s2s_stt_model,
|
||||||
language='fa', response_format='json', final_only=True),
|
language='fa', response_format='json', final_only=True),
|
||||||
@@ -66,9 +76,16 @@ class LocalS2SSettings(BaseModel):
|
|||||||
tts=dict(backend='openai', model=self.local_s2s_tts_model,
|
tts=dict(backend='openai', model=self.local_s2s_tts_model,
|
||||||
voice=self.local_s2s_tts_voice, response_format='pcm', sample_rate=24000),
|
voice=self.local_s2s_tts_voice, response_format='pcm', sample_rate=24000),
|
||||||
request_timeout_seconds=self.local_s2s_request_timeout_seconds)
|
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:
|
if self.local_s2s_tts_speed != 1.0:
|
||||||
result['tts']['speed'] = self.local_s2s_tts_speed
|
result['tts']['speed'] = self.local_s2s_tts_speed
|
||||||
if self.local_s2s_responsive:
|
if self.local_s2s_responsive:
|
||||||
|
if self.local_s2s_stt_provider == 'upstream':
|
||||||
result['stt'].update(temperature=0, prompt=RESPONSIVE_ASR_PROMPT)
|
result['stt'].update(temperature=0, prompt=RESPONSIVE_ASR_PROMPT)
|
||||||
result['llm']['stream_batch_sentences'] = 1
|
result['llm']['stream_batch_sentences'] = 1
|
||||||
return result
|
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"]
|
error = event["error"]
|
||||||
if not isinstance(error, dict):
|
if not isinstance(error, dict):
|
||||||
raise ValueError("Provider error object required")
|
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()
|
matches = [r for r in self.responses.values()
|
||||||
if r.cancel_deadline is not None and r.cancel_event == error.get("event_id")]
|
if r.cancel_deadline is not None and r.cancel_event == error.get("event_id")]
|
||||||
cleanup = next((a for a in self.audio.values()
|
cleanup = next((a for a in self.audio.values()
|
||||||
|
|||||||
@@ -3,6 +3,9 @@ name: rag-local-s2s-test
|
|||||||
x-candidate-env: &candidate-env
|
x-candidate-env: &candidate-env
|
||||||
PROVIDER: local_s2s
|
PROVIDER: local_s2s
|
||||||
VOICE_PROVIDER: local_s2s
|
VOICE_PROVIDER: local_s2s
|
||||||
|
LOCAL_S2S_COMPONENT_PROVIDER: ${LOCAL_S2S_COMPONENT_PROVIDER:-split}
|
||||||
|
LOCAL_S2S_TTS_PROVIDER: ${LOCAL_S2S_TTS_PROVIDER:-upstream}
|
||||||
|
LOCAL_S2S_STT_PROVIDER: ${LOCAL_S2S_STT_PROVIDER:-upstream}
|
||||||
LOCAL_S2S_ENABLED: ${LOCAL_S2S_ENABLE_CANDIDATE:-false}
|
LOCAL_S2S_ENABLED: ${LOCAL_S2S_ENABLE_CANDIDATE:-false}
|
||||||
VOICE_TRANSPORT_TESTING: "true"
|
VOICE_TRANSPORT_TESTING: "true"
|
||||||
LOCAL_S2S_ENDPOINT: ws://local-s2s-engine:8765/v1/realtime
|
LOCAL_S2S_ENDPOINT: ws://local-s2s-engine:8765/v1/realtime
|
||||||
@@ -61,6 +64,12 @@ services:
|
|||||||
# No database URL or application identity is supplied to the engine.
|
# No database URL or application identity is supplied to the engine.
|
||||||
# The inference key is sent only to the engine, never to the API/browser.
|
# The inference key is sent only to the engine, never to the API/browser.
|
||||||
OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-}
|
OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-}
|
||||||
|
LOCAL_S2S_COMPONENT_PROVIDER: ${LOCAL_S2S_COMPONENT_PROVIDER:-split}
|
||||||
|
GAPGPT_API_KEY: ${GAPGPT_API_KEY:-}
|
||||||
|
LOCAL_S2S_TTS_PROVIDER: ${LOCAL_S2S_TTS_PROVIDER:-upstream}
|
||||||
|
LOCAL_S2S_STT_PROVIDER: ${LOCAL_S2S_STT_PROVIDER:-upstream}
|
||||||
|
ELEVENLABS_API_KEY: ${ELEVENLABS_API_KEY:-}
|
||||||
|
LOCAL_S2S_STRICT_GROUNDING: ${LOCAL_S2S_STRICT_GROUNDING:-false}
|
||||||
LOCAL_S2S_ALLOW_PAID_STARTUP: ${LOCAL_S2S_ALLOW_PAID_STARTUP:-false}
|
LOCAL_S2S_ALLOW_PAID_STARTUP: ${LOCAL_S2S_ALLOW_PAID_STARTUP:-false}
|
||||||
LOCAL_S2S_SILERO_SOURCE: /vad/silero-vad
|
LOCAL_S2S_SILERO_SOURCE: /vad/silero-vad
|
||||||
LOCAL_S2S_NLTK_DATA: /assets/nltk
|
LOCAL_S2S_NLTK_DATA: /assets/nltk
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
"""Organization speech model selection; applied older revisions remain immutable."""
|
||||||
|
from alembic import op
|
||||||
|
revision = '0006_voice_model_settings'
|
||||||
|
down_revision = '0005_live_owner_chain'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade(**kwargs):
|
||||||
|
op.execute("ALTER TABLE organization_settings ADD COLUMN voice_models jsonb NOT NULL DEFAULT '{}'::jsonb CHECK (jsonb_typeof(voice_models)='object')")
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade(**kwargs):
|
||||||
|
op.execute('ALTER TABLE organization_settings DROP COLUMN voice_models')
|
||||||
@@ -2,6 +2,8 @@
|
|||||||
import asyncio
|
import asyncio
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
|
from contextvars import ContextVar
|
||||||
|
from uuid import uuid4
|
||||||
from collections import Counter
|
from collections import Counter
|
||||||
import socket
|
import socket
|
||||||
from threading import Event, Thread
|
from threading import Event, Thread
|
||||||
@@ -11,6 +13,15 @@ import httpx
|
|||||||
CLEANUP_WINDOW_SECONDS = 1.0
|
CLEANUP_WINDOW_SECONDS = 1.0
|
||||||
HALF_CLOSE_HEADER = 'x-local-s2s-half-close'
|
HALF_CLOSE_HEADER = 'x-local-s2s-half-close'
|
||||||
|
|
||||||
|
REQUEST_TRACE = ContextVar('local_component_trace', default=None)
|
||||||
|
|
||||||
|
|
||||||
|
def trace_phase(phase, **values):
|
||||||
|
state = REQUEST_TRACE.get()
|
||||||
|
if state is not None:
|
||||||
|
state.update(phase=phase, **values)
|
||||||
|
|
||||||
|
|
||||||
LIMITS = {'/v1/audio/transcriptions': (1100000, 65536),
|
LIMITS = {'/v1/audio/transcriptions': (1100000, 65536),
|
||||||
'/v1/chat/completions': (1048576, 1048576),
|
'/v1/chat/completions': (1048576, 1048576),
|
||||||
'/v1/audio/speech': (16384, 1440000)}
|
'/v1/audio/speech': (16384, 1440000)}
|
||||||
@@ -21,12 +32,27 @@ class EvaluationBudgetExhausted(ValueError):
|
|||||||
|
|
||||||
|
|
||||||
class ComponentServer:
|
class ComponentServer:
|
||||||
def __init__(self, key, *, port=8766, transport=None, timeout=30, inactivity=None, responsive=False):
|
def __init__(self, key, *, port=8766, transport=None, timeout=30, inactivity=None, responsive=False, provider='split', tts_provider='upstream', tts_key=None, stt_provider='upstream', stt_key=None, strict_grounding=False):
|
||||||
if not key or not key.isascii() or any(c.isspace() for c in key):
|
if not key or not key.isascii() or any(c.isspace() for c in key):
|
||||||
raise ValueError('LOCAL_COMPONENT_CREDENTIAL_REQUIRED')
|
raise ValueError('LOCAL_COMPONENT_CREDENTIAL_REQUIRED')
|
||||||
|
if provider not in ('split', 'gapgpt'):
|
||||||
|
raise ValueError('LOCAL_COMPONENT_PROVIDER_UNSUPPORTED')
|
||||||
|
if tts_provider not in ('upstream', 'elevenlabs'):
|
||||||
|
raise ValueError('LOCAL_TTS_PROVIDER_UNSUPPORTED')
|
||||||
|
if tts_provider == 'elevenlabs' and (not tts_key or not tts_key.isascii() or any(c.isspace() for c in tts_key)):
|
||||||
|
raise ValueError('LOCAL_ELEVENLABS_CREDENTIAL_REQUIRED')
|
||||||
|
if stt_provider not in ('upstream', 'elevenlabs'):
|
||||||
|
raise ValueError('LOCAL_STT_PROVIDER_UNSUPPORTED')
|
||||||
|
if stt_provider == 'elevenlabs' and (not stt_key or not stt_key.isascii() or any(c.isspace() for c in stt_key)):
|
||||||
|
raise ValueError('LOCAL_ELEVENLABS_CREDENTIAL_REQUIRED')
|
||||||
|
self.strict_grounding = strict_grounding
|
||||||
|
self.stt_provider, self.stt_key = stt_provider, stt_key
|
||||||
|
self.tts_provider, self.tts_key = tts_provider, tts_key
|
||||||
|
self.provider = provider
|
||||||
self.responsive = responsive
|
self.responsive = responsive
|
||||||
self.key, self.transport, self.timeout = key, transport, timeout
|
self.key, self.transport, self.timeout = key, transport, timeout
|
||||||
self.inactivity = min(timeout, 5) if inactivity is None else min(timeout, inactivity)
|
default_inactivity = timeout if provider == 'gapgpt' else min(timeout, 5)
|
||||||
|
self.inactivity = default_inactivity if inactivity is None else min(timeout, inactivity)
|
||||||
if self.timeout <= 0 or self.inactivity <= 0:
|
if self.timeout <= 0 or self.inactivity <= 0:
|
||||||
raise ValueError('LOCAL_COMPONENT_DEADLINE_REQUIRED')
|
raise ValueError('LOCAL_COMPONENT_DEADLINE_REQUIRED')
|
||||||
self.counts = Counter()
|
self.counts = Counter()
|
||||||
@@ -102,10 +128,13 @@ class ComponentServer:
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
async def _forward(self, client, writer, path, fields, body, response):
|
async def _forward(self, client, writer, path, fields, body, response):
|
||||||
url = 'https://openrouter.ai/api' + path
|
url = ('https://api.gapgpt.app' if self.provider == 'gapgpt' else 'https://openrouter.ai/api') + path
|
||||||
auth_key = self.key
|
auth_key = self.key
|
||||||
forward_body = bytes(body)
|
forward_body = bytes(body)
|
||||||
direct_asr = False
|
direct_asr = False
|
||||||
|
tts_provider = self.tts_provider
|
||||||
|
gemini_tts = False
|
||||||
|
eleven_stt = path.endswith('/transcriptions') and self.stt_provider == 'elevenlabs'
|
||||||
if path.endswith('/transcriptions'):
|
if path.endswith('/transcriptions'):
|
||||||
from email.parser import BytesParser
|
from email.parser import BytesParser
|
||||||
from email.policy import default
|
from email.policy import default
|
||||||
@@ -120,49 +149,93 @@ class ComponentServer:
|
|||||||
if path.endswith('/speech'):
|
if path.endswith('/speech'):
|
||||||
payload = json.loads(forward_body)
|
payload = json.loads(forward_body)
|
||||||
model_name = payload.get('model', '')
|
model_name = payload.get('model', '')
|
||||||
|
gemini_tts = self.provider == 'gapgpt' and model_name == 'gemini-2.5-flash-preview-tts'
|
||||||
|
if gemini_tts:
|
||||||
|
from services.local_s2s.gapgpt_audio import speech_payload
|
||||||
|
url = 'https://api.gapgpt.app/v1/chat/completions'
|
||||||
|
forward_body = json.dumps(speech_payload(payload)).encode()
|
||||||
direct_tts = model_name.startswith(('openai/', 'gpt-', 'tts-'))
|
direct_tts = model_name.startswith(('openai/', 'gpt-', 'tts-'))
|
||||||
if direct_tts and model_name.startswith('openai/'):
|
if direct_tts and model_name.startswith('openai/'):
|
||||||
payload['model'] = model_name.removeprefix('openai/')
|
payload['model'] = model_name.removeprefix('openai/')
|
||||||
forward_body = json.dumps(payload).encode()
|
forward_body = json.dumps(payload).encode()
|
||||||
else:
|
else:
|
||||||
direct_tts = False
|
direct_tts = False
|
||||||
if direct_asr or direct_tts:
|
if ((direct_asr and not eleven_stt) or (direct_tts and tts_provider != 'elevenlabs')) and self.provider == 'split':
|
||||||
url = 'https://api.openai.com' + path
|
url = 'https://api.openai.com' + path
|
||||||
auth_key = os.environ.get('OPENAI_API_KEY', '')
|
auth_key = os.environ.get('OPENAI_API_KEY', '')
|
||||||
if not auth_key:
|
if not auth_key:
|
||||||
raise ValueError('LOCAL_OPENAI_CREDENTIAL_REQUIRED')
|
raise ValueError('LOCAL_OPENAI_CREDENTIAL_REQUIRED')
|
||||||
|
|
||||||
|
eleven_tts = path.endswith('/speech') and tts_provider == 'elevenlabs'
|
||||||
|
if eleven_tts:
|
||||||
|
voice = payload.get('voice', '')
|
||||||
|
if not voice.isascii() or not voice.isalnum() or payload.get('response_format') != 'pcm':
|
||||||
|
raise ValueError('Invalid ElevenLabs speech request')
|
||||||
|
url = 'https://api.elevenlabs.io/v1/text-to-speech/' + voice + '?output_format=pcm_24000'
|
||||||
|
forward_body = json.dumps(dict(text=payload['input'], model_id=payload['model'],
|
||||||
|
language_code='fa', voice_settings=dict(speed=payload.get('speed', 1.0)))).encode()
|
||||||
|
gemini_tts = False
|
||||||
|
trace_phase('upstream_headers', provider='elevenlabs' if eleven_tts or eleven_stt else ('gapgpt' if self.provider == 'gapgpt' else ('openai' if direct_asr or direct_tts else 'openrouter')))
|
||||||
request = client.build_request('POST', url,
|
request = client.build_request('POST', url,
|
||||||
headers={'Authorization': 'Bearer ' + auth_key,
|
headers={**({'xi-api-key': self.tts_key} if eleven_tts else {'Authorization': 'Bearer ' + auth_key}),
|
||||||
'Content-Type': fields.get('content-type', 'application/json'), 'Accept-Encoding': 'identity'},
|
'Content-Type': fields.get('content-type', 'application/json'), 'Accept-Encoding': 'identity'},
|
||||||
content=forward_body)
|
content=forward_body)
|
||||||
|
if eleven_stt:
|
||||||
|
from services.local_s2s.elevenlabs import transcription_request
|
||||||
|
request = transcription_request(request, self.stt_key)
|
||||||
# The owner closes the response independently, even if cancellation or a
|
# The owner closes the response independently, even if cancellation or a
|
||||||
# stalled stream prevents this operation from reaching normal completion.
|
# stalled stream prevents this operation from reaching normal completion.
|
||||||
if self.responsive and path.endswith('/transcriptions') and not direct_asr:
|
if self.provider == 'split' and self.responsive and path.endswith('/transcriptions') and not direct_asr and not eleven_stt:
|
||||||
from services.local_s2s.responsiveness import transcription_request
|
from services.local_s2s.responsiveness import transcription_request
|
||||||
request = transcription_request(request)
|
request = transcription_request(request)
|
||||||
began = self.loop.time()
|
began = self.loop.time()
|
||||||
result = await client.send(request, stream=True)
|
result = await client.send(request, stream=True)
|
||||||
header_ms = round((self.loop.time() - began) * 1000)
|
header_ms = round((self.loop.time() - began) * 1000)
|
||||||
|
trace_phase('upstream_headers_received', upstream_status=result.status_code)
|
||||||
response.append(result)
|
response.append(result)
|
||||||
if result.status_code != 200:
|
if result.status_code != 200:
|
||||||
print(json.dumps(dict(stage="component_error", component=path.rsplit("/", 1)[-1], status=result.status_code)), flush=True)
|
print(json.dumps(dict(stage="component_error", component=path.rsplit("/", 1)[-1], status=result.status_code)), flush=True)
|
||||||
|
trace_phase('upstream_status_rejected')
|
||||||
await self._error(writer, 502)
|
await self._error(writer, 502)
|
||||||
return
|
return
|
||||||
|
if gemini_tts:
|
||||||
|
from services.local_s2s.gapgpt_audio import decode_pcm
|
||||||
|
if (result.headers.get('content-type', '').split(';')[0] != 'application/json'
|
||||||
|
or result.headers.get('content-encoding', 'identity') != 'identity'):
|
||||||
|
raise ValueError('Invalid GapGPT speech media')
|
||||||
|
envelope = bytearray()
|
||||||
|
async for part in result.aiter_bytes():
|
||||||
|
envelope.extend(part)
|
||||||
|
if len(envelope) > LIMITS[path][1] * 4 // 3 + 65536:
|
||||||
|
raise ValueError('GapGPT speech capacity')
|
||||||
|
pcm = decode_pcm(json.loads(envelope), LIMITS[path][1])
|
||||||
|
result = httpx.Response(200, headers={'content-type': 'audio/pcm'}, content=pcm)
|
||||||
media = result.headers.get('content-type', '').split(';')[0]
|
media = result.headers.get('content-type', '').split(';')[0]
|
||||||
expected = ('audio/pcm', 'application/octet-stream') if path.endswith('/speech') else ('application/json', 'text/event-stream')
|
expected = ('audio/pcm', 'application/octet-stream') if path.endswith('/speech') else ('application/json', 'text/event-stream')
|
||||||
if media not in expected or result.headers.get('content-encoding', 'identity') != 'identity':
|
if media not in expected or result.headers.get('content-encoding', 'identity') != 'identity':
|
||||||
|
trace_phase('upstream_media_rejected')
|
||||||
await self._error(writer, 502)
|
await self._error(writer, 502)
|
||||||
return
|
return
|
||||||
|
if self.strict_grounding and path == '/v1/chat/completions':
|
||||||
|
from services.local_s2s.grounding import guard_response
|
||||||
|
envelope = bytearray()
|
||||||
|
async for part in result.aiter_bytes():
|
||||||
|
envelope.extend(part)
|
||||||
|
if len(envelope) > LIMITS[path][1]:
|
||||||
|
raise ValueError('Grounded response capacity')
|
||||||
|
guarded = guard_response(bytes(envelope), media, json.loads(forward_body).get('messages', []))
|
||||||
|
result = httpx.Response(200, headers={'content-type': media}, content=guarded)
|
||||||
await self._write(writer, ('HTTP/1.1 200 OK\r\nContent-Type: ' + media +
|
await self._write(writer, ('HTTP/1.1 200 OK\r\nContent-Type: ' + media +
|
||||||
'\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n').encode('ascii'))
|
'\r\nConnection: close\r\nTransfer-Encoding: chunked\r\n\r\n').encode('ascii'))
|
||||||
total = 0
|
total = 0
|
||||||
# No 8192-byte accumulation: small SSE/PCM arrivals stay observable.
|
# No 8192-byte accumulation: small SSE/PCM arrivals stay observable.
|
||||||
|
trace_phase('upstream_body')
|
||||||
async for raw in result.aiter_bytes():
|
async for raw in result.aiter_bytes():
|
||||||
if self.responsive and raw and total == 0:
|
if self.responsive and raw and total == 0:
|
||||||
print(json.dumps(dict(stage='component_first_byte', component=path.rsplit('/',1)[-1],
|
print(json.dumps(dict(stage='component_first_byte', component=path.rsplit('/',1)[-1],
|
||||||
headers_ms=header_ms, first_body_ms=round((self.loop.time()-began)*1000))),flush=True)
|
headers_ms=header_ms, first_body_ms=round((self.loop.time()-began)*1000))),flush=True)
|
||||||
total += len(raw)
|
total += len(raw)
|
||||||
|
trace_phase('upstream_body', response_bytes=total)
|
||||||
if total > LIMITS[path][1]:
|
if total > LIMITS[path][1]:
|
||||||
raise ValueError('Response capacity')
|
raise ValueError('Response capacity')
|
||||||
for offset in range(0, len(raw), 8192):
|
for offset in range(0, len(raw), 8192):
|
||||||
@@ -171,6 +244,7 @@ class ComponentServer:
|
|||||||
if not total:
|
if not total:
|
||||||
raise ValueError('Empty component response')
|
raise ValueError('Empty component response')
|
||||||
await self._write(writer, b'0\r\n\r\n')
|
await self._write(writer, b'0\r\n\r\n')
|
||||||
|
trace_phase('completed', outcome='completed')
|
||||||
|
|
||||||
async def _close_owned(self, writer, tasks, client, response):
|
async def _close_owned(self, writer, tasks, client, response):
|
||||||
writer.close()
|
writer.close()
|
||||||
@@ -197,6 +271,11 @@ class ComponentServer:
|
|||||||
|
|
||||||
async def _serve(self, reader, writer, deadline):
|
async def _serve(self, reader, writer, deadline):
|
||||||
client, tasks, response = None, [], []
|
client, tasks, response = None, [], []
|
||||||
|
began = self.loop.time()
|
||||||
|
state = dict(stage='component_request', component_request_id=uuid4().hex,
|
||||||
|
component='unknown', phase='request_headers', outcome='rejected',
|
||||||
|
timeout_ms=round(self.timeout * 1000), inactivity_ms=round(self.inactivity * 1000))
|
||||||
|
token = REQUEST_TRACE.set(state)
|
||||||
try:
|
try:
|
||||||
async with asyncio.timeout_at(deadline):
|
async with asyncio.timeout_at(deadline):
|
||||||
# Header acquisition has its own short bound, including partial headers.
|
# Header acquisition has its own short bound, including partial headers.
|
||||||
@@ -213,6 +292,7 @@ class ComponentServer:
|
|||||||
if method != 'POST' or path not in LIMITS or version not in ('HTTP/1.0', 'HTTP/1.1'):
|
if method != 'POST' or path not in LIMITS or version not in ('HTTP/1.0', 'HTTP/1.1'):
|
||||||
await self._error(writer, 403)
|
await self._error(writer, 403)
|
||||||
return
|
return
|
||||||
|
trace_phase('request_body', component=path.rsplit('/', 1)[-1])
|
||||||
request_limit, _ = LIMITS[path]
|
request_limit, _ = LIMITS[path]
|
||||||
size = int(fields.get('content-length', '-1'))
|
size = int(fields.get('content-length', '-1'))
|
||||||
if 'transfer-encoding' in fields or not 0 < size <= request_limit:
|
if 'transfer-encoding' in fields or not 0 < size <= request_limit:
|
||||||
@@ -231,6 +311,7 @@ class ComponentServer:
|
|||||||
if half_close not in (None, 'receive-response'):
|
if half_close not in (None, 'receive-response'):
|
||||||
await self._error(writer, 400)
|
await self._error(writer, 400)
|
||||||
return
|
return
|
||||||
|
state['outcome'] = 'failed'
|
||||||
self.counts[path] += 1 # one admitted provider attempt, including failed probes
|
self.counts[path] += 1 # one admitted provider attempt, including failed probes
|
||||||
client = httpx.AsyncClient(transport=self.transport, timeout=httpx.Timeout(self.inactivity, connect=self.inactivity),
|
client = httpx.AsyncClient(transport=self.transport, timeout=httpx.Timeout(self.inactivity, connect=self.inactivity),
|
||||||
follow_redirects=False, trust_env=False)
|
follow_redirects=False, trust_env=False)
|
||||||
@@ -241,21 +322,33 @@ class ComponentServer:
|
|||||||
if forwarding in done:
|
if forwarding in done:
|
||||||
forwarding.result()
|
forwarding.result()
|
||||||
else:
|
else:
|
||||||
|
state['outcome'] = 'downstream_disconnected'
|
||||||
self.counts['disconnected'] += 1
|
self.counts['disconnected'] += 1
|
||||||
except EvaluationBudgetExhausted:
|
except EvaluationBudgetExhausted:
|
||||||
|
state['outcome'] = 'budget_rejected'
|
||||||
self.counts['budget_rejected'] += 1
|
self.counts['budget_rejected'] += 1
|
||||||
await self._error(writer, 429)
|
await self._error(writer, 429)
|
||||||
except TimeoutError:
|
except TimeoutError:
|
||||||
|
state['outcome'] = 'total_or_local_timeout'
|
||||||
self.counts['expired'] += 1
|
self.counts['expired'] += 1
|
||||||
except asyncio.CancelledError:
|
except asyncio.CancelledError:
|
||||||
|
state['outcome'] = 'cancelled'
|
||||||
self.counts['cancelled'] += 1
|
self.counts['cancelled'] += 1
|
||||||
raise
|
raise
|
||||||
except (ValueError, OSError, UnicodeError, asyncio.IncompleteReadError,
|
except (ValueError, OSError, UnicodeError, asyncio.IncompleteReadError,
|
||||||
asyncio.LimitOverrunError, httpx.HTTPError):
|
asyncio.LimitOverrunError, httpx.HTTPError) as exc:
|
||||||
|
known = (httpx.ReadTimeout, httpx.ConnectTimeout, httpx.WriteTimeout, httpx.PoolTimeout,
|
||||||
|
httpx.RemoteProtocolError, httpx.ConnectError, ValueError, OSError)
|
||||||
|
state['error_type'] = next((kind.__name__ for kind in known if isinstance(exc, kind)), 'transport_error')
|
||||||
self.counts['failures'] += 1
|
self.counts['failures'] += 1
|
||||||
finally:
|
finally:
|
||||||
# No successful terminal chunk is fabricated on any failure path.
|
# No successful terminal chunk is fabricated on any failure path.
|
||||||
|
try:
|
||||||
await self._close_owned(writer, tasks, client, response)
|
await self._close_owned(writer, tasks, client, response)
|
||||||
|
finally:
|
||||||
|
state['elapsed_ms'] = round((self.loop.time() - began) * 1000)
|
||||||
|
print(json.dumps(state), flush=True)
|
||||||
|
REQUEST_TRACE.reset(token)
|
||||||
|
|
||||||
def shutdown(self):
|
def shutdown(self):
|
||||||
if self.loop is not None and self.loop.is_running():
|
if self.loop is not None and self.loop.is_running():
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
"""Native ElevenLabs STT mapping; keep the original bounded audio bytes."""
|
||||||
|
from email.parser import BytesParser
|
||||||
|
from email.policy import default
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
|
||||||
|
def transcription_request(request, key):
|
||||||
|
message = BytesParser(policy=default).parsebytes(
|
||||||
|
('Content-Type: ' + request.headers.get('content-type', '') + '\r\n\r\n').encode() + request.content)
|
||||||
|
if not message.is_multipart():
|
||||||
|
raise ValueError('Multipart transcription required')
|
||||||
|
parts = {}
|
||||||
|
for part in message.iter_parts():
|
||||||
|
name = part.get_param('name', header='content-disposition')
|
||||||
|
if name in parts:
|
||||||
|
raise ValueError('Repeated transcription field')
|
||||||
|
parts[name] = part
|
||||||
|
try:
|
||||||
|
model = parts['model'].get_payload(decode=True).decode('ascii')
|
||||||
|
language = parts['language'].get_payload(decode=True).decode('ascii') if 'language' in parts else 'fa'
|
||||||
|
audio = parts['file'].get_payload(decode=True)
|
||||||
|
except (KeyError, UnicodeError, AttributeError):
|
||||||
|
raise ValueError('Invalid transcription fields') from None
|
||||||
|
if not model or not audio or language != 'fa':
|
||||||
|
raise ValueError('Invalid transcription fields')
|
||||||
|
result = httpx.Request('POST', 'https://api.elevenlabs.io/v1/speech-to-text',
|
||||||
|
headers={'xi-api-key': key, 'Accept-Encoding': 'identity'},
|
||||||
|
data=dict(model_id=model, language_code=language, tag_audio_events='false',
|
||||||
|
diarize='false', timestamps_granularity='none'),
|
||||||
|
files={'file': ('audio.wav', audio, parts['file'].get_content_type())})
|
||||||
|
result.read()
|
||||||
|
return result
|
||||||
@@ -36,7 +36,7 @@ def build_runtime(config, stop):
|
|||||||
import speech_to_speech.TTS.openai_compatible_handler as native_tts
|
import speech_to_speech.TTS.openai_compatible_handler as native_tts
|
||||||
from services.local_s2s.request_policy import install_tts_speed
|
from services.local_s2s.request_policy import install_tts_speed
|
||||||
install_tts_speed(native_tts, config.local_s2s_tts_speed)
|
install_tts_speed(native_tts, config.local_s2s_tts_speed)
|
||||||
if config.local_s2s_responsive:
|
if config.local_s2s_responsive and config.local_s2s_stt_provider == 'upstream':
|
||||||
import speech_to_speech.STT.openai_compatible_handler as native_stt
|
import speech_to_speech.STT.openai_compatible_handler as native_stt
|
||||||
from services.local_s2s.responsiveness import install_stt_policy
|
from services.local_s2s.responsiveness import install_stt_policy
|
||||||
install_stt_policy(native_stt)
|
install_stt_policy(native_stt)
|
||||||
@@ -66,6 +66,17 @@ def build_runtime(config, stop):
|
|||||||
raise
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
def engine_credential(name, parser):
|
||||||
|
credential_file = os.environ.get(name + '_FILE')
|
||||||
|
try:
|
||||||
|
key = Path(credential_file).read_text().strip() if credential_file else os.environ.get(name, '')
|
||||||
|
except OSError:
|
||||||
|
parser.error(name + '_FILE is unreadable.')
|
||||||
|
if not key:
|
||||||
|
parser.error(name + ' is required in the engine only.')
|
||||||
|
return key
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
parser = argparse.ArgumentParser(description=__doc__)
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
parser.add_argument('--allow-paid-startup', action='store_true')
|
parser.add_argument('--allow-paid-startup', action='store_true')
|
||||||
@@ -91,11 +102,14 @@ def main():
|
|||||||
logging.disable(logging.CRITICAL)
|
logging.disable(logging.CRITICAL)
|
||||||
os.environ['HF_HUB_OFFLINE'] = '1'
|
os.environ['HF_HUB_OFFLINE'] = '1'
|
||||||
os.environ['NLTK_DATA'] = root
|
os.environ['NLTK_DATA'] = root
|
||||||
key = os.environ.get('OPENROUTER_API_KEY', '')
|
credential = 'GAPGPT_API_KEY' if config.local_s2s_component_provider == 'gapgpt' else 'OPENROUTER_API_KEY'
|
||||||
if not key:
|
key = engine_credential(credential, parser)
|
||||||
parser.error('OPENROUTER_API_KEY is required in the engine only.')
|
eleven_key = engine_credential('ELEVENLABS_API_KEY', parser) if 'elevenlabs' in (config.local_s2s_tts_provider, config.local_s2s_stt_provider) else None
|
||||||
return run_owned(lambda stop: build_runtime(config, stop), key, config.local_s2s_request_timeout_seconds,
|
return run_owned(lambda stop: build_runtime(config, stop), key, config.local_s2s_request_timeout_seconds,
|
||||||
component_options={'responsive': True} if config.local_s2s_responsive else None)
|
component_options={'responsive': config.local_s2s_responsive, 'provider': config.local_s2s_component_provider,
|
||||||
|
'tts_provider': config.local_s2s_tts_provider, 'tts_key': eleven_key,
|
||||||
|
'stt_provider': config.local_s2s_stt_provider, 'stt_key': eleven_key,
|
||||||
|
'strict_grounding': config.local_s2s_strict_grounding})
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
"""Versioned extension for the pinned engine; no history-repair capability."""
|
"""Versioned extension for the pinned engine; no history-repair capability."""
|
||||||
|
import os
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
from queue import Queue, Full
|
from queue import Queue, Full
|
||||||
from app.modules.voice.local_s2s import effective_identity
|
from app.modules.voice.local_s2s import effective_identity
|
||||||
@@ -31,10 +32,17 @@ def active_components(unit, expected):
|
|||||||
tts=dict(backend='openai', model=tts.model, voice=tts.voice,
|
tts=dict(backend='openai', model=tts.model, voice=tts.voice,
|
||||||
response_format=tts.response_format, sample_rate=tts.sample_rate),
|
response_format=tts.response_format, sample_rate=tts.sample_rate),
|
||||||
request_timeout_seconds=stt.timeout)
|
request_timeout_seconds=stt.timeout)
|
||||||
|
if 'provider' in expected['stt']:
|
||||||
|
actual['stt']['provider'] = os.environ.get('LOCAL_S2S_STT_PROVIDER', 'upstream')
|
||||||
|
if 'provider' in expected['tts']:
|
||||||
|
actual['tts']['provider'] = os.environ.get('LOCAL_S2S_TTS_PROVIDER', 'upstream')
|
||||||
|
if 'upstream_provider' in expected:
|
||||||
|
actual['upstream_provider'] = os.environ.get('LOCAL_S2S_COMPONENT_PROVIDER', 'split')
|
||||||
if 'speed' in expected['tts']:
|
if 'speed' in expected['tts']:
|
||||||
actual['tts']['speed'] = tts.speed
|
actual['tts']['speed'] = tts.speed
|
||||||
if 'temperature' in expected['stt']:
|
if 'temperature' in expected['stt']:
|
||||||
actual['stt'].update(temperature=stt.gen_kwargs.get('temperature'), prompt=stt.gen_kwargs.get('prompt'))
|
actual['stt'].update(temperature=stt.gen_kwargs.get('temperature'), prompt=stt.gen_kwargs.get('prompt'))
|
||||||
|
if 'stream_batch_sentences' in expected['llm']:
|
||||||
actual['llm']['stream_batch_sentences'] = llm.stream_batch_sentences
|
actual['llm']['stream_batch_sentences'] = llm.stream_batch_sentences
|
||||||
if (actual != expected or tts.timeout != stt.timeout or llm.request_timeout_s != stt.timeout
|
if (actual != expected or tts.timeout != stt.timeout or llm.request_timeout_s != stt.timeout
|
||||||
or stt.base_url != 'http://127.0.0.1:8766/v1' or tts.base_url != stt.base_url
|
or stt.base_url != 'http://127.0.0.1:8766/v1' or tts.base_url != stt.base_url
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
"""GapGPT Gemini TTS audio envelope to the existing bounded PCM contract."""
|
||||||
|
import base64
|
||||||
|
import binascii
|
||||||
|
from io import BytesIO
|
||||||
|
import wave
|
||||||
|
|
||||||
|
|
||||||
|
def speech_payload(payload):
|
||||||
|
return dict(model=payload['model'], stream=False, modalities=['audio'],
|
||||||
|
audio=dict(voice=payload['voice'], format='pcm16'),
|
||||||
|
messages=[dict(role='user', content=(
|
||||||
|
'Read aloud only the following text in its original language. '
|
||||||
|
f"Speak at {payload.get('speed', 1.0)} times normal pace. Text: " + payload['input']))])
|
||||||
|
|
||||||
|
|
||||||
|
def decode_pcm(payload, limit):
|
||||||
|
try:
|
||||||
|
choice, = payload['choices']
|
||||||
|
if choice['finish_reason'] != 'stop':
|
||||||
|
raise ValueError('Incomplete speech')
|
||||||
|
encoded = choice['message']['audio']['data']
|
||||||
|
if not isinstance(encoded, str) or len(encoded) > 4 * ((limit + 44 + 2) // 3):
|
||||||
|
raise ValueError('Speech capacity')
|
||||||
|
data = base64.b64decode(encoded, validate=True)
|
||||||
|
if data.startswith(b'RIFF'):
|
||||||
|
with wave.open(BytesIO(data), 'rb') as audio:
|
||||||
|
if (audio.getnchannels(), audio.getsampwidth(), audio.getframerate()) != (1, 2, 24000):
|
||||||
|
raise ValueError('Speech format')
|
||||||
|
data = audio.readframes(limit // 2 + 1)
|
||||||
|
if not data or len(data) % 2 or len(data) > limit:
|
||||||
|
raise ValueError('Speech capacity')
|
||||||
|
return data
|
||||||
|
except (KeyError, TypeError, binascii.Error, wave.Error, EOFError) as exc:
|
||||||
|
raise ValueError('Invalid GapGPT speech response') from None
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
"""Fail-closed, extractive answer gate before any local answer reaches TTS."""
|
||||||
|
import json
|
||||||
|
import unicodedata
|
||||||
|
|
||||||
|
FALLBACK = 'اطلاعات کافی برای پاسخ به این سؤال در مدارک بازیابیشده ندارم.'
|
||||||
|
SAFE = {FALLBACK, 'سلام، بفرمایید.', 'سلام.', 'لطفاً موضوع درخواستتان را مشخص کنید.', 'لطفاً نام شهرک و نوع قرارداد را مشخص کنید.'}
|
||||||
|
|
||||||
|
|
||||||
|
def normalized(value):
|
||||||
|
return ' '.join(unicodedata.normalize('NFC', value).split()).strip(' .،؛:!?؟«»"')
|
||||||
|
|
||||||
|
|
||||||
|
def evidence(messages):
|
||||||
|
# Prior turns and assistant prose are never current evidence.
|
||||||
|
start=max((i for i,m in enumerate(messages) if m.get('role')=='user'),default=len(messages))
|
||||||
|
calls={};sources={};reported=[]
|
||||||
|
for message in messages[start+1:]:
|
||||||
|
if message.get('role')=='assistant':
|
||||||
|
for call in message.get('tool_calls') or []:
|
||||||
|
calls[call.get('id')]=call.get('function',{})
|
||||||
|
elif message.get('role')=='tool':
|
||||||
|
function=calls.get(message.get('tool_call_id'),{})
|
||||||
|
try:result=json.loads(message.get('content',''))
|
||||||
|
except (ValueError,TypeError):continue
|
||||||
|
if not isinstance(result,dict) or result.get('status')!='ok':continue
|
||||||
|
if function.get('name') in ('search_knowledge','reuse_last_evidence'):
|
||||||
|
for source in result.get('sources',[]):
|
||||||
|
if isinstance(source,dict) and isinstance(source.get('text'),str):sources[source.get('source_ref')]=source['text']
|
||||||
|
elif function.get('name')=='report_used_sources':
|
||||||
|
try:reported=json.loads(function.get('arguments','{}')).get('source_refs',[])
|
||||||
|
except (ValueError,TypeError):reported=[]
|
||||||
|
return [sources[ref] for ref in reported if isinstance(ref,str) and ref in sources]
|
||||||
|
|
||||||
|
|
||||||
|
def safe_text(answer,messages):
|
||||||
|
if answer in SAFE:return answer
|
||||||
|
candidate=normalized(answer)
|
||||||
|
if not candidate:return FALLBACK
|
||||||
|
passages=evidence(messages)
|
||||||
|
for passage in passages:
|
||||||
|
# FAQ questions are not evidence of their own premise.
|
||||||
|
answer_only=passage.split('پاسخ:',1)[-1] if 'سؤال:' in passage else passage
|
||||||
|
if candidate in normalized(answer_only):return answer
|
||||||
|
# For one cited FAQ, use its actual answer rather than a generated paraphrase.
|
||||||
|
# Do not choose another source, infer relevance from rank, or synthesize facts.
|
||||||
|
if len(passages)==1 and 'سؤال:' in passages[0] and 'پاسخ:' in passages[0]:
|
||||||
|
literal=passages[0].split('پاسخ:',1)[1].strip()
|
||||||
|
if literal and len(literal)<=1200:return literal
|
||||||
|
return FALLBACK
|
||||||
|
|
||||||
|
|
||||||
|
def guard_response(raw,media,messages):
|
||||||
|
if media=='application/json':
|
||||||
|
data=json.loads(raw)
|
||||||
|
for choice in data.get('choices',[]):
|
||||||
|
message=choice['message']
|
||||||
|
message['content']=None if message.get('tool_calls') else safe_text(message.get('content') or '',messages)
|
||||||
|
return json.dumps(data,ensure_ascii=False).encode()
|
||||||
|
packets=[];done=False
|
||||||
|
for line in raw.decode('utf-8').splitlines():
|
||||||
|
if not line.startswith('data:'):continue
|
||||||
|
payload=line[5:].strip()
|
||||||
|
if payload=='[DONE]':done=True;continue
|
||||||
|
packets.append(json.loads(payload))
|
||||||
|
if not done or not packets:raise ValueError('Incomplete grounded response')
|
||||||
|
choices=[c for p in packets for c in p.get('choices',[])]
|
||||||
|
if any(c.get('delta',{}).get('tool_calls') for c in choices):
|
||||||
|
for c in choices:c.get('delta',{}).pop('content',None)
|
||||||
|
return (''.join('data: '+json.dumps(p,ensure_ascii=False)+'\n\n' for p in packets)+'data: [DONE]\n\n').encode()
|
||||||
|
answer=''.join(c.get('delta',{}).get('content') or '' for c in choices)
|
||||||
|
safe=safe_text(answer,messages)
|
||||||
|
first=packets[0]
|
||||||
|
base={key:first[key] for key in ('id','object','created','model') if key in first}
|
||||||
|
content=dict(base,choices=[dict(index=0,delta=dict(role='assistant',content=safe),finish_reason=None)])
|
||||||
|
finish=dict(base,choices=[dict(index=0,delta={},finish_reason='stop')])
|
||||||
|
return ('data: '+json.dumps(content,ensure_ascii=False)+'\n\ndata: '+json.dumps(finish)+'\n\ndata: [DONE]\n\n').encode()
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
"""Soft deletion on isolated PostgreSQL, without provider calls."""
|
||||||
|
from uuid import uuid4
|
||||||
|
import pytest
|
||||||
|
from sqlalchemy import text
|
||||||
|
from app.modules.documents.deletion import delete_document
|
||||||
|
from app.modules.knowledge.service import KnowledgeError, selection_get, selection_replace
|
||||||
|
from tests.integration.test_phase2_postgres import seeded_env, reserve, concurrent
|
||||||
|
from tests.support.search import administrator
|
||||||
|
pytestmark=pytest.mark.postgres
|
||||||
|
|
||||||
|
|
||||||
|
def test_active_delete_replay_and_revocation(seeded_env):
|
||||||
|
e=seeded_env;_,sid=reserve(e);key=uuid4()
|
||||||
|
result=delete_document(e.engine,e.actor,e.doc,key,2)
|
||||||
|
assert result['knowledge_revision']==3 and result['access_epoch']==2
|
||||||
|
assert selection_get(e.engine,e.actor)['document_ids']==[]
|
||||||
|
with e.engine.connect() as c:
|
||||||
|
row=c.execute(text('SELECT deleted_at,is_active,storage_key FROM documents WHERE id=:id'),{'id':e.doc}).one()
|
||||||
|
assert row.deleted_at is not None and not row.is_active and row.storage_key
|
||||||
|
assert c.execute(text('SELECT count(*) FROM document_chunks WHERE document_id=:id'),{'id':e.doc}).scalar_one()>0
|
||||||
|
assert c.execute(text('SELECT status FROM live_sessions WHERE id=:id'),{'id':sid}).scalar_one()=='closed'
|
||||||
|
assert delete_document(e.engine,e.actor,e.doc,key,2)==dict(result,replayed=True)
|
||||||
|
with pytest.raises(KnowledgeError) as exc:delete_document(e.engine,e.actor,e.doc,key,3)
|
||||||
|
assert exc.value.code=='IDEMPOTENCY_CONFLICT'
|
||||||
|
assert delete_document(e.engine,e.actor,e.doc,uuid4(),2)['knowledge_revision']==3
|
||||||
|
with pytest.raises(KnowledgeError) as exc:selection_replace(e.engine,e.actor,3,[e.doc])
|
||||||
|
assert exc.value.code=='NOT_FOUND'
|
||||||
|
|
||||||
|
|
||||||
|
def test_inactive_delete_preserves_revisions(seeded_env):
|
||||||
|
e=seeded_env;selection_replace(e.engine,e.actor,2,[])
|
||||||
|
before=selection_get(e.engine,e.actor)
|
||||||
|
result=delete_document(e.engine,e.actor,e.doc,uuid4(),before['revision'])
|
||||||
|
assert result['knowledge_revision']==before['revision'] and result['access_epoch']==before['access_epoch']
|
||||||
|
|
||||||
|
|
||||||
|
def test_stale_revision_does_not_delete(seeded_env):
|
||||||
|
e=seeded_env
|
||||||
|
with pytest.raises(KnowledgeError) as exc:delete_document(e.engine,e.actor,e.doc,uuid4(),1)
|
||||||
|
assert exc.value.code=='REVISION_CONFLICT'
|
||||||
|
with e.engine.connect() as c:
|
||||||
|
assert c.execute(text('SELECT deleted_at FROM documents WHERE id=:id'),{'id':e.doc}).scalar_one() is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_scope_and_role(seeded_env):
|
||||||
|
e=seeded_env;_,other=administrator(e.engine)
|
||||||
|
with pytest.raises(KnowledgeError) as exc:delete_document(e.engine,other,e.doc,uuid4(),1)
|
||||||
|
assert exc.value.code=='NOT_FOUND'
|
||||||
|
with e.engine.begin() as c:c.execute(text("UPDATE users SET role='user' WHERE id=:id"),{'id':e.actor})
|
||||||
|
with pytest.raises(KnowledgeError) as exc:delete_document(e.engine,e.actor,e.doc,uuid4(),2)
|
||||||
|
assert exc.value.code=='FORBIDDEN'
|
||||||
|
|
||||||
|
|
||||||
|
def test_concurrent_delete_deduplicates(seeded_env):
|
||||||
|
e=seeded_env;key=uuid4()
|
||||||
|
results=concurrent(*[lambda:delete_document(e.engine,e.actor,e.doc,key,2)]*2)
|
||||||
|
assert {r['replayed'] for r in results}=={True,False}
|
||||||
|
assert selection_get(e.engine,e.actor)['revision']==3
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_fences_worker(seeded_env,tmp_path):
|
||||||
|
from app.modules.documents.intake import import_document
|
||||||
|
from app.infrastructure.intake_repository import SqlIntakeRepository
|
||||||
|
from app.infrastructure.file_store import LocalFileStore
|
||||||
|
from app.infrastructure.worker_repository import SqlWorkerRepository
|
||||||
|
from app.modules.documents.worker import LostClaim
|
||||||
|
e=seeded_env
|
||||||
|
source=tmp_path/'queued.md';source.write_text('Retained original for deletion fencing.')
|
||||||
|
store=LocalFileStore(e.settings.original_directory)
|
||||||
|
row=import_document(SqlIntakeRepository(e.engine),store,e.settings,path=source,
|
||||||
|
administrator_id=e.actor,request_id=uuid4(),title='Queued')['document']
|
||||||
|
worker=SqlWorkerRepository(e.engine,e.settings)
|
||||||
|
claim=worker.claim(str(uuid4()),30)
|
||||||
|
assert claim is not None and claim.document['id']==row['id']
|
||||||
|
delete_document(e.engine,e.actor,row['id'],uuid4(),2)
|
||||||
|
with pytest.raises(LostClaim):worker.check(claim)
|
||||||
|
assert worker.claim(str(uuid4()),30) is None
|
||||||
|
|
||||||
|
|
||||||
|
from tests.integration.test_phase2_postgres import api, login
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_http_csrf_replay_and_role(api):
|
||||||
|
client,_,_,e=api
|
||||||
|
auth_headers=login(client,e)
|
||||||
|
headers={'Origin':'http://localhost:8000','Idempotency-Key':str(uuid4())}
|
||||||
|
url=f'/api/v1/documents/{e.doc}'
|
||||||
|
assert client.request('DELETE',url,json={'expected_revision':2},headers=headers).status_code==403
|
||||||
|
headers['X-CSRF-Token']=auth_headers['X-CSRF-Token']
|
||||||
|
first=client.request('DELETE',url,json={'expected_revision':2},headers=headers)
|
||||||
|
assert first.status_code==202,first.text
|
||||||
|
replay=client.request('DELETE',url,json={'expected_revision':2},headers=headers)
|
||||||
|
assert replay.status_code==202 and replay.headers['Idempotency-Replayed']=='true'
|
||||||
|
with e.engine.begin() as c:c.execute(text("UPDATE users SET role='user' WHERE id=:id"),{'id':e.actor})
|
||||||
|
assert client.request('DELETE',url,json={'expected_revision':3},headers=headers).status_code==403
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
from app.infrastructure.realtime import RealtimeAdapter
|
||||||
|
from app.modules.voice.local_s2s import setup_session
|
||||||
|
from tests.unit.test_local_s2s_phase2 import local_config
|
||||||
|
from app.modules.knowledge.evidence import admit_candidates
|
||||||
|
from tests.unit.test_search_phase2 import row
|
||||||
|
|
||||||
|
|
||||||
|
def test_phone_evidence_at_rank_eight_is_now_delivered_and_budget_is_bounded():
|
||||||
|
candidates=[row(i,text="unrelated" if i!=8 else "phone evidence") for i in range(1,14)]
|
||||||
|
sources=admit_candidates(candidates,.2)
|
||||||
|
assert len(sources)==10
|
||||||
|
assert sources[7]['text']=='phone evidence'
|
||||||
|
assert sum(len(r['text']) for r in sources)<=12000
|
||||||
|
|
||||||
|
|
||||||
|
def test_local_and_openai_use_current_turn_evidence_only_policy():
|
||||||
|
for session in (RealtimeAdapter(None).setup()['session'],setup_session(local_config())):
|
||||||
|
instructions=session['instructions']
|
||||||
|
assert 'MANDATORY EVIDENCE-ONLY ANSWERING' in instructions
|
||||||
|
assert 'CURRENT turn' in instructions
|
||||||
|
assert 'Read all returned passages' in instructions
|
||||||
|
assert 'You cannot arrange or promise calls' in instructions
|
||||||
|
assert 'Never invent today' in instructions
|
||||||
|
assert 'Missing prices must not be guessed' in instructions
|
||||||
|
|
||||||
|
import json
|
||||||
|
import pytest
|
||||||
|
from services.local_s2s.grounding import safe_text,guard_response,FALLBACK
|
||||||
|
|
||||||
|
|
||||||
|
def grounded_messages(answer='شماره مرکز شرکت 031 - 3125 است.'):
|
||||||
|
return [{'role':'user','content':'شماره تماس شرکت؟'},
|
||||||
|
{'role':'assistant','tool_calls':[{'id':'search','function':{'name':'search_knowledge','arguments':'{}'}}]},
|
||||||
|
{'role':'tool','tool_call_id':'search','content':json.dumps({'status':'ok','sources':[{'source_ref':'S1','text':'سؤال: الان تعطیله؟\nپاسخ: '+answer}]})},
|
||||||
|
{'role':'assistant','tool_calls':[{'id':'report','function':{'name':'report_used_sources','arguments':json.dumps({'source_refs':['S1']})}}]},
|
||||||
|
{'role':'tool','tool_call_id':'report','content':'{"status":"ok"}'}]
|
||||||
|
|
||||||
|
|
||||||
|
def test_gate_admits_literal_answer_and_blocks_added_facts_and_question_premise():
|
||||||
|
messages=grounded_messages()
|
||||||
|
for invented in ('شماره شرکت 031-9999 است.','ساعت کاری ۷:۳۰ تا ۱۴:۳۰ است.','وقت ملاقات هماهنگ میکنم.','الان تعطیله؟','شماره مرکز شرکت 031 - 3125 است. پنجشنبه تعطیل است.'):
|
||||||
|
assert safe_text(invented,messages)=='شماره مرکز شرکت 031 - 3125 است.'
|
||||||
|
assert safe_text('شماره مرکز شرکت 031 - 3125 است.',messages)=='شماره مرکز شرکت 031 - 3125 است.'
|
||||||
|
|
||||||
|
|
||||||
|
def test_gate_refuses_old_turn_unreported_sources_and_prior_assistant_facts():
|
||||||
|
messages=grounded_messages()
|
||||||
|
text='شماره مرکز شرکت 031 - 3125 است.'
|
||||||
|
assert safe_text(text,messages+[{'role':'user','content':'موضوع جدید'}])==FALLBACK
|
||||||
|
assert safe_text(text,messages[:3])==FALLBACK
|
||||||
|
assert safe_text(text,[{'role':'user','content':'شماره؟'},{'role':'assistant','content':text}])==FALLBACK
|
||||||
|
|
||||||
|
|
||||||
|
def test_stream_is_buffered_and_replaced_before_unsupported_words_can_reach_tts():
|
||||||
|
events=[{'id':'fixture','choices':[{'index':0,'delta':{'content':part}}]} for part in ['ساعت کاری ','۷:۳۰ تا ۱۴:۳۰ است.']]
|
||||||
|
raw=(''.join('data: '+json.dumps(e)+'\n\n' for e in events)+'data: [DONE]\n\n').encode()
|
||||||
|
result=guard_response(raw,'text/event-stream',grounded_messages()).decode()
|
||||||
|
assert 'شماره مرکز شرکت 031 - 3125 است.' in result and '۷:۳۰' not in result
|
||||||
|
with pytest.raises(ValueError):guard_response(raw.replace(b'data: [DONE]\n\n',b''),'text/event-stream',grounded_messages())
|
||||||
|
|
||||||
|
|
||||||
|
def test_stream_tool_calls_survive_without_unverified_assistant_preface():
|
||||||
|
event={'choices':[{'delta':{'content':'unsupported preface','tool_calls':[{'index':0,'id':'a','function':{'name':'search_knowledge','arguments':'{}'}}]}}]}
|
||||||
|
raw=('data: '+json.dumps(event)+'\n\ndata: [DONE]\n\n').encode()
|
||||||
|
result=guard_response(raw,'text/event-stream',[])
|
||||||
|
assert b'unsupported preface' not in result and b'search_knowledge' in result
|
||||||
|
|
||||||
|
def test_gateway_applies_extractive_gate_to_stream_before_forwarding():
|
||||||
|
import asyncio,httpx
|
||||||
|
from services.local_s2s.components import ComponentServer
|
||||||
|
async def scenario():
|
||||||
|
class Writer:
|
||||||
|
def __init__(self):self.data=bytearray()
|
||||||
|
def write(self,data):self.data.extend(data)
|
||||||
|
async def drain(self):pass
|
||||||
|
event={'id':'fixture','choices':[{'index':0,'delta':{'content':'وقت ملاقات هماهنگ میکنم.'}}]}
|
||||||
|
raw=('data: '+json.dumps(event)+'\n\ndata: [DONE]\n\n').encode()
|
||||||
|
server=ComponentServer('fixture',port=0,provider='gapgpt',strict_grounding=True)
|
||||||
|
server.loop=asyncio.get_running_loop();responses=[];writer=Writer()
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(transport=httpx.MockTransport(lambda r:httpx.Response(200,headers={'content-type':'text/event-stream'},content=raw))) as client:
|
||||||
|
await server._forward(client,writer,'/v1/chat/completions',{'content-type':'application/json'},json.dumps({'model':'gpt-4.1-mini','messages':grounded_messages()}).encode(),responses)
|
||||||
|
assert 'وقت ملاقات'.encode() not in writer.data
|
||||||
|
assert 'شماره مرکز شرکت 031 - 3125 است.'.encode() in writer.data
|
||||||
|
finally:
|
||||||
|
for response in responses:await response.aclose()
|
||||||
|
server.server_close()
|
||||||
|
asyncio.run(scenario())
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import pytest
|
||||||
|
import httpx
|
||||||
|
from services.local_s2s.components import ComponentServer
|
||||||
|
from services.local_s2s.extension import active_components
|
||||||
|
from tests.unit.test_local_s2s_phase2 import local_config
|
||||||
|
from tests.unit.test_local_s2s_engine import handlers
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('status', [200, 401, 429])
|
||||||
|
def test_elevenlabs_route_key_isolation_pcm_and_no_fallback(status):
|
||||||
|
async def scenario():
|
||||||
|
observed = []
|
||||||
|
pcm = bytes(100)
|
||||||
|
def upstream(request):
|
||||||
|
observed.append(request)
|
||||||
|
return httpx.Response(status, headers={'content-type': 'audio/pcm'}, content=pcm)
|
||||||
|
class Writer:
|
||||||
|
def __init__(self): self.data = bytearray()
|
||||||
|
def write(self, data): self.data.extend(data)
|
||||||
|
async def drain(self): pass
|
||||||
|
server = ComponentServer('gap-fixture-secret', port=0, provider='gapgpt',
|
||||||
|
tts_provider='elevenlabs', tts_key='eleven-fixture-secret')
|
||||||
|
server.loop = asyncio.get_running_loop()
|
||||||
|
writer, responses = Writer(), []
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(transport=httpx.MockTransport(upstream)) as client:
|
||||||
|
await server._forward(client, writer, '/v1/audio/speech', {'content-type': 'application/json'},
|
||||||
|
json.dumps(dict(model='eleven_v3', voice='fixtureVoice', input='fixture',
|
||||||
|
response_format='pcm', speed=1.2)).encode(), responses)
|
||||||
|
assert len(observed) == 1
|
||||||
|
request = observed[0]
|
||||||
|
assert str(request.url) == 'https://api.elevenlabs.io/v1/text-to-speech/fixtureVoice?output_format=pcm_24000'
|
||||||
|
assert request.headers['xi-api-key'] == 'eleven-fixture-secret'
|
||||||
|
assert 'authorization' not in request.headers
|
||||||
|
assert json.loads(request.content) == dict(model_id='eleven_v3', text='fixture',
|
||||||
|
language_code='fa', voice_settings=dict(speed=1.2))
|
||||||
|
assert (b'HTTP/1.1 200' if status == 200 else b'HTTP/1.1 502') in writer.data
|
||||||
|
if status == 200: assert b'Content-Type: audio/pcm' in writer.data and pcm in writer.data
|
||||||
|
else: assert pcm not in writer.data
|
||||||
|
finally:
|
||||||
|
for response in responses: await response.aclose()
|
||||||
|
server.server_close()
|
||||||
|
asyncio.run(scenario())
|
||||||
|
|
||||||
|
|
||||||
|
def test_elevenlabs_tts_identity_pinned_and_attested(monkeypatch):
|
||||||
|
config = local_config(local_s2s_tts_provider='elevenlabs', local_s2s_tts_speed=1.2,
|
||||||
|
local_s2s_tts_model='eleven_v3', local_s2s_tts_voice='fixtureVoice')
|
||||||
|
assert config.profile() != config.model_copy(update={'local_s2s_tts_provider': 'upstream'}).profile()
|
||||||
|
monkeypatch.setenv('LOCAL_S2S_TTS_PROVIDER', 'elevenlabs')
|
||||||
|
unit = handlers(config)
|
||||||
|
unit.handlers[-1].speed = config.local_s2s_tts_speed
|
||||||
|
assert active_components(unit, config.components()) == config.components()
|
||||||
|
monkeypatch.setenv('LOCAL_S2S_TTS_PROVIDER', 'upstream')
|
||||||
|
with pytest.raises(ValueError): active_components(unit, config.components())
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('speed', [0.6, 1.6])
|
||||||
|
def test_elevenlabs_invalid_speed_rejected(speed):
|
||||||
|
with pytest.raises(ValueError): local_config(local_s2s_tts_provider='elevenlabs', local_s2s_tts_speed=speed)
|
||||||
|
|
||||||
|
|
||||||
|
def test_elevenlabs_missing_credential_fails_before_socket_binding():
|
||||||
|
with pytest.raises(ValueError, match='LOCAL_ELEVENLABS_CREDENTIAL_REQUIRED'):
|
||||||
|
ComponentServer('gap-key', port=0, provider='gapgpt', tts_provider='elevenlabs')
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('status', [200, 401, 429])
|
||||||
|
def test_elevenlabs_stt_maps_multipart_without_other_credentials(status):
|
||||||
|
from email.parser import BytesParser
|
||||||
|
from email.policy import default
|
||||||
|
async def scenario():
|
||||||
|
observed = []
|
||||||
|
def upstream(request):
|
||||||
|
observed.append(request)
|
||||||
|
return httpx.Response(status, json={'text': 'fixture', 'language_code': 'fas'})
|
||||||
|
class Writer:
|
||||||
|
def __init__(self): self.data = bytearray()
|
||||||
|
def write(self, data): self.data.extend(data)
|
||||||
|
async def drain(self): pass
|
||||||
|
original = httpx.Request('POST', 'http://fixture/v1/audio/transcriptions',
|
||||||
|
data={'model': 'scribe_v2', 'language': 'fa', 'response_format': 'json', 'prompt': 'PRIVATE_PROMPT'},
|
||||||
|
files={'file': ('audio.wav', b'fixture-wave-bytes', 'audio/wav')})
|
||||||
|
original.read()
|
||||||
|
server = ComponentServer('gap-fixture-secret', port=0, provider='gapgpt',
|
||||||
|
stt_provider='elevenlabs', stt_key='eleven-fixture-secret', responsive=True)
|
||||||
|
server.loop = asyncio.get_running_loop()
|
||||||
|
writer, responses = Writer(), []
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(transport=httpx.MockTransport(upstream)) as client:
|
||||||
|
await server._forward(client, writer, '/v1/audio/transcriptions',
|
||||||
|
{'content-type': original.headers['content-type']}, original.content, responses)
|
||||||
|
assert len(observed) == 1
|
||||||
|
request = observed[0]
|
||||||
|
assert str(request.url) == 'https://api.elevenlabs.io/v1/speech-to-text'
|
||||||
|
assert request.headers['xi-api-key'] == 'eleven-fixture-secret'
|
||||||
|
assert 'authorization' not in request.headers
|
||||||
|
message = BytesParser(policy=default).parsebytes(
|
||||||
|
('Content-Type: ' + request.headers['content-type'] + '\r\n\r\n').encode() + request.content)
|
||||||
|
fields = {p.get_param('name', header='content-disposition'): p.get_payload(decode=True)
|
||||||
|
for p in message.iter_parts()}
|
||||||
|
assert fields == {'model_id': b'scribe_v2', 'language_code': b'fa', 'tag_audio_events': b'false',
|
||||||
|
'diarize': b'false', 'timestamps_granularity': b'none', 'file': b'fixture-wave-bytes'}
|
||||||
|
assert (b'HTTP/1.1 200' if status == 200 else b'HTTP/1.1 502') in writer.data
|
||||||
|
finally:
|
||||||
|
for response in responses: await response.aclose()
|
||||||
|
server.server_close()
|
||||||
|
asyncio.run(scenario())
|
||||||
|
|
||||||
|
|
||||||
|
def test_elevenlabs_stt_profile_omits_whisper_policy_and_checks_actual_provider(monkeypatch):
|
||||||
|
config = local_config(local_s2s_stt_provider='elevenlabs', local_s2s_stt_model='scribe_v2', local_s2s_responsive=True)
|
||||||
|
expected = config.components()
|
||||||
|
assert expected['stt']['provider'] == 'elevenlabs'
|
||||||
|
assert 'prompt' not in expected['stt'] and 'temperature' not in expected['stt']
|
||||||
|
assert expected['llm']['stream_batch_sentences'] == 1
|
||||||
|
unit = handlers(config)
|
||||||
|
unit.handlers[2].stream_batch_sentences = 1
|
||||||
|
monkeypatch.setenv('LOCAL_S2S_STT_PROVIDER', 'elevenlabs')
|
||||||
|
assert active_components(unit, expected) == expected
|
||||||
|
monkeypatch.setenv('LOCAL_S2S_STT_PROVIDER', 'upstream')
|
||||||
|
with pytest.raises(ValueError): active_components(unit, expected)
|
||||||
|
assert config.profile() != config.model_copy(update={'local_s2s_stt_provider': 'upstream'}).profile()
|
||||||
|
|
||||||
|
|
||||||
|
def test_elevenlabs_stt_rejects_repeated_fields_and_missing_key():
|
||||||
|
from services.local_s2s.elevenlabs import transcription_request
|
||||||
|
request = httpx.Request('POST', 'http://fixture', data={'model': 'scribe_v2'},
|
||||||
|
files=[('file', ('audio.wav', b'one', 'audio/wav')), ('file', ('audio.wav', b'two', 'audio/wav'))])
|
||||||
|
request.read()
|
||||||
|
with pytest.raises(ValueError): transcription_request(request, 'fixture-key')
|
||||||
|
with pytest.raises(ValueError, match='LOCAL_ELEVENLABS_CREDENTIAL_REQUIRED'):
|
||||||
|
ComponentServer('gap-key', port=0, provider='gapgpt', stt_provider='elevenlabs')
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
import json
|
||||||
|
from threading import Thread
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
from services.local_s2s.components import ComponentServer
|
||||||
|
from app.modules.voice.configuration import VoiceSettings
|
||||||
|
from services.local_s2s.extension import active_components
|
||||||
|
from tests.unit.test_local_s2s_engine import handlers
|
||||||
|
from tests.unit.test_local_s2s_phase2 import local_config
|
||||||
|
from tests.unit.test_local_s2s_responsiveness import request
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('status', [200, 429])
|
||||||
|
@pytest.mark.parametrize('path', ['/v1/audio/transcriptions', '/v1/chat/completions', '/v1/audio/speech'])
|
||||||
|
def test_gapgpt_routes_every_component_without_other_provider_keys(monkeypatch, path, capsys, status):
|
||||||
|
monkeypatch.delenv('OPENAI_API_KEY', raising=False)
|
||||||
|
monkeypatch.delenv('OPENROUTER_API_KEY', raising=False)
|
||||||
|
observed = []
|
||||||
|
content = b'{"text":"fixture"}' if path.endswith('transcriptions') else b'data: [DONE]\n\n'
|
||||||
|
media = 'application/json' if path.endswith('transcriptions') else 'text/event-stream'
|
||||||
|
if path.endswith('speech'):
|
||||||
|
content, media = bytes(100), 'audio/pcm'
|
||||||
|
def upstream(r):
|
||||||
|
observed.append(r)
|
||||||
|
return httpx.Response(status, headers={'content-type': media}, content=content)
|
||||||
|
server = ComponentServer('gap-fixture-secret', port=0, provider='gapgpt', responsive=True,
|
||||||
|
transport=httpx.MockTransport(upstream))
|
||||||
|
thread = Thread(target=server.serve_forever, daemon=True)
|
||||||
|
thread.start(); assert server.ready.wait(3)
|
||||||
|
try:
|
||||||
|
with httpx.Client(trust_env=False, timeout=5) as client:
|
||||||
|
headers = {'authorization': 'Bearer local-components'}
|
||||||
|
if path.endswith('transcriptions'):
|
||||||
|
r = request()
|
||||||
|
headers['content-type'] = r.headers['content-type']
|
||||||
|
result = client.post(f'http://127.0.0.1:{server.server_port}' + path, content=r.content, headers=headers)
|
||||||
|
assert observed[0].content == r.content
|
||||||
|
else:
|
||||||
|
payload = {'model': 'gpt-4.1-mini', 'messages': [], 'stream': True}
|
||||||
|
if path.endswith('speech'):
|
||||||
|
payload = {'model': 'openai/gpt-4o-mini-tts', 'input': 'fixture', 'voice': 'alloy', 'response_format': 'pcm'}
|
||||||
|
result = client.post(f'http://127.0.0.1:{server.server_port}' + path, json=payload, headers=headers)
|
||||||
|
assert result.status_code == (200 if status == 200 else 502)
|
||||||
|
assert result.content == (content if status == 200 else b'')
|
||||||
|
assert len(observed) == 1
|
||||||
|
assert str(observed[0].url) == 'https://api.gapgpt.app' + path
|
||||||
|
assert observed[0].headers['authorization'] == 'Bearer gap-fixture-secret'
|
||||||
|
if path.endswith('speech'):
|
||||||
|
assert json.loads(observed[0].content)['model'] == 'gpt-4o-mini-tts'
|
||||||
|
finally:
|
||||||
|
server.shutdown(); server.server_close(); thread.join(3)
|
||||||
|
output = capsys.readouterr().out
|
||||||
|
assert 'gapgpt' in output and 'gap-fixture-secret' not in output
|
||||||
|
|
||||||
|
|
||||||
|
def test_upstream_provider_is_pinned_and_actual_engine_mismatch_is_rejected(monkeypatch):
|
||||||
|
config = local_config(local_s2s_component_provider='gapgpt')
|
||||||
|
assert config.profile() != local_config().profile()
|
||||||
|
assert config.components()['upstream_provider'] == 'gapgpt'
|
||||||
|
monkeypatch.setenv('LOCAL_S2S_COMPONENT_PROVIDER', 'gapgpt')
|
||||||
|
assert active_components(handlers(config), config.components()) == config.components()
|
||||||
|
monkeypatch.setenv('LOCAL_S2S_COMPONENT_PROVIDER', 'split')
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
active_components(handlers(config), config.components())
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_upstream_provider_fails_before_binding():
|
||||||
|
with pytest.raises(ValueError, match='LOCAL_COMPONENT_PROVIDER_UNSUPPORTED'):
|
||||||
|
ComponentServer('fixture-key', port=0, provider='unknown')
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
VoiceSettings(_env_file=None, local_s2s_component_provider='unknown')
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('provider,expected', [('split', 5), ('gapgpt', 60)])
|
||||||
|
def test_provider_header_wait_respects_total_bound(provider, expected):
|
||||||
|
server = ComponentServer('fixture-key', port=0, provider=provider, timeout=60)
|
||||||
|
try:
|
||||||
|
assert server.inactivity == expected
|
||||||
|
finally:
|
||||||
|
server.server_close()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('payload', [
|
||||||
|
{}, {'choices': []},
|
||||||
|
{'choices': [{'finish_reason': 'length', 'message': {'audio': {'data': 'AAAA'}}}]},
|
||||||
|
{'choices': [{'finish_reason': 'stop', 'message': {'audio': {'data': 'not base64!'}}}]},
|
||||||
|
])
|
||||||
|
def test_gemini_audio_rejects_missing_partial_or_malformed_audio(payload):
|
||||||
|
from services.local_s2s.gapgpt_audio import decode_pcm
|
||||||
|
with pytest.raises(ValueError): decode_pcm(payload, 100)
|
||||||
|
|
||||||
|
|
||||||
|
def test_gemini_audio_payload_and_pcm_bounds():
|
||||||
|
import base64
|
||||||
|
from services.local_s2s.gapgpt_audio import speech_payload, decode_pcm
|
||||||
|
request = speech_payload(dict(model='gemini-2.5-flash-preview-tts', input='fixture', voice='Kore', speed=1.6))
|
||||||
|
assert request['modalities'] == ['audio'] and request['audio'] == {'voice': 'Kore', 'format': 'pcm16'}
|
||||||
|
response = {'choices': [{'finish_reason': 'stop', 'message': {'audio': {'data': base64.b64encode(bytes(100)).decode()}}}]}
|
||||||
|
assert decode_pcm(response, 100) == bytes(100)
|
||||||
|
with pytest.raises(ValueError): decode_pcm(response, 98)
|
||||||
|
|
||||||
|
|
||||||
|
def test_gapgpt_gemini_speech_gateway_uses_audio_chat_and_returns_pcm():
|
||||||
|
import asyncio
|
||||||
|
import base64
|
||||||
|
async def scenario():
|
||||||
|
observed = []
|
||||||
|
pcm = bytes(100)
|
||||||
|
def upstream(request):
|
||||||
|
observed.append(request)
|
||||||
|
return httpx.Response(200, json={'choices': [{'finish_reason': 'stop', 'message': {
|
||||||
|
'audio': {'data': base64.b64encode(pcm).decode()}}}]})
|
||||||
|
class Writer:
|
||||||
|
data = bytearray()
|
||||||
|
def write(self, data): self.data.extend(data)
|
||||||
|
async def drain(self): pass
|
||||||
|
server = ComponentServer('fixture-key', port=0, provider='gapgpt')
|
||||||
|
server.loop = asyncio.get_running_loop()
|
||||||
|
responses = []
|
||||||
|
writer = Writer()
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient(transport=httpx.MockTransport(upstream)) as client:
|
||||||
|
await server._forward(client, writer, '/v1/audio/speech', {'content-type': 'application/json'},
|
||||||
|
json.dumps(dict(model='gemini-2.5-flash-preview-tts', input='fixture', voice='Kore')).encode(), responses)
|
||||||
|
assert len(observed) == 1
|
||||||
|
assert str(observed[0].url) == 'https://api.gapgpt.app/v1/chat/completions'
|
||||||
|
assert json.loads(observed[0].content)['audio']['format'] == 'pcm16'
|
||||||
|
assert b'Content-Type: audio/pcm' in writer.data and pcm in writer.data
|
||||||
|
finally:
|
||||||
|
for response in responses: await response.aclose()
|
||||||
|
server.server_close()
|
||||||
|
asyncio.run(scenario())
|
||||||
@@ -86,6 +86,13 @@ def test_actual_gateway_transforms_request_without_rewriting_transcript(capsys):
|
|||||||
server.shutdown();server.server_close();thread.join(3)
|
server.shutdown();server.server_close();thread.join(3)
|
||||||
output=capsys.readouterr().out
|
output=capsys.readouterr().out
|
||||||
assert 'component_first_byte' in output
|
assert 'component_first_byte' in output
|
||||||
|
traces = [json.loads(line) for line in output.splitlines() if line.startswith('{')]
|
||||||
|
terminal = [row for row in traces if row.get('stage') == 'component_request']
|
||||||
|
assert len(terminal) == 1
|
||||||
|
assert terminal[0]['outcome'] == 'completed' and terminal[0]['phase'] == 'completed'
|
||||||
|
assert terminal[0]['response_bytes'] > 0 and terminal[0]['elapsed_ms'] >= 0
|
||||||
|
assert terminal[0]['upstream_status'] == 200 and terminal[0]['component_request_id']
|
||||||
|
assert 'fixture-key' not in output
|
||||||
assert RESPONSIVE_ASR_PROMPT not in output and 'unchanged transcript' not in output
|
assert RESPONSIVE_ASR_PROMPT not in output and 'unchanged transcript' not in output
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ def test_exact_match_cannot_bypass_admission_or_whole_chunk_budget():
|
|||||||
accepted = admit_candidates(rows, .2)
|
accepted = admit_candidates(rows, .2)
|
||||||
assert [r["chunk_id"].int for r in accepted] == [3, 4, 5]
|
assert [r["chunk_id"].int for r in accepted] == [3, 4, 5]
|
||||||
assert sum(len(r["text"]) for r in accepted) == 12000
|
assert sum(len(r["text"]) for r in accepted) == 12000
|
||||||
assert len(admit_candidates([row(i) for i in range(1, 10)])) == 5
|
assert len(admit_candidates([row(i) for i in range(1, 14)])) == 10
|
||||||
|
|
||||||
|
|
||||||
def test_execution_reuses_refs_and_never_rebinds_across_searches():
|
def test_execution_reuses_refs_and_never_rebinds_across_searches():
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import json
|
||||||
|
from types import SimpleNamespace
|
||||||
|
import pytest
|
||||||
|
from app.modules.voice.diagnostics import provider_error_summary
|
||||||
|
from app.modules.voice.model_catalog import model_catalog
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('enabled,selectable,expected', [
|
||||||
|
(True, ('local_s2s', 'gemini'), {'embedding', 'ocr', 'openai', 'gemini', 'dialogue', 'stt', 'tts'}),
|
||||||
|
(False, ('local_s2s',), {'embedding', 'ocr', 'openai'}),
|
||||||
|
(True, (), {'embedding', 'ocr', 'openai'}),
|
||||||
|
])
|
||||||
|
def test_catalog_only_exposes_deployed_models(enabled, selectable, expected):
|
||||||
|
ingest = SimpleNamespace(embedding_model='fixture-embedding', vision_model='fixture-vision', api_key='PRIVATE')
|
||||||
|
voice = SimpleNamespace(provider='openai', voice_selectable_providers=selectable,
|
||||||
|
local_s2s_enabled=enabled, local_s2s_llm_model='fixture-llm', local_s2s_stt_model='fixture-stt',
|
||||||
|
local_s2s_tts_model='fixture-tts', openai_realtime_model='fixture-realtime', gemini_model='fixture-gemini',
|
||||||
|
openai_api_key='PRIVATE', local_s2s_token='PRIVATE')
|
||||||
|
rows = model_catalog(ingest, voice)
|
||||||
|
assert {row['id'] for row in rows} == expected
|
||||||
|
assert all(set(row) == {'id', 'label', 'model'} for row in rows)
|
||||||
|
assert 'PRIVATE' not in json.dumps(rows)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('error,signature', [
|
||||||
|
({'type': 'invalid_request_error', 'code': 'response_cancel_not_active'}, 'code=response_cancel_not_active'),
|
||||||
|
({'type': 'PRIVATE', 'code': 'PRIVATE'}, 'type=other code=other'),
|
||||||
|
({'type': ['PRIVATE'], 'code': {'message': 'PRIVATE'}}, 'type=other code=other'),
|
||||||
|
({}, 'type=other code=other'),
|
||||||
|
])
|
||||||
|
def test_provider_error_summary_never_logs_payload(caplog, error, signature):
|
||||||
|
provider_error_summary('fixture-session', dict(error, message='PRIVATE', param='PRIVATE'))
|
||||||
|
assert 'session=fixture-session' in caplog.text and signature in caplog.text
|
||||||
|
assert 'PRIVATE' not in caplog.text
|
||||||
Reference in New Issue
Block a user