Author SHA1 Message Date
amirhosein mazaheri 9b5be918d4 docs: reconcile project status and local stack operations
Refresh entry points and progress checkpoints, document schema revision 0006, and consolidate the final ElevenLabs/GapGPT profile and host prerequisites.

Preserve dated activation evidence and distinguish implementation, targeted validation, incomplete full-suite checks and remaining human acceptance gates.

Validation: 409 local Markdown link targets resolved and staged whitespace checks passed.
2026-10-20 09:00:55 +03:30
amirhosein mazaheri 42400495af 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.
2026-10-20 09:00:37 +03:30
amirhosein mazaheri 2bffb9476a fix(voice): handle response.cancel no-active race on local S2S provider
- implement LocalS2SAdapter.is_no_active to recognize cancellation of completed or inactive responses
- normalize local S2S history handler cancellation error to standard response_cancel_not_active contract
- align calibration distance for measured BGE-M3 search threshold
2026-10-17 17:01:28 +03:30
amirhosein mazaheri 5bb6945377 feat(spaces): add whisper persian v4 speech recognition demo space 2026-10-17 13:03:15 +03:30
amirhosein mazaheri 628aec8def feat(voice): implement local S2S responsiveness candidate and direct TTS routing
Add local S2S responsiveness candidate pinning ASR options and sentence-at-a-time generation. Route speech synthesis directly to OpenAI API for fluent Persian phonetics with gpt-4o-mini-tts-2025-12-15. Add responsiveness, budget carry, and browser watch unit tests along with acceptance benchmarks and evaluation evidence.
2026-10-17 13:02:41 +03:30
79 changed files with 3739 additions and 471 deletions
+24 -2
View File
@@ -153,13 +153,17 @@ OPENAI_REALTIME_SPEED=1.30
LOCAL_S2S_ENABLED=false LOCAL_S2S_ENABLED=false
# Phase 3 development opt-in; saved interrupted text is not treated as heard. # Phase 3 development opt-in; saved interrupted text is not treated as heard.
LOCAL_S2S_RETAIN_INTERRUPTED_ANSWERS=false LOCAL_S2S_RETAIN_INTERRUPTED_ANSWERS=false
# Isolated responsiveness candidate; pins ASR options and sentence-at-a-time generation.
LOCAL_S2S_RESPONSIVE=false
# Provider synthesis speed; 1.0 preserves normal local speech.
LOCAL_S2S_TTS_SPEED=1.0
LOCAL_S2S_ENDPOINT=ws://local-s2s-engine:8765/v1/realtime LOCAL_S2S_ENDPOINT=ws://local-s2s-engine:8765/v1/realtime
LOCAL_S2S_ENGINE_REVISION=619e3fe4f71d1c6f35c15870d588a3638de34722 LOCAL_S2S_ENGINE_REVISION=619e3fe4f71d1c6f35c15870d588a3638de34722
LOCAL_S2S_STT_MODEL=openai/whisper-large-v3 LOCAL_S2S_STT_MODEL=openai/whisper-large-v3
LOCAL_S2S_LLM_MODEL=openai/gpt-4.1-mini LOCAL_S2S_LLM_MODEL=openai/gpt-4.1-mini
# Candidate only: actual voice/rate/Persian compatibility is not accepted yet. # Candidate only: actual voice/rate/Persian compatibility is not accepted yet.
LOCAL_S2S_TTS_MODEL=google/gemini-3.8-flash-lite-tts LOCAL_S2S_TTS_MODEL=gpt-4o-mini-tts-2025-12-15
LOCAL_S2S_TTS_VOICE=Kore LOCAL_S2S_TTS_VOICE=alloy
LOCAL_S2S_MAX_OUTPUT_TOKENS=256 LOCAL_S2S_MAX_OUTPUT_TOKENS=256
LOCAL_S2S_REQUEST_TIMEOUT_SECONDS=30 LOCAL_S2S_REQUEST_TIMEOUT_SECONDS=30
LOCAL_S2S_TOKEN= LOCAL_S2S_TOKEN=
@@ -172,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
+1
View File
@@ -86,6 +86,7 @@ temp/
# Immutable ingestion originals (may contain private uploaded content) # Immutable ingestion originals (may contain private uploaded content)
data/originals/ data/originals/
data/extractions/
# Isolated local S2S generated source and dependency inputs # Isolated local S2S generated source and dependency inputs
.local-s2s-build/ .local-s2s-build/
+72 -333
View File
@@ -1,333 +1,72 @@
For the current modular document/voice backend, use the [Phase 4 startup and recovery guide](docs/guides/phase4-backend-operations.md) and [acceptance evidence](docs/guides/realtime-agent-phase4-acceptance.md). Install `.[api,voice,embedding]`, apply online migrations, and run one `python -m app.server` process with a separate `python -m app.worker`. Service readiness does not certify calibrated retrieval or usable grounded voice. The paragraphs and prototype walkthrough below preserve older checkpoints. # Technical Documentation Assistant
Phase 6 adds [integration validation and operator handoff](docs/guides/ingestion-operator-handoff.md), redacted worker heartbeat/stage diagnostics and an opt-in real-provider smoke command. The existing chat retriever still uses Chroma/FastEmbed and does not search uploaded PostgreSQL chunks. Scoped pgvector search and authorized knowledge selection are the next milestone; published documents remain inactive. Phase 1 backend for independently uploaded documents and grounded Persian voice.
The application uses a modular FastAPI API, a separate ingestion worker,
Current target: the English [LangChain Live document MVP](docs/specifications/RAG-AI-Phase1-Delivery-Plan.md), with new browser uploads and direct Persian speech-to-speech. Ingestion Phases 1-4 plus the [Phase 5 worker, publication and retry](docs/guides/worker-orchestration.md) are implemented. Durable review decisions/resume and factual FAQ inclusion are implemented behind trusted backend services. Scoped uploaded-document retrieval, HTTP identity/upload/review transport, Live and UI remain planned. See [documentation and implementation order](docs/README.md) and [recorded setup/validation](docs/guides/ingestion-foundation-setup.md). The four sample files are acceptance examples, not the accepted corpus. The startup/API details below describe the legacy prototype. PostgreSQL/pgvector, durable original/extraction storage, and backend-owned search.
The Angular frontend is maintained in the sibling faq_chatbot_frontend repository.
# 🤖 Technical Documentation Assistant (RAG Agent)
Start with [current status](docs/current-status.md), the
[![FastAPI](https://img.shields.io/badge/FastAPI-0.115+-009688.svg?style=flat-square&logo=FastAPI&logoColor=white)](https://fastapi.tiangolo.com) [documentation index](docs/README.md), and the
[![LangGraph](https://img.shields.io/badge/LangGraph-StateGraph-FF4F00.svg?style=flat-square&logo=python&logoColor=white)](https://github.com/langchain-ai/langgraph) [startup and recovery guide](docs/guides/phase4-backend-operations.md).
[![LangChain](https://img.shields.io/badge/LangChain-1.x-1C3C3C.svg?style=flat-square&logo=langchain&logoColor=white)](https://github.com/langchain-ai/langchain) The [local Windows runbook](docs/guides/current-local-stack.md) describes the
[![ChromaDB](https://img.shields.io/badge/VectorDB-ChromaDB-FF6F00.svg?style=flat-square)](https://www.trychroma.com/) last recorded isolated speech stack; it is not a production deployment recipe.
[![FastEmbed](https://img.shields.io/badge/Embeddings-FastEmbed%20(BGE--Small)-blue.svg?style=flat-square)](https://github.com/qdrant/fastembed)
[![Python](https://img.shields.io/badge/Python-3.11%2B-3776AB.svg?style=flat-square&logo=python&logoColor=white)](https://www.python.org/) ## Current capabilities
[![License](https://img.shields.io/badge/License-MIT-green.svg?style=flat-square)](LICENSE)
- Authenticated upload, processing status, retained extraction review, retry,
A **Retrieval-Augmented Generation (RAG)** prototype built with **FastAPI**, **LangGraph**, **LangChain**, and **ChromaDB**. The sections below document that existing Markdown/text prototype. The target Live MVP will connect the separate PostgreSQL/pgvector ingestion pipeline through shared LangChain retrieval; production readiness and zero-hallucination behavior are not established. active knowledge selection and soft deletion with request replay protection.
- Immutable independent document IDs, fenced worker publication and
--- organization-scoped retrieval over eligible uploaded PostgreSQL chunks.
- Shared backend search and private voice adapters for OpenAI, Gemini and the
## 📑 Table of Contents development-only Local S2S engine, with pinned session profiles.
- Local strict extractive grounding before TTS and up to ten whole source chunks
- [Key Features](#-key-features) within 12,000 characters. This is not a guarantee that uploaded facts are true.
- [Architecture & Workflow](#-architecture--workflow) - Public model identifiers and allowed voice-provider selection; arbitrary model,
- [Project Structure](#-project-structure) credential and general settings editing remain deferred.
- [Tech Stack](#-tech-stack)
- [Getting Started](#-getting-started) Implementation, fixture tests, real-provider checks and human acceptance are
- [Prerequisites](#prerequisites) separate claims. See [current status and remaining gates](docs/current-status.md).
- [Installation](#installation)
- [Environment Configuration](#environment-configuration) ## Setup
- [Running the Application](#-running-the-application)
- [Starting the FastAPI Server](#starting-the-fastapi-server) Python 3.11+, PostgreSQL with pgvector and configured provider access are required.
- [Running the CLI Test Harness](#running-the-cli-test-harness) Use the frozen embedding profile and durable directories for the target database.
- [API Reference](#-api-reference) Never change an existing embedding identity merely to make startup succeed.
- [Health Check](#1-health-check)
- [Chat with Assistant](#2-chat-with-assistant) ~~~powershell
- [Adding Custom Documentation](#-adding-custom-documentation) .venv/Scripts/python -m pip install -e ".[api,voice,embedding,test]"
- [Contributing](#-contributing) .venv/Scripts/alembic upgrade head
- [License](#-license) .venv/Scripts/python -m app.server --host 127.0.0.1 --port 8080
# Separate process, with an authorized ingestion queue:
--- .venv/Scripts/python -m app.worker
~~~
## ✨ Key Features
Configure from [.env.example](.env.example). Provision a new installation with
- **Autonomous Agentic RAG (LangGraph)**: Uses a compiled `StateGraph` with conditional tool routing (`tools_condition`), cyclical reasoning loops, and multi-turn conversational memory (`MemorySaver`). app.bootstrap/app.provision as described in the operations guide. Persistent
- **Intent Distillation & Query Reformulation**: Analyzes incoming natural language queries and distills them into high-precision technical search terms before invoking vector retrieval. provider keys stay server-side. The supported voice API entry point is app.server.
- **Strict Grounded Reasoning & Anti-Hallucination**: System prompts mandate that answers are strictly based on retrieved documentation chunks. If context is missing, the agent explicitly clarifies or states its limitations.
- **Document Source Citations**: Automatically tracks and references origin files (e.g., `fastapi_handling_errors.md`) in responses. The current Live schema requirement is 0006_voice_model_settings. Apply forward
- **Fast Local Embeddings**: Utilizes `FastEmbed` (`BAAI/bge-small-en-v1.5`) for lightweight, high-performance CPU/GPU vector embeddings without incurring third-party embedding API costs. migrations before starting the API; do not edit applied revisions.
- **Persistent ChromaDB Store**: Automated document ingestion, chunking via `RecursiveCharacterTextSplitter`, and persistent vector indexing.
- **Asynchronous REST API**: Powered by FastAPI with Pydantic validation, CORS middleware, and automatic Swagger/ReDoc OpenAPI documentation. ## Validation
--- ~~~powershell
.venv/Scripts/python -m pytest -m "not postgres"
## 🏛️ Architecture & Workflow .venv/Scripts/python -m pytest -m postgres --require-postgres
git diff --check
```mermaid ~~~
flowchart TD
User([User / Client]) -->|POST /api/v1/chat| API[FastAPI Router] PostgreSQL acceptance requires an isolated TEST_DATABASE_URL and pgvector;
API --> AgentExec[LangGraph Agent Engine] missing configuration must fail acceptance. Ordinary skips are not database proof.
See [test guidance](tests/README.md). No build/lint pipeline is defined here.
subgraph LangGraph ["LangGraph Agent Loop"]
AgentExec --> AgentNode[Agent Node: LLM Reasoning] ## Scope and legacy prototype
AgentNode -->|Inspect Query| IntentCheck{Needs Retrieval?}
IntentCheck -->|Ambiguous| Clarify[Ask Clarifying Questions] The [Phase 1 delivery plan](docs/specifications/RAG-AI-Phase1-Delivery-Plan.md)
IntentCheck -->|Clear Technical Query| ToolCall[Reformulate Query & Call Tool] governs scope, with dated authorized amendments indexed in the reference map.
ToolCall --> RetrieverTool[retriever_tool] Full text history and general settings editing remain deferred.
RetrieverTool --> ToolNode[Tool Execution Node]
ToolNode --> ContextRetriever[Context Retriever] The older app.main / app.services agent uses Chroma/FastEmbed and the optional
ContextRetriever --> ChromaDB[(Chroma Vector Store)] prototype dependencies. That path does not represent uploaded-document search
ChromaDB -->|Top-K Chunks| RetrieverTool or the supported modular voice startup. Project specifications under docs are
ToolNode -->|Document Context| AgentNode not organization knowledge and must not be ingested as the user corpus.
AgentNode -->|Final Answer + Citations| Checkpoint[MemorySaver State Checkpointer]
end
Checkpoint --> Response[Format ChatResponse]
Response --> User
```
---
## 📁 Project Structure
```text
rag-technical-docs-assistant/
├── app/
│ ├── __init__.py # Application package init
│ ├── main.py # FastAPI entrypoint, middleware & routers
│ ├── api/
│ │ ├── __init__.py # API routers package
│ │ └── v1/
│ │ ├── __init__.py # API v1 package
│ │ └── chat.py # Chat endpoint handler (POST /api/v1/chat)
│ ├── core/
│ │ ├── __init__.py # Core package
│ │ └── config.py # Pydantic Settings and environment config
│ ├── schemas/
│ │ ├── __init__.py # Schemas package
│ │ └── chat.py # ChatRequest and ChatResponse models
│ └── services/
│ ├── __init__.py # Services package
│ ├── doc_processor.py # Markdown document loader and text chunker
│ ├── retriever.py # ContextRetriever with FastEmbed & ChromaDB
│ ├── agent/
│ │ ├── __init__.py # Agent package
│ │ ├── prompt.py # System prompts and prompt templates
│ │ └── exec.py # LangGraph workflow, state graph, and executor
│ └── tools/
│ ├── __init__.py # Tools package
│ └── retriever_tool.py # LangChain @tool for documentation retrieval
├── data/
│ ├── documents/ # Raw markdown technical documentation files
│ │ ├── fastapi_handling_errors.md
│ │ ├── fastapi_settings.md
│ │ └── _style_guide.md
│ └── vector_db/ # Persistent ChromaDB vector database files
├── tests/ # Automated tests directory
├── .env.example # Example environment variables template
├── .gitignore # Git ignore patterns
└── README.md # Project documentation
```
---
## 🛠️ Tech Stack
- **Framework**: [FastAPI](https://fastapi.tiangolo.com/)
- **Agent Workflow**: [LangGraph](https://github.com/langchain-ai/langgraph)
- **LLM Orchestration**: [LangChain](https://github.com/langchain-ai/langchain) & [LangChain-OpenAI](https://github.com/langchain-ai/langchain-openai)
- **Vector Database**: [ChromaDB](https://www.trychroma.com/)
- **Embeddings**: [FastEmbed](https://github.com/qdrant/fastembed) (`BAAI/bge-small-en-v1.5`)
- **Data Validation & Settings**: [Pydantic](https://docs.pydantic.dev/) & [pydantic-settings](https://docs.pydantic.dev/latest/concepts/pydantic_settings/)
- **Server**: [Uvicorn](https://www.uvicorn.org/)
---
## 🚀 Getting Started
### Prerequisites
- **Python 3.11+** installed on your machine.
- An API key for an OpenAI-compatible provider (such as [OpenRouter](https://openrouter.ai/) or [OpenAI](https://platform.openai.com/)).
### Installation
1. **Clone the repository:**
```bash
git clone https://github.com/11linear11/rag-technical-docs-assistant.git
cd rag-technical-docs-assistant
```
2. **Create and activate a virtual environment:**
```bash
# On Linux/macOS
python3 -m venv .venv
source .venv/bin/activate
# On Windows
python -m venv .venv
.venv\Scripts\activate
```
3. **Install dependencies:**
```bash
pip install -e ".[prototype]"
```
*(Or install the core packages: `fastapi uvicorn langgraph langchain langchain-openai langchain-chroma chromadb fastembed pydantic-settings`)*
### Environment Configuration
Copy the sample environment file `.env.example` to `.env`:
```bash
cp .env.example .env
```
Edit `.env` and fill in your settings:
```env
# Application Settings
APP_NAME="Technical Documentation Assistant"
APP_VERSION="1.0.0"
APP_ENVIRONMENT="development"
# LLM Configuration (OpenRouter, OpenAI, or any OpenAI-compatible provider)
API_KEY="your_api_key_here"
LLM_BASE_URL="https://openrouter.ai/api/v1"
LLM_MODEL="gpt-4o-mini"
LLM_TEMPERATURE=0.0
LLM_MAX_TOKENS=2048
LLM_MAX_ITERATIONS=3
# RAG & Storage Configuration
CHUNK_SIZE=1000
CHUNK_OVERLAP=200
DOCS_DIR="./data/documents"
CHROMA_PERSIST_DIR="./data/vector_db"
```
| Variable | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `APP_NAME` | `str` | `Technical Documentation Assistant` | Name of the application |
| `APP_VERSION` | `str` | `1.0.0` | Application release version |
| `APP_ENVIRONMENT` | `str` | `development` | Deployment environment (`development`, `production`) |
| `API_KEY` | `str` | *(Required)* | API key for LLM provider |
| `LLM_BASE_URL` | `str` | `https://openrouter.ai/api/v1` | Base URL for LLM API |
| `LLM_MODEL` | `str` | `gpt-4o-mini` | LLM model identifier |
| `LLM_TEMPERATURE` | `float` | `0.0` | Sampling temperature for LLM completions |
| `LLM_MAX_TOKENS` | `int` | `2048` | Max tokens generated per completion |
| `LLM_MAX_ITERATIONS` | `int` | `3` | Maximum agent reasoning loop iterations |
| `CHUNK_SIZE` | `int` | `1000` | Character size for document chunking |
| `CHUNK_OVERLAP` | `int` | `200` | Overlap character count between chunks |
| `DOCS_DIR` | `str` | `./data/documents` | Path to directory containing source Markdown docs |
| `CHROMA_PERSIST_DIR` | `str` | `./data/vector_db` | Path where Chroma database is persisted |
---
## 💻 Running the Application
### Starting the FastAPI Server
Start the application with Uvicorn:
```bash
python -m app.server --host 0.0.0.0 --port 8000
```
- **Interactive Swagger Documentation**: [http://localhost:8000/docs](http://localhost:8000/docs)
- **ReDoc Documentation**: [http://localhost:8000/redoc](http://localhost:8000/redoc)
### Running the CLI Test Harness
You can test the agent directly from your terminal:
```bash
python -m app.services.agent.exec
```
---
## 📡 API Reference
### 1. Health Check
Checks if the service is running and ready.
- **URL**: `/api/v1/health`
- **Method**: `GET`
- **Response**: `200 OK`
```json
{
"status": "healthy"
}
```
---
### 2. Chat with Assistant
Sends a query to the agent. Supports stateful conversations using `thread_id`.
- **URL**: `/api/v1/chat`
- **Method**: `POST`
- **Headers**: `Content-Type: application/json`
#### Request Body
```json
{
"query": "How can I implement custom exception handlers in FastAPI?",
"thread_id": "optional-session-uuid-or-id"
}
```
> **Note**: If `thread_id` is omitted, the system generates a new UUID and preserves the conversation context for subsequent requests using that returned `thread_id`.
#### cURL Example
```bash
curl -X POST "http://localhost:8000/api/v1/chat" \
-H "Content-Type: application/json" \
-d '{
"query": "How do I handle custom exceptions in FastAPI?",
"thread_id": "session-123"
}'
```
#### Successful Response (`200 OK`)
```json
{
"response": "To handle custom exceptions in FastAPI, you can define a custom exception class and register an `@app.exception_handler`...\n\n**Source:** `fastapi_handling_errors.md`",
"thread_id": "session-123"
}
```
---
## 📚 Adding Custom Documentation
1. Place any Markdown (`.md`) files into the `data/documents/` directory.
2. If the vector database (`data/vector_db/`) already exists and you want to trigger a complete re-index, simply remove the existing database folder:
```bash
rm -rf ./data/vector_db
```
3. Restart the service or run the agent. The `ContextRetriever` will automatically detect the missing store, load all `.md` files, chunk them, compute embeddings using FastEmbed, and persist the new vector database.
---
## 🤝 Contributing
Contributions are welcome! To contribute:
1. Fork the repository.
2. Create your feature branch (`git checkout -b feature/amazing-feature`).
3. Commit your changes (`git commit -m 'Add amazing feature'`).
4. Push to the branch (`git push origin feature/amazing-feature`).
5. Open a Pull Request.
---
## 📄 License
This project is open-source and licensed under the [MIT License](LICENSE).
Live uses the bounded single-process entrypoint above; run ingestion separately with
`python -m app.worker`. See the [voice integration guide](docs/guides/frontend-voice-integration-example.md)
for backend provider settings, transport limits, recovery and acceptance prerequisites.
Document/knowledge endpoints and backend-only `INGEST_OCR_REVIEW_REQUIRED`
(default true) are documented in the [Phase 3 frontend handoff](docs/guides/realtime-agent-phase3-handoff.md).
API and worker must share immutable original/extraction storage. New job profiles
freeze the OCR gate; existing/legacy jobs and factual review remain unchanged.
+23
View File
@@ -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
+2
View File
@@ -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)),
+1 -1
View File
@@ -60,7 +60,7 @@ def voice_providers(user: Annotated[UserContext, Depends(get_current_user)],
config: Annotated[VoiceSettings, Depends(get_voice_settings)], config: Annotated[VoiceSettings, Depends(get_voice_settings)],
engine: Annotated[object, Depends(get_engine)]): engine: Annotated[object, Depends(get_engine)]):
rows = [] rows = []
for provider, label in (('openai', 'OpenAI'), ('local_s2s', 'سیستم جدید'), ('gemini', 'Gemini')): for provider, label in (('openai', 'OpenAI'), ('local_s2s', 'سرویس لوکال'), ('gemini', 'Gemini')):
reason = None reason = None
if provider not in {config.provider, *config.voice_selectable_providers}: if provider not in {config.provider, *config.voice_selectable_providers}:
reason = 'disabled' reason = 'disabled'
+6 -5
View File
@@ -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\')
+12 -1
View File
@@ -1,4 +1,4 @@
"""Pinned local engine GA transport; no invented native input/history receipts.""" """Pinned local engine GA transport; no invented native input/history receipts."""
from app.infrastructure.realtime import RealtimeAdapter from app.infrastructure.realtime import RealtimeAdapter
from app.modules.voice.provider import ProviderProtocolError from app.modules.voice.provider import ProviderProtocolError
from app.modules.voice.local_s2s import setup_session, effective_identity from app.modules.voice.local_s2s import setup_session, effective_identity
@@ -49,6 +49,17 @@ class LocalS2SAdapter(RealtimeAdapter):
return False return False
def is_no_active(self, error): def is_no_active(self, error):
try:
return (isinstance(error, dict)
and (
(error.get("type") == "invalid_request_error"
and error.get("code") == "response_cancel_not_active"
and error.get("param") is None)
or (error.get("type") == "s2s_history_failed"
and error.get("message") == "Cancellation identity mismatch"
and error.get("param") is None)
))
except Exception:
return False return False
def history_repair_request(self, repair): def history_repair_request(self, repair):
+31 -3
View File
@@ -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.",
+58
View File
@@ -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)
+1 -1
View File
@@ -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}"
+21 -2
View File
@@ -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
+12
View File
@@ -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'])
+32 -4
View File
@@ -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'
@@ -19,8 +19,17 @@ RETENTION_INSTRUCTIONS = (DRAFT_MARKER + ' Interrupted assistant output is a sav
RESPONSIVE_ASR_PROMPT = 'Transcribe conversational Iranian Persian faithfully, including short informal questions. Do not answer, translate, or add missing words.'
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_strict_grounding: 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'
local_s2s_token: SecretStr = SecretStr('') local_s2s_token: SecretStr = SecretStr('')
@@ -53,14 +62,33 @@ 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):
return 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),
llm=dict(backend='chat-completions', model=self.local_s2s_llm_model, llm=dict(backend='chat-completions', model=self.local_s2s_llm_model,
max_output_tokens=self.local_s2s_max_output_tokens), max_output_tokens=self.local_s2s_max_output_tokens),
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:
result['tts']['speed'] = self.local_s2s_tts_speed
if self.local_s2s_responsive:
if self.local_s2s_stt_provider == 'upstream':
result['stt'].update(temperature=0, prompt=RESPONSIVE_ASR_PROMPT)
result['llm']['stream_batch_sentences'] = 1
return result
def setup_session(config): def setup_session(config):
@@ -72,7 +100,7 @@ def setup_session(config):
session['max_output_tokens'] = config.local_s2s_max_output_tokens session['max_output_tokens'] = config.local_s2s_max_output_tokens
session['audio']['input']['transcription'] = dict(model=config.local_s2s_stt_model, language='fa') session['audio']['input']['transcription'] = dict(model=config.local_s2s_stt_model, language='fa')
session['audio']['output']['voice'] = config.local_s2s_tts_voice session['audio']['output']['voice'] = config.local_s2s_tts_voice
session['audio']['output']['speed'] = 1.0 session['audio']['output']['speed'] = config.local_s2s_tts_speed
if config.local_s2s_retain_interrupted_answers: if config.local_s2s_retain_interrupted_answers:
session['instructions'] += '\n' + RETENTION_INSTRUCTIONS session['instructions'] += '\n' + RETENTION_INSTRUCTIONS
return session return session
@@ -80,7 +108,7 @@ def setup_session(config):
def effective_identity(components, session): def effective_identity(components, session):
retention = session.get('instructions', '').endswith(RETENTION_INSTRUCTIONS) retention = session.get('instructions', '').endswith(RETENTION_INSTRUCTIONS)
return dict(engine_revision=UPSTREAM_REVISION, patch_revision='rag-local-s2s-phase3-retain-v1' if retention else PATCH_REVISION, return dict(engine_revision=UPSTREAM_REVISION, patch_revision='rag-local-s2s-responsive-v1' if 'stream_batch_sentences' in components['llm'] else ('rag-local-s2s-phase3-retain-v1' if retention else PATCH_REVISION),
contract_revision='rag-local-s2s-phase3-retain-v1' if retention else CONTRACT_REVISION, components=components, contract_revision='rag-local-s2s-phase3-retain-v1' if retention else CONTRACT_REVISION, components=components,
effective_config_sha256=sha256(canonical_json(dict(components=components, session=session)).encode()).hexdigest()) effective_config_sha256=sha256(canonical_json(dict(components=components, session=session)).encode()).hexdigest())
+24
View File
@@ -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
+2
View File
@@ -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()
+13 -4
View File
@@ -3,13 +3,16 @@ 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
LOCAL_S2S_STT_MODEL: ${LOCAL_S2S_STT_MODEL:-openai/whisper-large-v3} LOCAL_S2S_STT_MODEL: ${LOCAL_S2S_STT_MODEL:-openai/whisper-large-v3}
LOCAL_S2S_LLM_MODEL: ${LOCAL_S2S_LLM_MODEL:-openai/gpt-4.1-mini} LOCAL_S2S_LLM_MODEL: ${LOCAL_S2S_LLM_MODEL:-openai/gpt-4.1-mini}
LOCAL_S2S_TTS_MODEL: ${LOCAL_S2S_TTS_MODEL:-google/gemini-3.8-flash-lite-tts} LOCAL_S2S_TTS_MODEL: ${LOCAL_S2S_TTS_MODEL:-gpt-4o-mini-tts-2025-12-15}
LOCAL_S2S_TTS_VOICE: ${LOCAL_S2S_TTS_VOICE:-Kore} LOCAL_S2S_TTS_VOICE: ${LOCAL_S2S_TTS_VOICE:-alloy}
LOCAL_S2S_MAX_OUTPUT_TOKENS: "256" LOCAL_S2S_MAX_OUTPUT_TOKENS: "256"
LOCAL_S2S_REQUEST_TIMEOUT_SECONDS: "30" LOCAL_S2S_REQUEST_TIMEOUT_SECONDS: "30"
LOCAL_S2S_TOKEN: ${LOCAL_S2S_TOKEN:-} LOCAL_S2S_TOKEN: ${LOCAL_S2S_TOKEN:-}
@@ -53,14 +56,20 @@ services:
VOICE_TRANSPORT_TESTING: "true" VOICE_TRANSPORT_TESTING: "true"
LOCAL_S2S_STT_MODEL: ${LOCAL_S2S_STT_MODEL:-openai/whisper-large-v3} LOCAL_S2S_STT_MODEL: ${LOCAL_S2S_STT_MODEL:-openai/whisper-large-v3}
LOCAL_S2S_LLM_MODEL: ${LOCAL_S2S_LLM_MODEL:-openai/gpt-4.1-mini} LOCAL_S2S_LLM_MODEL: ${LOCAL_S2S_LLM_MODEL:-openai/gpt-4.1-mini}
LOCAL_S2S_TTS_MODEL: ${LOCAL_S2S_TTS_MODEL:-google/gemini-3.8-flash-lite-tts} LOCAL_S2S_TTS_MODEL: ${LOCAL_S2S_TTS_MODEL:-gpt-4o-mini-tts-2025-12-15}
LOCAL_S2S_TTS_VOICE: ${LOCAL_S2S_TTS_VOICE:-Kore} LOCAL_S2S_TTS_VOICE: ${LOCAL_S2S_TTS_VOICE:-alloy}
LOCAL_S2S_MAX_OUTPUT_TOKENS: "256" LOCAL_S2S_MAX_OUTPUT_TOKENS: "256"
LOCAL_S2S_REQUEST_TIMEOUT_SECONDS: "30" LOCAL_S2S_REQUEST_TIMEOUT_SECONDS: "30"
LOCAL_S2S_TOKEN: ${LOCAL_S2S_TOKEN:-} LOCAL_S2S_TOKEN: ${LOCAL_S2S_TOKEN:-}
# 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
+40 -40
View File
@@ -1,51 +1,51 @@
# Project documentation # Project documentation
The current implementation baseline is the English revision 1.3 Start with [current status](current-status.md) for implemented capabilities,
[Live document MVP delivery plan](specifications/RAG-AI-Phase1-Delivery-Plan.md). the last recorded local profile, evidence boundaries and remaining gates.
It targets a conditional four-day demo using the existing ingestion/embedding Use the [reference map](agent-reference-map.md) for source locations and dated
Phases 1-4, LangChain RAG/tools, new browser uploads and direct Gemini Live. authorized amendments. Historical reports describe the run/date named in them;
The four supplied examples are mandatory initial tests, not an upload allowlist. their pending or running statements do not describe today's service state.
Full text chat/history and settings editing are deferred.
## Implementation reading order ## Contract authority
1. [Delivery plan](specifications/RAG-AI-Phase1-Delivery-Plan.md): active scope, gates, Days 1-4 and MVP-01 through MVP-14. 1. [Phase 1 delivery plan](specifications/RAG-AI-Phase1-Delivery-Plan.md): scope.
2. [Implementation guide](specifications/RAG-Phase1-Implementation-Guide.md): work packages, embedding/LangChain boundary, worker and retained review/resume. 2. [API catalog](specifications/RAG-Phase1-API-Catalog.md): public contracts and amendments.
3. [API catalog](specifications/RAG-Phase1-API-Catalog.md): active/deferred routes, D06/D07 exact review and authenticated Live. 3. [Database design](specifications/RAG-Phase1-Database-Design.md): persistence contracts.
4. [Database design](specifications/RAG-Phase1-Database-Design.md): existing foundation, proposed forward review/identity/voice changes and invariants. 4. [Implementation guide](specifications/RAG-Phase1-Implementation-Guide.md): workflows.
5. [English scenarios](specifications/RAG-Phase1-MVP-Scenarios.md): supplied and unseen uploads, factual FAQ, voice and failure walkthroughs. 5. [English scenarios](specifications/RAG-Phase1-MVP-Scenarios.md): acceptance scenarios.
6. [Architecture](specifications/RAG-AI-Architecture.md): dependency boundaries; broader deferred sections are context. 6. [Architecture](specifications/RAG-AI-Architecture.md): broader context and boundaries.
The plan governs scope, API/database govern contracts and the guide governs The English revision 1.3 baseline is amended by the dated authorized changes in
workflows. Proposed mechanisms are not implementation-completion reports. the reference map. Existing code alone does not override a contract. Full text
chat/history and arbitrary settings/model editing remain deferred. The Persian
revision 1.2 scenario report is historical.
Implementation progress is tracked in the [Live document MVP TODO](plans/live-document-mvp-todo.md). Checked baseline components do not prove complete MVP acceptance. ## Operations and validation
## Current code and recorded evidence - [Backend startup/recovery](guides/phase4-backend-operations.md).
- [Current local Windows stack](guides/current-local-stack.md): final recorded
routing, profile settings, startup dependencies, HTTPS and verification.
- [Foundation setup](guides/ingestion-foundation-setup.md) and
[worker orchestration](guides/worker-orchestration.md).
- [Tests](../tests/README.md): provider-free checks and isolated PostgreSQL acceptance.
- [Local S2S engine](../services/local_s2s/README.md): build/native-engine details.
- [Progress checklist](plans/live-document-mvp-todo.md) and
[Local S2S progress](plans/local-s2s-adapter-progress.md).
- [Reference map](agent-reference-map.md): source inventory, agent routes and historical acceptance. ## Latest change reports
- [Ingestion pipeline plan](plans/ingestion-pipeline-plan.md): implemented ingestion Phases 1-6 backend/validation and pending HTTP/search/Live integration.
- [Setup and validation](guides/ingestion-foundation-setup.md): actual commands and recorded checks; real provider/voice quality remains separate.
- [Repository instructions](../AGENTS.md) and [test guidance](../tests/README.md).
Phase 5 worker/publication/retry and retained review/resume backend services are - [Deletion, public models and diagnostics](guides/server-source-sync-20261018.md).
implemented; [Phase 6 operator handoff](guides/ingestion-operator-handoff.md) - [GapGPT and subsequent ElevenLabs activation](guides/local-gapgpt-20261018.md).
records integration acceptance and the separate opt-in provider smoke command. - [Strict current-turn grounding and ten-source retrieval](guides/strict-grounding-20261018.md).
Scoped pgvector search/selection and Fast-Track Search Phase 2 technical - [LAN HTTPS and client trust](guides/local-lan-access-20261018.md).
correctness are implemented; [Phase 2 results and calibration prerequisites](guides/scoped-search-phase2.md) - [Combined ingestion/RAG/voice evidence](evaluation/local-s2s/combined-ready-20261017.md).
record actual acceptance. Real-model cutoff calibration, LangChain, authenticated - [Presentation diagrams](presentation/README.md).
D06/D07 transport, HTTP identity/upload, browser integration, Live and UI remain pending. Real-provider
compatibility and Persian extraction/semantic quality are not certified by mocks.
The [root README](../README.md) retains prototype startup instructions.
## Historical context and corpus boundary The modular backend implements identity/upload/review transport, scoped search
and authenticated voice; older ingestion reports that call these pending are
historical checkpoints. Frontend source lives in the sibling repository and
cannot be committed from this repository.
The [Persian scenario report](specifications/RAG-Phase1-Scenario-Report-FA.md) Documentation stays under docs; uploaded/sample corpus stays under data.
is preserved as historical revision 1.2. New MVP instructions/scenarios are English. Preserve applied migrations, immutable document identities, technical revisions
Older text/history/settings promises do not override revision 1.3. and compatible embedding profiles. Do not rebuild an index as documentation cleanup.
Project documentation stays under docs; uploaded/sample corpus stays under data.
Documentation changes do not clean/rebuild any existing vector index.
Preserve applied migrations, independent immutable document IDs, technical
revisions and compatible embedding profiles. Do not index project specifications
as organization knowledge.
+43 -9
View File
@@ -1,5 +1,39 @@
Current documentation reconciliation (2026-10-20):
[implementation/evidence status](current-status.md) and
[consolidated local Windows runbook](guides/current-local-stack.md).
The latest recorded runtime remains 2026-10-18, not a fresh uptime check.
Live schema head is 0006_voice_model_settings; public models remain deployment-owned.
Dated checkpoints below are historical where superseded.
# Phase 1 agent reference map # Phase 1 agent reference map
Latest user override (2026-10-18): [strict evidence-only local voice answers and ten-source retrieval](guides/strict-grounding-20261018.md). Shared retrieval now admits up to ten whole chunks within 12,000 characters. Local engine validates extractive output before TTS; uploaded-FAQ calibration replaces the previous local synthetic report. Existing settings-editor rollback remains in effect.
Latest local LAN access (2026-10-18): [HTTPS LAN setup and client certificate](guides/local-lan-access-20261018.md). Local test is also available at https://192.168.180.151:4201/login, with same-origin WSS and a LocalSubnet-only firewall rule. A second physical client must trust the local CA for microphone use.
Latest local activation (2026-10-18): [Local S2S through GapGPT](guides/local-gapgpt-20261018.md). Local STT now uses ElevenLabs scribe_v2; TTS uses ElevenLabs eleven_v3/George with explicit PCM 24000Hz and speed 1.2. Only LLM gpt-4.1-mini remains on GapGPT. The local total request deadline is 60 seconds. Existing embedding profile/documents preserved; microphone acceptance pending.
Latest user-authorized source import (2026-10-18): [deployed deletion, model display/provider choice and S2S diagnostics](guides/server-source-sync-20261018.md). D05 HTTP/UI is enabled; F01 exposes public deployed model identifiers. Other settings mutation remains deferred. The API catalog amendment supersedes older deferred-D05 and no-model-display statements for this scope.
Latest document-intake override (2026-10-17): mandatory admin review disabled for new isolated-test uploads; existing Gemini 2.5 Flash Vision configured, automatic admission with warnings enabled. Four user files independently reimported and ready (5/100/3/21 chunks), 75 relevant tests passed. Historical failed rows preserved; active knowledge selection unchanged. Details in [combined runtime evidence](evaluation/local-s2s/combined-ready-20261017.md).
Latest user override and runtime (2026-10-17): [both voice providers and calibrated RAG ready](evaluation/local-s2s/combined-ready-20261017.md). Cost admission disabled explicitly; old budget ceilings below are historical. Memory prevention remains OFF. Direct OpenAI ASR/TTS, 85 focused tests passed, both actual session_ready/normal close passed, bge-m3 calibration reproduced 6/6 supported and 0/4 false positives. Microphone acceptance and immediate provider-switch cleanup remain open.
Latest responsive candidate (2026-10-17): [sentence-at-a-time and ASR policy implemented/live](evaluation/local-s2s/responsive-candidate-20261017.md). 157 unit +3 PostgreSQL passed; actual single-sentence native active-cancel/history fixture passed; real startup and proxied setup/normal close passed. Human Persian accuracy/latency comparison pending. Reserve $0.769884452, exclusive ceiling $0.981884452. Memory prevention OFF; no old-ledger restart.
Latest human result (2026-10-17): [two real playback interruptions and continuation passed](evaluation/local-s2s/windows-live-interruption-20261017.md). User confirms intentional barge-in and no stale audio. Generation had already completed at both cuts; active cancellation and same-answer repeat untested. New12 bills total $0.006186253; reconciled exposure $0.710884452. Engine stopped after attempt caps; UI/API remain. Memory prevention OFF. Phase3/4 open.
Latest active Windows handoff (2026-10-17): [second browser test ready](evaluation/local-s2s/windows-browser-handoff-02-20261017.md). Memory prevention OFF per user; startup and proxied session_ready/normal close passed. New exclusive billed carry baseline $0.704698199, reserve $0.763698199, ceiling $0.940698199. Human test now required; RAG/OpenAI comparison pending. Never restart the ledger.
User override (2026-10-17): Windows browser memory prevention is temporarily disabled by default; monitoring continues. `--enforce-memory-floor` restores preflight/runtime RAM checks. Docker memory cap, budget/exclusive ledger and time limits remain. See [incident and override](evaluation/local-s2s/windows-browser-stop-20261017.md). No paid restart occurred.
Latest Windows incident (2026-10-17): [engine stopped on memory floor before human tests](evaluation/local-s2s/windows-browser-stop-20261017.md). Earlier browser-ready handoff is inactive. Two user setup failures made no inference calls. Exact startup bills reconcile new exposure to $0.704698199, with full older reserves retained; exclusive ledger not restarted. Memory headroom and a verified billing-linked new carry are required before another paid launch.
Latest Windows handoff (2026-10-17): [human browser test ready](evaluation/local-s2s/windows-browser-handoff-20261017.md). Actual startup and proxied session_ready/normal close passed; carried reserve $0.763504399, exclusive ceiling $0.940504399. Real microphone/interruption acceptance, RAG and bounded OpenAI comparison remain pending. Engine expires after30minutes; never restart this ledger.
Current host continuation (2026-10-17): [Windows reconstruction and budget carry](evaluation/local-s2s/windows-continuation-20261017.md). Prior tests ran on another computer. Native images/private ledgers are absent here; verified source/assets and conservative $0.704504399 carry are prepared. No new paid inference or Phase 3/4 acceptance. Windows host memory and bounded admission remain launch gates.
Current preparation (2026-10-16): [Phase 4 frontend/provider selection and paired evaluation tooling](evaluation/local-s2s/phase-04.md). Current preparation (2026-10-16): [Phase 4 frontend/provider selection and paired evaluation tooling](evaluation/local-s2s/phase-04.md).
Phase 3 retains interrupted answers as explicitly unheard drafts per the user's Phase 3 retains interrupted answers as explicitly unheard drafts per the user's
revised policy; real barge-in/RAG/factual acceptance remains pending. Phase 4 is revised policy; real barge-in/RAG/factual acceptance remains pending. Phase 4 is
@@ -187,7 +221,7 @@ Section numbers and heading names below are verified against these files; no inf
| --- | --- | --- | | --- | --- | --- |
| `RAG-AI-Phase1-Delivery-Plan.md` | [Delivery plan](specifications/RAG-AI-Phase1-Delivery-Plan.md) | Scope, sequence, acceptance: 3. Included and Deferred Scope; 6. Document Lifecycle and Knowledge Changes; 8. Delivery Schedule and Checkpoints; 9. Acceptance Criteria; 10. Demonstration Script | | `RAG-AI-Phase1-Delivery-Plan.md` | [Delivery plan](specifications/RAG-AI-Phase1-Delivery-Plan.md) | Scope, sequence, acceptance: 3. Included and Deferred Scope; 6. Document Lifecycle and Knowledge Changes; 8. Delivery Schedule and Checkpoints; 9. Acceptance Criteria; 10. Demonstration Script |
| `RAG-Phase1-Implementation-Guide.md` | [Implementation guide](specifications/RAG-Phase1-Implementation-Guide.md) | Modules/workflows: 3. Modules and ports; 5. Identity and request context; 6. Document upload and ingestion; 7. Selection, revisions and revocation; 8. Deferred text turn execution; 9. Live lifecycle; 10. Internal search contract; 12. Tests and handoff; 13. Decisions still requiring confirmation | | `RAG-Phase1-Implementation-Guide.md` | [Implementation guide](specifications/RAG-Phase1-Implementation-Guide.md) | Modules/workflows: 3. Modules and ports; 5. Identity and request context; 6. Document upload and ingestion; 7. Selection, revisions and revocation; 8. Deferred text turn execution; 9. Live lifecycle; 10. Internal search contract; 12. Tests and handoff; 13. Decisions still requiring confirmation |
| `RAG-Phase1-API-Catalog.md` | [API catalog](specifications/RAG-Phase1-API-Catalog.md) | Routes/DTOs/permissions/errors/replay: 1. Transport and common conventions; 2. Endpoint inventory; 4. Documents and selected knowledge; 6. Conversations and deferred text; 7. Voice contract أ¢â‚¬â€‌ OpenAI Realtime; frozen application audio/events; 9. Error envelope and mapping | | `RAG-Phase1-API-Catalog.md` | [API catalog](specifications/RAG-Phase1-API-Catalog.md) | Routes/DTOs/permissions/errors/replay: 1. Transport and common conventions; 2. Endpoint inventory; 4. Documents and selected knowledge; 6. Conversations and deferred text; 7. Voice contract ط·آ£ط¢آ¢ط£آ¢أ¢â‚¬ع‘ط¢آ¬ط£آ¢أ¢â€ڑآ¬أ¢â‚¬إ’ OpenAI Realtime; frozen application audio/events; 9. Error envelope and mapping |
| `RAG-Phase1-Database-Design.md` | [Database design](specifications/RAG-Phase1-Database-Design.md) | Schema/constraints/transactions: 4. Knowledge tables; 5. Minimal voice conversation and evidence; deferred text tables; 6. Live and audit tables; 7. Transaction boundaries and invariant enforcement; 8. Migration plan; 9. Essential database validation | | `RAG-Phase1-Database-Design.md` | [Database design](specifications/RAG-Phase1-Database-Design.md) | Schema/constraints/transactions: 4. Knowledge tables; 5. Minimal voice conversation and evidence; deferred text tables; 6. Live and audit tables; 7. Transaction boundaries and invariant enforcement; 8. Migration plan; 9. Essential database validation |
| `RAG-Phase1-MVP-Scenarios.md` | [English MVP scenarios](specifications/RAG-Phase1-MVP-Scenarios.md) | Current journeys: 2. Examples and unseen files; 3. Upload/replay; 4-5. Exact review and factual FAQ; 6. Publication; 7-10. Voice/failure/revocation; 11-12. Restart/evaluation | | `RAG-Phase1-MVP-Scenarios.md` | [English MVP scenarios](specifications/RAG-Phase1-MVP-Scenarios.md) | Current journeys: 2. Examples and unseen files; 3. Upload/replay; 4-5. Exact review and factual FAQ; 6. Publication; 7-10. Voice/failure/revocation; 11-12. Restart/evaluation |
| `RAG-AI-Architecture.md` | [Architecture](specifications/RAG-AI-Architecture.md) | Context/future direction: 4. Backend Modules and Dependency Rules; 6. Search Tool Contract; 7. Dynamic Document Lifecycle; 17. Historical prototype mapping; 19. Open Decisions and Owners; 22. Current Live document MVP decisions | | `RAG-AI-Architecture.md` | [Architecture](specifications/RAG-AI-Architecture.md) | Context/future direction: 4. Backend Modules and Dependency Rules; 6. Search Tool Contract; 7. Dynamic Document Lifecycle; 17. Historical prototype mapping; 19. Open Decisions and Owners; 22. Current Live document MVP decisions |
@@ -446,11 +480,11 @@ Persian, ZWNJ, CJK and emoji metadata. No real provider checks were run; these
repairs introduce no provider behavior. Original-store power-loss guarantees and repairs introduce no provider behavior. Original-store power-loss guarantees and
unavailable Windows symlink creation remain outside the verified evidence. unavailable Windows symlink creation remain outside the verified evidence.
## Persian document and voice MVP documentation أ¢â‚¬â€‌ 2026-10-06 ## Persian document and voice MVP documentation ط·آ£ط¢آ¢ط£آ¢أ¢â‚¬ع‘ط¢آ¬ط£آ¢أ¢â€ڑآ¬أ¢â‚¬إ’ 2026-10-06
The governing specifications now include page-level PDF quality/fallback, DOCX FAQ pairing, infographic group preservation, retained extraction artifacts, shared semantic/identifier retrieval and direct Gemini Live `search_knowledge`. The earlier proposed `search_documents` name and SDP request/answer contract are superseded; prototype `retriever_tool` remains unchanged. The governing specifications now include page-level PDF quality/fallback, DOCX FAQ pairing, infographic group preservation, retained extraction artifacts, shared semantic/identifier retrieval and direct Gemini Live `search_knowledge`. The earlier proposed `search_documents` name and SDP request/answer contract are superseded; prototype `retriever_tool` remains unchanged.
[Architecture Sections 7, 8 and 21](specifications/RAG-AI-Architecture.md) cover diagrams, decisions and static implementation evidence. [Delivery plan Sections 9 and 14أ¢â‚¬â€œ15](specifications/RAG-AI-Phase1-Delivery-Plan.md) retain P1-01أ¢â‚¬â€œP1-12, add P1-13أ¢â‚¬â€œP1-17 and record budget/account/rehearsal gates. [API Section 7](specifications/RAG-Phase1-API-Catalog.md) distinguishes HTTP, application Live WSS and internal tools. [Database Section 4.4](specifications/RAG-Phase1-Database-Design.md) proposes extraction artifacts without content-version entities. [Persian scenarios Sections 18أ¢â‚¬â€œ22](specifications/RAG-Phase1-Scenario-Report-FA.md) document actual sample inspection limits and worked examples. [Architecture Sections 7, 8 and 21](specifications/RAG-AI-Architecture.md) cover diagrams, decisions and static implementation evidence. [Delivery plan Sections 9 and 14ط·آ£ط¢آ¢ط£آ¢أ¢â‚¬ع‘ط¢آ¬ط£آ¢أ¢â€ڑآ¬ط¥â€œ15](specifications/RAG-AI-Phase1-Delivery-Plan.md) retain P1-01ط·آ£ط¢آ¢ط£آ¢أ¢â‚¬ع‘ط¢آ¬ط£آ¢أ¢â€ڑآ¬ط¥â€œP1-12, add P1-13ط·آ£ط¢آ¢ط£آ¢أ¢â‚¬ع‘ط¢آ¬ط£آ¢أ¢â€ڑآ¬ط¥â€œP1-17 and record budget/account/rehearsal gates. [API Section 7](specifications/RAG-Phase1-API-Catalog.md) distinguishes HTTP, application Live WSS and internal tools. [Database Section 4.4](specifications/RAG-Phase1-Database-Design.md) proposes extraction artifacts without content-version entities. [Persian scenarios Sections 18ط·آ£ط¢آ¢ط£آ¢أ¢â‚¬ع‘ط¢آ¬ط£آ¢أ¢â€ڑآ¬ط¥â€œ22](specifications/RAG-Phase1-Scenario-Report-FA.md) document actual sample inspection limits and worked examples.
All four supplied files exist in `data/documents/`; DOCX XML and infographic were inspected locally, and PDF structure confirms five/one pages. Full local PDF text/layout extraction was unavailable; prior word/number-order observations remain supplied context. No provider/OCR benchmark or Persian speech test was run. All four supplied files exist in `data/documents/`; DOCX XML and infographic were inspected locally, and PDF structure confirms five/one pages. Full local PDF text/layout extraction was unavailable; prior word/number-order observations remain supplied context. No provider/OCR benchmark or Persian speech test was run.
@@ -902,7 +936,7 @@ Executed evidence for these four semantic repairs (2026-10-06):
An intermediate corrected targeted run had one compatibility failure: An intermediate corrected targeted run had one compatibility failure:
`Decision dated 1403/01/02` was being treated as an identifier. The final parser `Decision dated 1403/01/02` was being treated as an identifier. The final parser
recognizes the explicit dated/ط¸â€¦ط¸ث†ط·آ±ط·آ® metadata qualifier; the existing control passes. recognizes the explicit dated/ط·آ·ط¢آ¸ط£آ¢أ¢â€ڑآ¬ط¢آ¦ط·آ·ط¢آ¸ط·آ«أ¢â‚¬آ ط·آ·ط¢آ·ط·آ¢ط¢آ±ط·آ·ط¢آ·ط·آ¢ط¢آ® metadata qualifier; the existing control passes.
Real-provider extraction quality and manual Persian fidelity acceptance remain Real-provider extraction quality and manual Persian fidelity acceptance remain
**unverified**. These generated fixtures and fake providers do not establish **unverified**. These generated fixtures and fake providers do not establish
@@ -936,7 +970,7 @@ changes, immutable originals, frozen profiles, normalization and applied migrati
Active position/case/hiding semantics fail safely; resets, harmless formatting Active position/case/hiding semantics fail safely; resets, harmless formatting
and unused styles pass. Deeper DOCX answer headings/table continuations stay and unused styles pass. Deeper DOCX answer headings/table continuations stay
atomic; incomplete/ambiguous/oversized groups fail. English singular/plural and atomic; incomplete/ambiguous/oversized groups fail. English singular/plural and
Persian ط¸â€¦ط·آ§ط·آ¯ط¸â€،/ط¸â€¦ط¸ث†ط·آ§ط·آ¯ targets support explicit conjunction/comma lists and simple Persian ط·آ·ط¢آ¸ط£آ¢أ¢â€ڑآ¬ط¢آ¦ط·آ·ط¢آ·ط·آ¢ط¢آ§ط·آ·ط¢آ·ط·آ¢ط¢آ¯ط·آ·ط¢آ¸ط£آ¢أ¢â€ڑآ¬ط·إ’/ط·آ·ط¢آ¸ط£آ¢أ¢â€ڑآ¬ط¢آ¦ط·آ·ط¢آ¸ط·آ«أ¢â‚¬آ ط·آ·ط¢آ·ط·آ¢ط¢آ§ط·آ·ط¢آ·ط·آ¢ط¢آ¯ targets support explicit conjunction/comma lists and simple
integer ranges; unsupported malformed/complex identifiers fail. Incidental integer ranges; unsupported malformed/complex identifiers fail. Incidental
citations and ordinary decision prose remain accepted. See the setup guide for citations and ordinary decision prose remain accepted. See the setup guide for
exact grammar and output/intake bounds. Attachment/reuse remain Phase 5 gated; exact grammar and output/intake bounds. Attachment/reuse remain Phase 5 gated;
@@ -2044,8 +2078,8 @@ Exactly one API process owns media guards; ingestion runs separately. Fake tests
are not real provider/Persian speech/browser hardware or frontend readiness proof. are not real provider/Persian speech/browser hardware or frontend readiness proof.
Verified final commands: `.venv/bin/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short` Verified final commands: `.venv/bin/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short`
أ¢â‚¬â€‌ **1679 passed**, two existing Windows path skips; `.venv/bin/python -m pytest -m postgres --require-postgres -q -p no:cacheprovider --tb=short` ط·آ£ط¢آ¢ط£آ¢أ¢â‚¬ع‘ط¢آ¬ط£آ¢أ¢â€ڑآ¬أ¢â‚¬إ’ **1679 passed**, two existing Windows path skips; `.venv/bin/python -m pytest -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
أ¢â‚¬â€‌ **372 passed**, zero skips, using only the isolated task-created test database. ط·آ£ط¢آ¢ط£آ¢أ¢â‚¬ع‘ط¢آ¬ط£آ¢أ¢â€ڑآ¬أ¢â‚¬إ’ **372 passed**, zero skips, using only the isolated task-created test database.
Affected PostgreSQL cases: **61 passed**. Missing TEST_DATABASE_URL produced the Affected PostgreSQL cases: **61 passed**. Missing TEST_DATABASE_URL produced the
required prerequisite failure. Executable JS, syntax/compile, diff and baseline required prerequisite failure. Executable JS, syntax/compile, diff and baseline
preservation checks passed. See the report for exact durations, failed/interrupted preservation checks passed. See the report for exact durations, failed/interrupted
@@ -2062,7 +2096,7 @@ intake/review/worker/selection services, with bounded streaming
prior pending-HTTP statements above. The standalone frontend developer handoff is prior pending-HTTP statements above. The standalone frontend developer handoff is
[Phase 3 integration](guides/realtime-agent-phase3-handoff.md), with executable [Phase 3 integration](guides/realtime-agent-phase3-handoff.md), with executable
DocumentClient and a same-origin Vite proxy example. Existing VoiceClient/worklet, DocumentClient and a same-origin Vite proxy example. Existing VoiceClient/worklet,
Gemini/OpenAI selection, canonical search and migrations 0001أ¢â‚¬â€œ0005 are preserved. Gemini/OpenAI selection, canonical search and migrations 0001ط·آ£ط¢آ¢ط£آ¢أ¢â‚¬ع‘ط¢آ¬ط£آ¢أ¢â€ڑآ¬ط¥â€œ0005 are preserved.
`INGEST_OCR_REVIEW_REQUIRED=true` is a deployment default frozen in new job `INGEST_OCR_REVIEW_REQUIRED=true` is a deployment default frozen in new job
profiles; false admits only automatically validated OCR. Legacy profiles retain profiles; false admits only automatically validated OCR. Legacy profiles retain
@@ -2348,7 +2382,7 @@ current-turn labels from delivered search/reuse evidence; the existing sources
event shows that subset, not every retrieval candidate. Metadata reports do not event shows that subset, not every retrieval candidate. Metadata reports do not
create retrieval rows. See `tests/unit/test_voice_reported_sources.py` and create retrieval rows. See `tests/unit/test_voice_reported_sources.py` and
`tests/integration/test_voice_evidence_reuse.py` for validation and revocation `tests/integration/test_voice_evidence_reuse.py` for validation and revocation
coverage. Optional acknowledgement is only «یه لحظه…» once per turn, under coverage. Optional acknowledgement is only ط¢آ«ط؛إ’ط¸â€، ط¸â€‍ط·آ­ط·آ¸ط¸â€،أ¢â‚¬آ¦ط¢آ» once per turn, under
OpenAI delivery v5. New sessions pin the selected-evidence policy revision; OpenAI delivery v5. New sessions pin the selected-evidence policy revision;
existing reservations are not rewritten. Real provider adherence remains existing reservations are not rewritten. Real provider adherence remains
separate from deterministic runtime tests. separate from deterministic runtime tests.
@@ -8,7 +8,7 @@
"dimensions": 1024, "dimensions": 1024,
"preprocessing_version": "v1" "preprocessing_version": "v1"
}, },
"distance": 0.65, "distance": 0.72,
"retrieval_policy": "exact-first-cosine-id-50x2-whole-5-12000/nfc-digits-kaf-yeh-lower-whitespace-terminal-period-v2" "retrieval_policy": "exact-first-cosine-id-50x2-whole-5-12000/nfc-digits-kaf-yeh-lower-whitespace-terminal-period-v2"
}, },
"complete_support": 6, "complete_support": 6,
+104
View File
@@ -0,0 +1,104 @@
# Current implementation and recorded evidence
Documentation reconciled 2026-10-20 against the working tree. The latest local
runtime evidence is dated 2026-10-18; no service uptime, provider call or new human
acceptance is inferred from this documentation update.
## Implemented baseline
The modular FastAPI backend runs through app.server with a separate app.worker,
PostgreSQL/pgvector and durable originals/extraction artifacts. Authentication,
upload/status, retained review/resume, eligible failed-job retry, active knowledge
selection and soft deletion have backend implementations. Every upload creates
an independent immutable document; retries reuse the eligible document/job.
Deletion retains original/chunk content while removing eligibility, fencing
publication and invalidating affected context.
Shared backend retrieval enforces organization/access scope and ready, active,
undeleted, unpurged eligibility. It admits up to ten whole chunks within 12,000
characters, with document_id/chunk_id references and policy whole-10-12000.
Calibration must match the embedding profile and retrieval policy.
SearchInput also removes recognized organization-name filler from longer Persian
queries while preserving backend-derived scope; see the grounding guide.
Voice has private OpenAI, Gemini and development-only Local S2S adapters.
Reservations pin provider/profile identity; provider changes require a fresh
session. Public F01 model identifiers are deployment-owned display information,
not an arbitrary model editor. D05 deletion is enabled; general settings editing
and full text chat/history remain deferred.
## Last recorded local profile
| Component | Recorded selection |
| --- | --- |
| STT | ElevenLabs scribe_v2, Persian |
| Dialogue | GapGPT gpt-4.1-mini |
| TTS | ElevenLabs eleven_v3, George, speed 1.2, PCM mono 24 kHz |
| Request deadline | 60 seconds |
| Embedding | Existing local bge-m3 profile, preserved |
| Grounding | Current-turn extractive gate before local TTS |
| Live schema head | 0006_voice_model_settings |
| Loopback frontend | http://127.0.0.2:4201/login |
| LAN frontend | https://192.168.180.151:4201/login |
These are local test observations, not repository defaults or a production switch.
The full profile, host dependencies and startup references are in the
[local runbook](guides/current-local-stack.md).
## Evidence and open gates
- [Source import](guides/server-source-sync-20261018.md): 146 focused backend
checks, seven isolated PostgreSQL deletion cases, frontend build and 20
frontend tests recorded. Three cancellation-diagnostic expectations also failed
against the original HEAD runtime and remain open baseline failures.
- [Final ElevenLabs route](guides/local-gapgpt-20261018.md): 164 focused
provider-free checks and successful native component warmups recorded.
This does not establish human Persian accuracy, latency or listening quality.
- [Strict grounding](guides/strict-grounding-20261018.md): 108 focused checks,
actual gateway answer/refusal checks, six supported calibration cases and four
negative cases recorded. Calibration is not held-out quality acceptance.
- [LAN verification](guides/local-lan-access-20261018.md): TLS, login and WSS
setup/normal close passed from the host. A second physical client remains open.
- Earlier browser/interruption acceptance applies to its recorded provider/profile.
The latest ElevenLabs/strict-grounding profile still needs human microphone,
spoken-answer and interruption acceptance and a bounded paired comparison.
- The 2026-10-20 targeted provider-free run passed 199 tests (command below).
The full provider-free run stopped producing output late in the suite and was
interrupted; it has no passing final result. TEST_DATABASE_URL was absent, so
PostgreSQL acceptance was not run. Historical database results remain dated
evidence, not verification of this checkout.
The strict local gate can reject correct paraphrases and multi-source synthesis.
Literal source excerpts can still be irrelevant or factually wrong. Common
instructions on other adapters do not provide the local deterministic gate.
## Persistence and reproducibility
Migration 0006 adds organization_settings.voice_models as an object-valued JSONB
column with an empty-object default. Current public model display reads deployment
settings; this column does not establish implemented model mutation endpoints.
Live admission requires the new head. Apply migrations forward and retain
original content, embedding metadata and existing profile bytes.
Host-specific launch wrappers, credentials, local calibration/runtime evidence
and certificates are intentionally ignored. A fresh checkout needs equivalent
host provisioning; it cannot reproduce the running stack using tracked files
alone. The [runbook](guides/current-local-stack.md) identifies those dependencies.
## Documentation/commit validation — 2026-10-20
Targeted command (199 passed in 9.73 seconds):
~~~powershell
.venv/Scripts/python -m pytest tests/unit/test_server_source_sync.py tests/unit/test_grounded_voice_regression.py tests/unit/test_local_s2s_elevenlabs.py tests/unit/test_local_s2s_gapgpt.py tests/unit/test_local_s2s_engine.py tests/unit/test_local_s2s_responsiveness.py tests/unit/test_local_s2s_boundary.py tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_repairs.py tests/unit/test_search_phase2.py -m "not postgres" -q -o faulthandler_timeout=30
~~~
The attempted full command was `.venv/Scripts/python -m pytest -m "not postgres" -q`.
It was interrupted after several minutes without further output late in the run;
the stalled case was not identified. No product fix or test expectation change
was made during documentation reconciliation.
Local links in changed/new Markdown were checked: 409 targets, none missing.
Whitespace checks passed. A basic credential-pattern scan of the 42 changed/new
files found no matching provider-key or private-key patterns; this is not a
comprehensive security audit. No service startup or paid-provider call was made.
@@ -1,5 +1,6 @@
"""Actual proxied auth/API/native setup/normal close; sends no microphone audio.""" """Actual proxied auth/API/native setup/normal close; sends no microphone audio."""
import asyncio import asyncio
import argparse
import json import json
from pathlib import Path from pathlib import Path
from uuid import uuid4 from uuid import uuid4
@@ -7,7 +8,12 @@ import httpx
from websockets.asyncio.client import connect from websockets.asyncio.client import connect
root=Path('.local-s2s-build') root=Path('.local-s2s-build')
account=json.loads((root/'browser-login.json').read_text()) parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--account',type=Path,default=root/'browser-login.json')
parser.add_argument('--ledger',type=Path,default=root/'phase4-browser-paid/browser-paid-ledger.json')
parser.add_argument('--output',type=Path,default=root/'phase4-browser-connection-result.json')
args=parser.parse_args()
account=json.loads(args.account.read_text())
origin='http://127.0.0.2:4201' origin='http://127.0.0.2:4201'
async def main(): async def main():
@@ -26,7 +32,7 @@ async def main():
report['providers']=metadata.json() report['providers']=metadata.json()
assert next(p for p in report['providers']['providers'] if p['id']=='local_s2s')['can_start'] assert next(p for p in report['providers']['providers'] if p['id']=='local_s2s')['can_start']
assert not next(p for p in report['providers']['providers'] if p['id']=='openai')['can_start'] assert not next(p for p in report['providers']['providers'] if p['id']=='openai')['can_start']
ledger=root/'phase4-browser-paid'/'browser-paid-ledger.json' ledger=args.ledger
before=len(json.loads(ledger.read_text())['attempts']) before=len(json.loads(ledger.read_text())['attempts'])
try: try:
async with connect('ws://127.0.0.2:4201'+session['stream_path'],origin=origin, async with connect('ws://127.0.0.2:4201'+session['stream_path'],origin=origin,
@@ -44,7 +50,7 @@ async def main():
client.post('/api/v1/auth/logout') client.post('/api/v1/auth/logout')
report['component_attempts_before']=before report['component_attempts_before']=before
report['component_attempts_after']=len(json.loads(ledger.read_text())['attempts']) report['component_attempts_after']=len(json.loads(ledger.read_text())['attempts'])
(root/'phase4-browser-connection-result.json').write_text(json.dumps(report,indent=2)+'\n') args.output.write_text(json.dumps(report,indent=2)+'\n')
assert report.get('session_ready') assert report.get('session_ready')
assert before==report['component_attempts_after'],'Unexpected inference during connection-only check' assert before==report['component_attempts_after'],'Unexpected inference during connection-only check'
print(json.dumps(report)) print(json.dumps(report))
@@ -0,0 +1,51 @@
{
"status": "ready_for_human_test",
"date": "2026-10-17",
"environment": "isolated Windows Docker test",
"cost_controls": "disabled_by_explicit_user_request",
"memory_prevention": false,
"providers": {
"openai": {
"session_ready": true,
"events": [
"session_ready"
]
},
"local_s2s": {
"session_ready": true,
"events": [
"session_ready"
]
}
},
"local_components": {
"asr": "gpt-4o-transcribe",
"asr_endpoint": "https://api.openai.com/v1/audio/transcriptions",
"tts": "gpt-4o-mini-tts-2025-12-15",
"voice": "alloy",
"tts_endpoint": "https://api.openai.com/v1/audio/speech",
"llm": "openai/gpt-4.1-mini via OpenRouter"
},
"calibration": {
"calibration_id": "cd5c3bac-5c83-454a-bb34-19d6c2045294",
"status": "calibrated",
"complete_support": 6,
"unsupported_false_positives": 0,
"cutoff": {
"profile": {
"provider": "ollama",
"endpoint": "http://localhost:11434/v1",
"model": "bge-m3",
"dimensions": 1024,
"preprocessing_version": "v1"
},
"distance": 0.33686461167069426,
"retrieval_policy": "exact-first-cosine-id-50x2-whole-5-12000/nfc-digits-kaf-yeh-lower-whitespace-terminal-period-v2"
},
"provider_calls": 10,
"final_authorization_confirmed": true
},
"unit_tests": "85 passed",
"human_voice_acceptance": "pending",
"rapid_switch_before_media_cleanup": "403 observed; explicit close and waiting for WebSocket close passed"
}
@@ -0,0 +1,31 @@
# Combined voice and calibrated RAG test ? 2026-10-17
Explicit user override: cost admission controls are disabled for this isolated run. Historical bills/reserves are preserved and are no longer this run's admission ceiling. Memory prevention remains off. Docker memory bounds, request timeouts and cancellation remain. Session lifetime is restored to the existing 600-second setting.
Both OpenAI Realtime (existing gpt-realtime-2.1/marin/low/1.30 profile) and local_s2s reached session_ready through the actual frontend proxy. Local ASR gpt-4o-transcribe and TTS gpt-4o-mini-tts-2025-12-15/alloy route directly to OpenAI; LLM remains GPT-4.1 mini through OpenRouter. Direct audio refuses missing OpenAI credentials instead of forwarding the router key. Existing OpenRouter ASR compatibility remains. Four new routing regressions plus affected tests: 85 passed.
RAG uses a new isolated rag_bge_local_s2s_test database and dedicated volumes. The approved original hash and ten frozen labels were preserved; proper intake/worker published six chunks, then fenced selection activated the document. Ollama bge-m3/1024/v1 reproduced the original measured cutoff 0.33686461167069426, six supported cases and zero false positives in four unsupported cases. The old report currently contains 0.65 despite its guide/trials documenting the stricter measured cutoff; it was left unchanged. The new measured report is independently retained.
Runtime files are ignored under .local-s2s-build: windows-combined.compose.json, combined-compose.py, combined-engine.py and combined-evidence/. The launcher forwards only the two required OpenAI keys from the existing .env into the API runtime; it writes no copied provider credentials or full .env mount. Engine uses existing server-only secret mounts. Start from repository root using `.venv/Scripts/python .local-s2s-build/combined-compose.py up -d --no-deps candidate_api candidate_worker local-s2s-engine`. Do not use obsolete budget launchers/watchdogs for this run.
Browser: http://127.0.0.2:4201/login, existing test credentials. Refresh and log in again because test identity belongs to the new isolated database. Ask the approved sample pump-pressure question and unsupported land-price question on both providers. Only the approved calibration sample is loaded here; other operational documents were not silently copied.
Both provider setups and explicit normal close passed. OpenAI-to-local switching passed after waiting for WebSocket closure. Abruptly disconnecting and immediately starting another provider produced 403 while the single media slot was still cleaning up; immediate-switch acceptance remains open. No microphone, listening, ASR accuracy or full spoken RAG acceptance is claimed. Phase 3/4 remain open.
## Temporary automatic document intake override
2026-10-17, explicit user request: candidate API, worker and migration/operator configuration now use the existing OpenRouter Vision profile google/gemini-2.5-flash, 60-second timeout. INGEST_OCR_REVIEW_REQUIRED=false, INGEST_FACTUAL_REVIEW_REQUIRED=false and INGEST_ALLOW_PARTIAL_EXTRACTION=true. This last existing switch also bypasses direct-PDF visual review while retaining automatic-admission warnings. Factual placeholders remain excluded by the existing policy. No human approval was fabricated. This temporary setup admits outputs with warnings and is not a manual accuracy certification.
The launcher forwards only INGEST_VISION_API_KEY in addition to the two necessary OpenAI keys; no additional credential file is created. Existing originals/jobs/profiles are immutable: four files were independently reimported through proper intake with deterministic operation IDs. Old failed rows remain historical. New ready records: photo db37c610-4fb8-4f9f-aa9d-481720a64a86 (5 chunks), DOCX ba72acfa-4f3c-403e-bafe-879b08ed0ccb (100), PDF 5905? 0abd2545-05af-4c7c-8194-6a9182d164e7 (3), PDF 7364? d9c23e5a-8a51-4696-94ac-4a060957c58b (21). Two intermediate stricter-policy PDF attempts failed and remain historical too. All four final jobs published successfully; no pending administrator review. Knowledge selection was not changed by this intake operation; ready documents can be selected separately for RAG. Original calibration sample remains selected.
Validation: 75 relevant unit tests passed (test_phase5_review.py, test_partial_extraction.py, test_gemini_vision.py); real hosted Vision + local bge-m3 embedding + atomic worker publication succeeded. No application behavior code or database migration was changed for this configuration-only operation.
## Local speech pace and selector label
Explicit user request: LOCAL_S2S_TTS_SPEED=1.3 in the isolated runtime; default remains 1.0. Applied before native TTS setup/warmup, forwarded by the existing handler to the speech request, read from the actual initialized handler in component attestation, and included in session identity. No sample-rate or playback-buffer change. Provider metadata label changed to ????? ?????; frontend displays that server-provided label. 45 focused unit tests passed, including applied speed and rejection of a handler-speed mismatch.
## Follow-up: pace 1.6 and unanswered person query
User requested a further pace increase: active local TTS speed is now 1.6 (previously 1.3). Both actual proxied session_ready/normal-close checks passed again; local paid startup probes passed.
Read-only diagnosis: all five ready documents are active at knowledge revision 6. Local tool queries were the Persian equivalent of Mr. Danesh and deputy of planning; OpenAI queried Danesh. Both returned succeeded/no_evidence, not provider errors. The extracted 5905 PDF contains the salutation Mr. Danesh followed by deputy of planning. Candidate distances for Mr. Danesh started at 0.5615, while the active calibration cutoff is 0.33686461167069426; all 50 candidates were filtered out. Role query nearest distance 0.4371 was rejected too. Existing exact lexical matching handles article/date/alphanumeric identifiers, not person names. The calibration sample does not establish recall for these real document questions. No threshold or retrieval contract was changed; a name-query retrieval repair and real-corpus evaluation remain pending. Original PDF text-layer matching did not independently verify the OCR person spelling, so the extracted text is evidence of the retrieval defect, not manual certification of the original image.
@@ -38,6 +38,7 @@ real = mode == 'real'
duplex = '--duplex' in sys.argv duplex = '--duplex' in sys.argv
retention = '--retention' in sys.argv or '--retention-active' in sys.argv retention = '--retention' in sys.argv or '--retention-active' in sys.argv
retention_active = '--retention-active' in sys.argv retention_active = '--retention-active' in sys.argv
responsive = '--responsive' in sys.argv
assert not (retention and real) assert not (retention and real)
assert not (duplex and real) assert not (duplex and real)
models = ('openai/whisper-large-v3', 'openai/gpt-4.1-mini', 'google/gemini-3.8-flash-lite-tts', 'Kore') if real else ('fixture/stt', 'fixture/llm', 'fixture/tts', 'fixture') models = ('openai/whisper-large-v3', 'openai/gpt-4.1-mini', 'google/gemini-3.8-flash-lite-tts', 'Kore') if real else ('fixture/stt', 'fixture/llm', 'fixture/tts', 'fixture')
@@ -54,7 +55,7 @@ config = VoiceSettings(_env_file=None, provider='local_s2s', local_s2s_enabled=T
local_s2s_stt_model=models[0], local_s2s_llm_model=models[1], local_s2s_stt_model=models[0], local_s2s_llm_model=models[1],
local_s2s_tts_model=models[2], local_s2s_tts_voice=models[3], local_s2s_tts_model=models[2], local_s2s_tts_voice=models[3],
local_s2s_request_timeout_seconds=timeout, local_s2s_max_output_tokens=limit, local_s2s_request_timeout_seconds=timeout, local_s2s_max_output_tokens=limit,
local_s2s_retain_interrupted_answers=retention) local_s2s_retain_interrupted_answers=retention, local_s2s_responsive=responsive)
config.require_voice() config.require_voice()
adapter = LocalS2SAdapter(None, config=config, settings=RuntimeSettings(_env_file=None)) adapter = LocalS2SAdapter(None, config=config, settings=RuntimeSettings(_env_file=None))
calls, events, logs, owned = [], [], [], {} calls, events, logs, owned = [], [], [], {}
@@ -98,7 +99,7 @@ async def upstream(request):
class InterruptedStream(httpx.AsyncByteStream): class InterruptedStream(httpx.AsyncByteStream):
async def __aiter__(self): async def __aiter__(self):
initial=deepcopy(chunks[0]) initial=deepcopy(chunks[0])
initial['choices'][0]['delta']['content']=fixture_text+' One preserved sentence. Another preserved sentence. Pending fragment' initial['choices'][0]['delta']['content']=fixture_text+(' Pending fragment' if responsive else ' One preserved sentence. Another preserved sentence. Pending fragment')
yield ('data: '+json.dumps(initial)+'\n\n').encode() yield ('data: '+json.dumps(initial)+'\n\n').encode()
try: try:
while not late_release.is_set(): while not late_release.is_set():
@@ -135,7 +136,7 @@ def start_components(key, timeout):
finally: finally:
if real: if real:
await transport.close_owned() await transport.close_owned()
guard = OwnedGateway(key, port=8766, transport=transport, timeout=timeout) guard = OwnedGateway(key, port=8766, transport=transport, timeout=timeout, responsive=responsive)
thread = Thread(target=guard.serve_forever, daemon=True) thread = Thread(target=guard.serve_forever, daemon=True)
thread.start() thread.start()
assert guard.ready.wait(3) assert guard.ready.wait(3)
@@ -317,7 +318,7 @@ worker.start()
key = Path('/secret/openrouter-test.key').read_text().strip() if real else 'offline-fixture-key' key = Path('/secret/openrouter-test.key').read_text().strip() if real else 'offline-fixture-key'
outcome = lifecycle.run_owned(build, key, timeout, emit=emit) outcome = lifecycle.run_owned(build, key, timeout, emit=emit)
worker.join(15) worker.join(15)
summary = dict(active_retention_verified=owned.get('active_retention_verified',False), retention_verified=owned.get('retention_verified',False), mode=mode, duplex=duplex, duplex_frames=owned.get('duplex_frames',0), lifecycle_outcome=outcome, client_done=client_done.is_set(), summary = dict(responsive=responsive, single_sentence_probe=responsive and retention_active, active_retention_verified=owned.get('active_retention_verified',False), retention_verified=owned.get('retention_verified',False), mode=mode, duplex=duplex, duplex_frames=owned.get('duplex_frames',0), lifecycle_outcome=outcome, client_done=client_done.is_set(),
client_error=owned.get('client_error'), events=dict(Counter(e['type'] for e in events)), client_error=owned.get('client_error'), events=dict(Counter(e['type'] for e in events)),
native_events=[{k:v for k,v in e.items() if k != 'delta'} if e['type'] == 'response.output_audio.delta' else e for e in events] if real else events, fixture_attempts=dict(Counter(calls)), native_events=[{k:v for k,v in e.items() if k != 'delta'} if e['type'] == 'response.output_audio.delta' else e for e in events] if real else events, fixture_attempts=dict(Counter(calls)),
fixture_llm_payloads=provider_payloads, fixture_llm_payloads=provider_payloads,
@@ -4,6 +4,7 @@ Persistent reservations include failed requests. Exactly two attempts per compon
cover construction probes and one turn. No retries or ledger reset are supported. cover construction probes and one turn. No retries or ledger reset are supported.
""" """
from decimal import Decimal from decimal import Decimal
import base64
from io import BytesIO from io import BytesIO
import json import json
from pathlib import Path from pathlib import Path
@@ -51,6 +52,16 @@ def validate_request(request):
request.url.scheme == 'https' and request.url.path in ( request.url.scheme == 'https' and request.url.path in (
'/api/v1/audio/speech', '/api/v1/audio/transcriptions', '/api/v1/chat/completions')) '/api/v1/audio/speech', '/api/v1/audio/transcriptions', '/api/v1/chat/completions'))
if stage == 'transcriptions': if stage == 'transcriptions':
if request.headers.get('content-type','').startswith('application/json'):
from app.modules.voice.local_s2s import RESPONSIVE_ASR_PROMPT
data=json.loads(request.content)
require(set(data)=={'model','language','response_format','temperature','input_audio','provider'} and
data['model']==MODELS[stage] and data['language']=='fa' and data['response_format']=='json' and
type(data['temperature']) is int and data['temperature']==0 and
data['provider']=={'options':{'groq':{'prompt':RESPONSIVE_ASR_PROMPT}}} and
set(data['input_audio'])=={'data','format'} and data['input_audio']['format']=='wav')
fields={'file':base64.b64decode(data['input_audio']['data'],validate=True)}
else:
message = BytesParser(policy=default).parsebytes( message = BytesParser(policy=default).parsebytes(
('Content-Type: '+request.headers['content-type']+'\r\nMIME-Version: 1.0\r\n\r\n').encode()+request.content) ('Content-Type: '+request.headers['content-type']+'\r\nMIME-Version: 1.0\r\n\r\n').encode()+request.content)
fields = {p.get_param('name', header='content-disposition'): p.get_payload(decode=True) fields = {p.get_param('name', header='content-disposition'): p.get_payload(decode=True)
@@ -14,6 +14,65 @@ previous=importlib.util.module_from_spec(spec);spec.loader.exec_module(previous)
class BrowserBudget(previous.BrowserBudget): class BrowserBudget(previous.BrowserBudget):
def __init__(self,root,*,upstream=None): def __init__(self,root,*,upstream=None):
previous.native.validate_prices(root) previous.native.validate_prices(root)
checkpoint=root/'carried-budget-preparation.json'
if checkpoint.exists():
# Migration from another host: documentary carry, never invented bills.
prior=json.loads(checkpoint.read_text())
previous.require(prior['prior_conservative_exposure_usd']=='0.704504399' and
prior['total_cap_usd']=='1' and prior['paid_calls_on_this_host']==0 and
prior['prior_private_ledgers_available'] is False and
prior['source']=='docs/evaluation/local-s2s/phase-04-interruption-incident.md' and
prior['status']=='preparation_only_not_a_live_admission_ledger' and
not (root/'previous-phase4-ledger.json').exists() and
not (root/'prior-final-billing.json').exists())
carried=Decimal(prior['prior_conservative_exposure_usd'])
self.maximum_attempts={'speech':4,'transcriptions':4,'completions':4}
runs_path=root/'previous-windows-runs.json'
old_ledger=root/'previous-windows-ledger.json'
old_billing=root/'previous-windows-billing.json'
previous.require(old_ledger.exists()==old_billing.exists())
if runs_path.exists():
previous.require(not old_ledger.exists())
runs=json.loads(runs_path.read_text())
previous.require(isinstance(runs,list) and 0<len(runs)<=16)
files=[]
for run in runs:
previous.require(set(run)=={'ledger','billing'} and
all(Path(run[key]).name==run[key] for key in run))
files.append((root/run['ledger'],root/run['billing']))
self.maximum_attempts={'speech':5,'transcriptions':4,'completions':4}
else:
files=[(old_ledger,old_billing)] if old_ledger.exists() else []
generation_ids=set()
for ledger_file,billing_file in files:
ledger=json.loads(ledger_file.read_text())
bills=json.loads(billing_file.read_text())
attempts=ledger['attempts']
previous.require(ledger['previous_reserved_and_billed_usd']==str(carried) and
0<len(attempts)==len(bills) and
len({row['generation_id'] for row in bills})==len(bills))
reserved=Decimal(0)
billed=Decimal(0)
for attempt in attempts:
stage=attempt['stage']
previous.require(stage in previous.RESERVES and
sum(row['stage']==stage for row in attempts)<=ledger.get('maximum_attempts',{}).get(stage,4))
reserve=Decimal(attempt['reserved_usd'])
previous.require(reserve==previous.RESERVES[stage] and
attempt['status']=='headers_received' and attempt['http_status']==200 and
attempt['generation_id'] not in generation_ids)
generation_ids.add(attempt['generation_id'])
matches=[row for row in bills if row['generation_id']==attempt['generation_id']]
previous.require(len(matches)==1)
bill=matches[0]
previous.require(bill['stage']==stage and bill['http_status']==200)
cost=Decimal(str(bill['billing']['total_cost']))
previous.require(cost.is_finite() and 0<=cost<=reserve)
reserved+=reserve
billed+=cost
previous.require(Decimal(ledger['reserved_usd'])==carried+reserved)
carried+=billed # Release only exact-ID, successful, individually billed attempts.
else:
report=json.loads((root/'prior-final-billing.json').read_text()) report=json.loads((root/'prior-final-billing.json').read_text())
reconciliation=report['reconciliation'] reconciliation=report['reconciliation']
previous.require(reconciliation['confirmed_cost_usd']=='0.003504399' and previous.require(reconciliation['confirmed_cost_usd']=='0.003504399' and
@@ -43,6 +102,7 @@ class BrowserBudget(previous.BrowserBudget):
self.state={'previous_reserved_and_billed_usd':str(carried),'reserved_usd':str(carried), self.state={'previous_reserved_and_billed_usd':str(carried),'reserved_usd':str(carried),
'maximum_cumulative_usd':str(maximum),'maximum_attempts':self.maximum_attempts, 'maximum_cumulative_usd':str(maximum),'maximum_attempts':self.maximum_attempts,
'unknown_prior_reservations_usd':'0.417','attempts':[], 'unknown_prior_reservations_usd':'0.417','attempts':[],
'carry_basis':('documentary_checkpoint_with_local_bills' if (root/'previous-windows-ledger.json').exists() or (root/'previous-windows-runs.json').exists() else 'documentary_checkpoint') if checkpoint.exists() else 'private_ledgers',
'purpose':'phase3_4_local_browser_only_no_openai_inference'} 'purpose':'phase3_4_local_browser_only_no_openai_inference'}
with self.path.open('x') as output:json.dump(self.state,output,indent=2) with self.path.open('x') as output:json.dump(self.state,output,indent=2)
self.upstream=upstream or httpx.AsyncHTTPTransport(retries=0,trust_env=False) self.upstream=upstream or httpx.AsyncHTTPTransport(retries=0,trust_env=False)
@@ -12,7 +12,8 @@ module=importlib.util.module_from_spec(spec)
spec.loader.exec_module(module) spec.loader.exec_module(module)
def start_components(key, timeout): def start_components(key, timeout, **options):
if os.environ.get('LOCAL_S2S_TTS_MODEL') == 'google/gemini-3.8-flash-lite-tts':
transport=module.BrowserBudget(Path('/evidence')) transport=module.BrowserBudget(Path('/evidence'))
class OwnedGateway(ComponentServer): class OwnedGateway(ComponentServer):
async def _run(self): async def _run(self):
@@ -20,7 +21,9 @@ def start_components(key, timeout):
await super()._run() await super()._run()
finally: finally:
await transport.close_owned() await transport.close_owned()
gateway=OwnedGateway(key,port=8766,transport=transport,timeout=timeout) gateway=OwnedGateway(key,port=8766,transport=transport,timeout=timeout,**options)
else:
gateway=ComponentServer(key,port=8766,timeout=timeout,**options)
thread=Thread(target=gateway.serve_forever,daemon=True) thread=Thread(target=gateway.serve_forever,daemon=True)
thread.start() thread.start()
if not gateway.ready.wait(5): if not gateway.ready.wait(5):
@@ -31,4 +34,6 @@ lifecycle.start_components=start_components
# The key is mounted only into this engine, never Compose environment/API/browser. # The key is mounted only into this engine, never Compose environment/API/browser.
import os import os
os.environ['OPENROUTER_API_KEY']=Path('/secret/openrouter-test.key').read_text().strip() os.environ['OPENROUTER_API_KEY']=Path('/secret/openrouter-test.key').read_text().strip()
if Path('/secret/openai-test.key').exists():
os.environ['OPENAI_API_KEY']=Path('/secret/openai-test.key').read_text().strip()
raise SystemExit(main()) raise SystemExit(main())
@@ -0,0 +1,104 @@
{
"date": "2026-10-17",
"status": "candidate_live_human_comparison_pending",
"image": "sha256:ddbb90366f19f8077b1cb40a77e529393459485fb8ae0cb9d074ffea641c265f",
"unit_tests": {
"passed": 157,
"seconds": 8.51
},
"postgres": {
"passed": 3,
"seconds": 6.72,
"skips": 0
},
"native_fixture": {
"responsive": true,
"single_sentence_probe": true,
"active_retention_verified": true,
"retention_verified": true,
"client_error": null,
"normal_complete": true,
"unit_released": true,
"paid_calls": 0,
"final_cleanup": {
"stage": "close",
"cleanup": {
"gateway_shutdown": 0,
"gateway_close": 0,
"runtime_stop": 0,
"gateway_join": 0,
"gateway_alive": 0
},
"request_counts": {
"accepted": 10,
"/v1/audio/transcriptions": 2,
"released": 10,
"/v1/chat/completions": 4,
"/v1/audio/speech": 4,
"disconnected": 2,
"shutdown_pending": 0
}
}
},
"native_single_sentence_seconds": 18.272,
"connection": {
"conversation_id": "c4ad0ece-e0e4-42fd-b9c3-63eaab1f5494",
"session_id": "2931f6df-176c-4f95-8bb3-55f2c4920312",
"events": [
"session_ready"
],
"providers": {
"default_provider": "local_s2s",
"connection_checked": false,
"providers": [
{
"id": "openai",
"label": "OpenAI",
"can_start": false,
"reason": "not_configured"
},
{
"id": "local_s2s",
"label": "\u0633\u06cc\u0633\u062a\u0645 \u062c\u062f\u06cc\u062f",
"can_start": true,
"reason": null
},
{
"id": "gemini",
"label": "Gemini",
"can_start": false,
"reason": "disabled"
}
]
},
"session_ready": true,
"close": {
"session_id": "2931f6df-176c-4f95-8bb3-55f2c4920312",
"status": "closed",
"close_reason": "user_requested"
},
"component_attempts_before": 3,
"component_attempts_after": 3
},
"watch": {
"stage": "ready",
"memory_enforcement": false,
"minimum_windows_available_bytes": 4080177152,
"minimum_vm_available_bytes": 4225368064,
"startup_seconds": 24.639
},
"budget": {
"previous_reserved_and_billed_usd": "0.710884452",
"reserved_usd": "0.769884452",
"maximum_cumulative_usd": "0.981884452",
"maximum_attempts": {
"speech": 5,
"transcriptions": 4,
"completions": 4
},
"carry_basis": "documentary_checkpoint_with_local_bills"
},
"nominal_expiry_tehran": "2026-10-17T11:01:18.153111+03:30",
"human_asr_improvement": "not_measured",
"human_latency_improvement": "not_measured"
}
@@ -0,0 +1,36 @@
# Isolated responsiveness candidate ? 2026-10-17
Status: **implemented and live for human comparison; ASR/latency improvement not accepted**. User requested fixes after two real short-utterance transcription errors and server speech-start-to-audio delays5.6?10.5s. This candidate does not claim those errors are resolved without new real audio.
## Changes
`LOCAL_S2S_RESPONSIVE=true` opts into a separate frozen local profile; defaultfalse preserves old profiles. The LLM emits each complete sentence instead of waiting for3. Actual initialized handler attestation checks the applied value, and the profile digest/patch revision `rag-local-s2s-responsive-v1` distinguish old reservations. No old execution profile is rewritten.
ASR uses temperature0 and a generic conversational Persian transcription hint; neither known test utterance is embedded and returned transcripts are not rewritten. Native setup applies settings before warmup. The gateway preserves exact WAV bytes while translating multipart into documented JSON `input_audio` and `provider.options.groq.prompt`; `fa` stays explicit. OpenRouter documents plain multipart `prompt` as accepted but ignored and documents provider-specific options here: [STT contract](https://openrouter.ai/docs/guides/overview/multimodal/stt). The hint applies only when Groq serves the request; other routes still receive explicit language and temperature. No unsupported latency routing preference is claimed.
The gateway records numeric component header/first-body times without text, audio or keys, to separate provider delay from pipeline delay. Existing HTTP PCM streaming is retained; `openai_tts_stream` remainsfalse because its upstream flag is not a general HTTP-streaming switch. PCM format, audio speed, playback/queue capacity, silence/padding settings, models/voices and retained-answer policy remain unchanged. Smaller sentence requests may increase TTS call counts; budget caps still apply.
## Validation
-157 focused unit tests passed in8.51s: wire bytes/options, applied policy/attestation, profile mismatch, cancellation/history, budget/supervisor and baseline behavior.
-3 PostgreSQL profile/replay/revocation tests passed in6.72s, zero skips, `--require-postgres` on a fresh dedicated tmpfs PostgreSQL. Owned container removed; operational and browser DB unchanged. Responsive and baseline reservations both pin original profiles on replay.
-COPY-only image `sha256:ddbb90366f19f8077b1cb40a77e529393459485fb8ae0cb9d074ffea641c265f`, verified parent `66aceba8e58a`; no dependencies downloaded/changed and private inputs excluded from context.
-Actual pinned native engine with real assets, networknone and fixture provider I/O passed. Final stricter18.272s run supplies only one complete sentence and holds generation open; audio arrives before completion, active cancellation/retained drafts/next generation and stale-output exclusion pass. Client error null; cleanup/pending zero, paid calls0. Controlled duration is not a Persian latency benchmark.
-Actual candidate startup24.639s; STT/LLM/TTS probes all200. Authenticated proxied session_ready and closed/user_requested pass; connection check did not increase inference count. This proves setup/probe compatibility, not human accuracy or quality.
-Initial local test runs exposed a Windows BOM decoding issue in the edited engine file and a missing RuntimeSettings argument in the new test; both corrected before the passing runs. No assertion weakened.
## Live handoff and budget
Browser http://127.0.0.2:4201/login, same private account/password and ?????? ?????. API and engine use the new image and responsive flag in the isolated stack. Memory prevention remains OFF per user; Docker3GiB/no-swap, deadlines and30minute expiry remain. Nominal expiry (Tehran): 2026-10-17T11:01:18.153111+03:30.
New exclusive directory `.local-s2s-build/windows-responsive-paid-01` carries both previous local ledgers and exact-ID receipts in order. All prior$0.710884452 exposure remains accounted. Current reserve **$0.769884452**, maximum **$0.981884452**, below the original$1 total. Limits:4 STT,4 LLM,5 TTS attempts including startup. Extra TTS allowance covers sentence splitting; no unrestricted OpenAI. Failed/unknown attempts keep reserves, partial or discontinuous billing chains fail closed, old ledgers remain unchanged. No automatic restart.
Human next: repeat the same short Persian utterances, listen to response onset and interrupt/request the same answer. Exact acoustic timing needs browser/capture measurements; server timing alone excludes the final audible-output path. Same-answer compliance and factual RAG remain pending. [Sanitized actual results](responsive-candidate-20261017.json).
## Human retest: latency still high, evaluation quota failure
User reports high latency persists and supplied browser error `LIVE_PROVIDER_UNAVAILABLE` for session e67dea1c-74bc-427e-8143-8187546e7cd3. Exact evaluation ledger denial: speech attempt_limit,5 admitted. Sentence splitting increased TTS calls; the sixth speech call was refused before provider I/O.13 admitted requests all returned200 (4STT,4LLM,5TTS); reserved exposure$0.981884452 held pending billing. This is an evaluation quota failure, not proof of provider outage or a successful repair. Engine stopped; UI/API remain available. No new inference during diagnosis.
Measured user-request component first-body delays: STT2046/1553/2058ms; LLM765/768/767ms; TTS2491/1578/2036/3741ms. These server timings exclude user speech and final browser audible onset. Sentence-at-a-time alone has not established acceptable end-to-end latency. Do not repeat this capped handoff or claim the latency fix accepted. Next funded evaluation must account for per-answer sentence/TTS calls before admitting generation, or use a deliberately bounded small scenario after exact bill reconciliation. Budget stays$1; memory prevention staysoff.
User explicitly asks to minimize coding quota consumption: keep follow-up investigation/changes narrowly targeted, avoid broad test/build/document churn.
@@ -0,0 +1,82 @@
"""One exclusive, bounded Windows browser handoff. Never restart its ledger."""
import argparse
import ctypes
import json
from pathlib import Path
import signal
import subprocess
import time
ROOT=Path(__file__).resolve().parents[3]
EVIDENCE=ROOT/'.local-s2s-build/windows-browser-paid'
REPORT=ROOT/'.local-s2s-build/windows-browser-watch.json'
COMPOSE=['docker','compose','--project-directory',str(ROOT),'--env-file',str(ROOT/'.local-s2s-build/windows-browser.env'),'-f',str(ROOT/'docs/evaluation/local-s2s/windows-browser.compose.yml')]
class Memory(ctypes.Structure):
_fields_=[('length',ctypes.c_ulong),('load',ctypes.c_ulong)]+[(name,ctypes.c_ulonglong) for name in ('total','available','page_total','page_available','virtual_total','virtual_available','extended')]
def available():
memory=Memory();memory.length=ctypes.sizeof(memory)
if not ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(memory)):raise OSError('Windows memory query failed')
return memory.available
def vm_available():
data=subprocess.check_output(COMPOSE+['exec','-T','candidate_db','cat','/proc/meminfo'],text=True,timeout=10)
return int(next(line.split()[1] for line in data.splitlines() if line.startswith('MemAvailable:')))*1024
def main(*, enforce_memory=False):
state={'stage':'preflight','memory_enforcement':enforce_memory,'minimum_windows_available_bytes':available(),'minimum_vm_available_bytes':vm_available()}
def save():REPORT.write_text(json.dumps(state,indent=2)+'\n',encoding='utf-8')
if (EVIDENCE/'browser-paid-ledger.json').exists():raise SystemExit('Exclusive ledger already exists; no restart allowed')
if enforce_memory:
# Admit using this host's measured native peak plus the floor and256MiB margin.
trial=json.loads((ROOT/'docs/evaluation/local-s2s/windows-native-retention-20261017.json').read_text())
observed=trial['supervisor']
if observed['exit_code']!=0 or observed['abort'] is not None:raise SystemExit('Missing successful native memory evidence')
required=2500*1024**2+(observed['start_windows_available_bytes']-observed['minimum_windows_available_bytes'])+256*1024**2
state['required_windows_start_bytes']=required
if state['minimum_windows_available_bytes']<required or state['minimum_vm_available_bytes']<=5*1024**3:
state.update(stage='blocked',reason='prestart_memory');save();raise SystemExit(1)
stop=False
def terminate(*args):
nonlocal stop
stop=True
for sig in (signal.SIGINT,signal.SIGTERM):signal.signal(sig,terminate)
began=time.monotonic();owned=False
try:
owned=True
subprocess.run(COMPOSE+['up','--pull','never','--no-deps','-d','local-s2s-engine'],check=True,timeout=40)
state['stage']='starting';save()
while not stop:
win=available();vm=vm_available()
state['minimum_windows_available_bytes']=min(win,state['minimum_windows_available_bytes'])
state['minimum_vm_available_bytes']=min(vm,state['minimum_vm_available_bytes'])
if enforce_memory and min(win,vm)<2500*1024**2:state['reason']='memory_floor';break
if time.monotonic()-began>1800:state['reason']='handoff_expired_30_minutes';break
status=subprocess.check_output(COMPOSE+['ps','--all','--format','json','local-s2s-engine'],text=True,timeout=10)
rows=[json.loads(line) for line in status.splitlines() if line.startswith('{')]
if rows and rows[0].get('State') not in ('running','created'):state['reason']='engine_exited';break
if state['stage']=='starting':
logs=subprocess.check_output(COMPOSE+['logs','--no-log-prefix','--tail','10','local-s2s-engine'],text=True,timeout=10)
if '"stage": "startup"' in logs:
state.update(stage='ready',startup_seconds=round(time.monotonic()-began,3));print('Browser engine ready',flush=True)
elif time.monotonic()-began>180:state['reason']='startup_deadline';break
save();time.sleep(2)
except BaseException as exc:
state['reason']=type(exc).__name__
raise
finally:
if owned:subprocess.run(COMPOSE+['stop','--timeout','5','local-s2s-engine'],timeout=15)
state.update(stage='stopped',elapsed_seconds=round(time.monotonic()-began,3));state.setdefault('reason','operator_stop');save()
if __name__=='__main__':
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--enforce-memory-floor',action='store_true',help='Opt in to host/VM memory admission and automatic low-memory stop')
parser.add_argument('--evidence',type=Path)
parser.add_argument('--report',type=Path)
parser.add_argument('--compose',type=Path)
args=parser.parse_args()
if args.evidence:EVIDENCE=args.evidence.resolve()
if args.report:REPORT=args.report.resolve()
if args.compose:COMPOSE[-1]=str(args.compose.resolve())
main(enforce_memory=args.enforce_memory_floor)
@@ -0,0 +1,61 @@
{
"date": "2026-10-17",
"status": "ready_for_human_test",
"memory_enforcement": false,
"budget": {
"previous_reserved_and_billed_usd": "0.704698199",
"reserved_usd": "0.763698199",
"maximum_cumulative_usd": "0.940698199",
"carry_basis": "documentary_checkpoint_with_local_bills"
},
"connection": {
"conversation_id": "a515ec75-1fb4-496d-879b-ed824df881e9",
"session_id": "991b5a14-07b6-4891-bd16-eebaeab35487",
"events": [
"session_ready"
],
"providers": {
"default_provider": "local_s2s",
"connection_checked": false,
"providers": [
{
"id": "openai",
"label": "OpenAI",
"can_start": false,
"reason": "not_configured"
},
{
"id": "local_s2s",
"label": "\u0633\u06cc\u0633\u062a\u0645 \u062c\u062f\u06cc\u062f",
"can_start": true,
"reason": null
},
{
"id": "gemini",
"label": "Gemini",
"can_start": false,
"reason": "disabled"
}
]
},
"session_ready": true,
"close": {
"session_id": "991b5a14-07b6-4891-bd16-eebaeab35487",
"status": "closed",
"close_reason": "user_requested"
},
"component_attempts_before": 3,
"component_attempts_after": 3
},
"watch": {
"stage": "ready",
"memory_enforcement": false,
"minimum_windows_available_bytes": 4233564160,
"minimum_vm_available_bytes": 4304089088,
"startup_seconds": 26.674
},
"nominal_expiry_tehran": "2026-10-17T10:40:19.606602+03:30",
"openai_comparison_ready": false,
"real_rag_ready": false,
"human_result": "pending"
}
@@ -0,0 +1,18 @@
# Second Windows browser handoff ? 2026-10-17
Status: **ready for human voice/interruption test; Phase3/4 not accepted**.
The user requested temporary disabling of memory prevention and an actual restart for testing. The engine is running with `memory_enforcement=false`; memory measurements alone no longer block/stop it. Docker3GiB/no-swap, startup/30minute deadlines and exclusive budget remain.
## Verified
-15 budget/supervisor tests passed in0.51s. Exact-ID billed carry replaces only the three verified old startup reservations with$0.0001938 actual costs, preserving the full$0.704504399 older exposure. Missing/mismatched/negative receipts fail closed; old live ledger is unchanged.
- New exclusive directory `.local-s2s-build/windows-browser-paid-02`; previous ledger and receipt copies retained. New baseline$0.704698199; three actual startup requests returned200; current conservative exposure$0.763698199; maximum$0.940698199 under the original$1 cap. At most three further admissions per component remain, not guaranteed complete turns.
- Engine startup26.674s; actual proxied login, selected local WebSocket `session_ready` and normal close passed. No audio sent; paid attempts remained3 before/after connection. API and static frontend are healthy. Existing account/password unchanged.
- Watcher now accepts evidence/report/compose paths for fresh exclusive runs; old defaults remain. [Sanitized actual handoff](windows-browser-handoff-02-20261017.json).
Browser http://127.0.0.2:4201/login; credentials `.local-s2s-build/windows-browser-login.txt`. Select ?????? ?????. First ask for a short three-sentence general answer; interrupt with a same-answer repeat, listen to its completion, then request a short continuation. Report audio/transcript behavior and exact errors. Keep prompts/answers short within the per-component caps. No document claims should be tested in this transport-only database.
Nominal expiry (Tehran): 2026-10-17T10:40:19.606602+03:30. Memory prevention remains off; time/budget/provider failures can still end a session. No automatic restart of this ledger.
Next gates: human microphone/interruption/repetition acceptance; approved factual corpus and bounded compatible embeddings/shared search; then bounded OpenAI admission, paired comparisons and restoration. Current fixture and connection successes close none of these acceptance gates.
@@ -0,0 +1,73 @@
{
"date": "2026-10-17",
"status": "ready_for_human_transport_interruption_test_not_phase_acceptance",
"browser_url": "http://127.0.0.2:4201/login",
"image": "sha256:66aceba8e58ad53e6a912352b4471f7bed5db8cd270f41901d1db6affd1240a1",
"connection": {
"conversation_id": "1ad9d329-7ca7-4280-a38f-3f12fc33c1d1",
"session_id": "5cad13f2-d1c0-486b-902f-0a1e2c74b868",
"events": [
"session_ready"
],
"providers": {
"default_provider": "local_s2s",
"connection_checked": false,
"providers": [
{
"id": "openai",
"label": "OpenAI",
"can_start": false,
"reason": "not_configured"
},
{
"id": "local_s2s",
"label": "\u0633\u06cc\u0633\u062a\u0645 \u062c\u062f\u06cc\u062f",
"can_start": true,
"reason": null
},
{
"id": "gemini",
"label": "Gemini",
"can_start": false,
"reason": "disabled"
}
]
},
"session_ready": true,
"close": {
"session_id": "5cad13f2-d1c0-486b-902f-0a1e2c74b868",
"status": "closed",
"close_reason": "user_requested"
},
"component_attempts_before": 3,
"component_attempts_after": 3
},
"budget": {
"previous_reserved_and_billed_usd": "0.704504399",
"reserved_usd": "0.763504399",
"maximum_cumulative_usd": "0.940504399",
"maximum_attempts": {
"speech": 4,
"transcriptions": 4,
"completions": 4
},
"carry_basis": "documentary_checkpoint"
},
"startup_http_statuses": [
200,
200,
200
],
"watch_at_handoff": {
"stage": "ready",
"minimum_windows_available_bytes": 3021164544,
"minimum_vm_available_bytes": 4236189696,
"required_windows_start_bytes": 3816460288,
"startup_seconds": 30.553
},
"watchdog_started_utc": "2026-10-17T06:06:40Z",
"nominal_expiry_tehran": "2026-10-17T10:06:40+03:30",
"rag_ready": false,
"openai_bounded_admission_ready": false,
"human_result": "pending"
}
@@ -0,0 +1,29 @@
# Windows browser handoff ? 2026-10-17
Status: **ready for human microphone/interruption checks; neither Phase3 nor Phase4 accepted**.
Browser: http://127.0.0.2:4201/login. Private account details are in `.local-s2s-build/windows-browser-login.txt`. Select ?????? ?????. This is an isolated voice transport environment; real document RAG and bounded OpenAI comparison are not ready.
## Actual evidence
- Separate project `rag-local-s2s-windows-test` owns a fresh PostgreSQL database, originals/extractions volumes and account; existing operational and prior test data unchanged. API8092 readiness200, new administrator bootstrap successful.
- Actual Angular source built in19.165s; Vite preview serves the generated bundle and proxies HTTP/WebSocket. Development server used553MiB; preview used64MiB at the observed sample. Existing frontend package.json changes preserved.
- Actual proxied login and metadata passed. Explicitly selected local session reached `session_ready`; close persisted `closed/user_requested`. No microphone data sent. Component attempts remained3 before/after the connection check.
- Three actual startup requests (STT/LLM/TTS) returned200. No manual retry/reset. Full documentary carry$0.704504399 retained; current reserved exposure$0.763504399; exclusive cumulative ceiling$0.940504399 below the original$1 cap. This is conservative exposure, not final invoicing. Four attempts per stage include startup, so at most three further admissions per stage remain; batching/failure/interruption may consume these earlier than three user turns.
- Key was available under existing legacy `API_KEY` with OpenRouter endpoint; copied privately to engine-only secret mount. API/browser receive neither it nor OpenAI inference keys. Preserved original profile remains private and unchanged. OpenAI metadata is `not_configured` in this test API until separate bounded admission exists.
- Watchdog uses the measured native Windows memory increase plus2500MiB runtime floor and256MiB margin for preflight (3,816,460,288 bytes), and >5GiB Docker VM availability. Both Windows and VM runtime floors remain2500MiB. Only its engine stops on low memory, startup failure or30minute expiry; no restart of the exclusive ledger is allowed. Nominal expiry **10:06:40 Tehran,2026-10-17**; memory/exit can end it earlier.
## Implementation and checks
The evaluation budget guard adds an explicit documentary carry mode. It validates the exact known checkpoint and rejects mixed private/documentary evidence; it does not fabricate historical requests or invoices. Existing private-ledger paths remain supported. Failures retain reservations; quota denial occurs before provider I/O. Guard code is mounted read-only into the candidate. The connection checker accepts optional account/ledger/report paths, retaining old defaults.
- Budget/history/evaluation/provider selection: **60 passed in9.14s**.
- Budget/supervisor checks: **10 passed in0.69s**, including six overlapping budget cases. They test exclusive-ledger rejection, changed-carry rejection, failure retention, low-memory no-launch and only-owned-engine shutdown on memory/expiry.
- Compose validation, Windows configuration-only no-inference run, real metadata validation in a disposable directory and final `git diff --check` passed.
- Actual startup and authenticated proxied native connection are real-provider evidence limited to the described checks. They do not establish human Persian quality, interrupted-answer compliance or factual correctness. [Sanitized handoff](windows-browser-handoff-20261017.json).
## Human action now required
Use short, non-document questions. Exercise interruption with a same-answer repeat and then a brief continuation, listening for stale audio/errors and retained answer behavior. Keep answers short because the budget has only three additional admissions per component. Report the exact error code if any. No phase closure from this handoff.
Approved corpus/factual annotations, compatible bounded embedding/search preparation, OpenAI admission, paired comparison and restoration remain pending. Do not enable unrestricted OpenAI or bypass calibration to call document retrieval ready. If this handoff expires, create a new carried ledger only after reconciliation; never rerun this ledger.
@@ -0,0 +1,24 @@
{
"date": "2026-10-17",
"cause": "watchdog_memory_floor_before_user_connections",
"watchdog": {
"stage": "stopped",
"minimum_windows_available_bytes": 2606247936,
"minimum_vm_available_bytes": 4236189696,
"required_windows_start_bytes": 3816460288,
"startup_seconds": 30.553,
"reason": "memory_floor",
"elapsed_seconds": 175.791
},
"failed_user_sessions": [
"a4a1f0b8-b5e0-4dcf-9707-6b177ef93a34",
"c542c2a6-81f9-486b-bc0a-18de0dec0453"
],
"api_error": "LIVE_SETUP_FAILED",
"api_exception": "gaierror",
"paid_attempts_after_user_connections": 3,
"new_billed_startup_usd": "0.0001938",
"prior_exposure_held_usd": "0.704504399",
"reconciled_conservative_exposure_usd": "0.704698199",
"human_voice_acceptance": "not_run_engine_unavailable"
}
@@ -0,0 +1,21 @@
# Windows browser startup failure ? 2026-10-17
The browser handoff is **no longer live**. The Windows watchdog stopped only its owned engine after175.791s with reason `memory_floor`; minimum Windows availability2,606,247,936 bytes, just below2500MiB. This was a guarded stop, not a proven OOM or interruption/history defect. The frontend/API stayed available.
The two user WebSocket attempts at06:29:54 and06:30:01 UTC occurred after that stop. API diagnostics show `stream_setup`, `gaierror`, `LIVE_SETUP_FAILED`; frontend close1011 corresponds to failed engine setup. Three login401s were followed by login200 and authenticated me/configuration/session requests; those login failures do not explain the later voice failures. Initial me401 before login is expected.
Engine logs show only the three startup requests and normal shutdown. Ledger still contains exactly three attempts; neither failed browser connection admitted inference. There is no microphone/barge-in quality result.
## Billing reconciliation
Read-only generation lookups for all three exact ledger IDs returned200. Actual costs: STT$0.0000075, LLM$0.0000228, TTS$0.0001635; total **$0.0001938**. The corresponding new$0.059 startup reserve can be replaced only in a new carry; the historical$0.704504399 remains held in full. Reconciled conservative exposure **$0.704698199**. Original exclusive ledger remains untouched and must not restart. Full billing receipts retained privately; [sanitized evidence](windows-browser-stop-20261017.json).
No new inference or engine restart was performed during diagnosis. The current host had3463MiB free after engine stop. Native fixture peak alone underestimated live handoff memory pressure; next admission must include the observed live decline and browser/UI headroom instead of silently reducing the runtime floor. Free memory with the actual browser open before another paid startup. A new carried-forward exclusive ledger is required; old documentary constructor currently accepts only its original checkpoint, so do not substitute the new exposure into it without implementing/verifying a billing-linked carry path.
Phase3/4 remain unaccepted. Next user dependency: free nonessential memory with the browser open; plan roughly4.5GiB available before another supervised trial. No unrelated process was terminated. The previous advertised handoff expiry was an upper bound; this earlier memory stop supersedes its ready state.
## User override: memory prevention disabled
The user explicitly requested disabling memory prevention temporarily. `watch-windows-browser.py` now defaults to observation only: neither Windows/VM pre-start thresholds nor the runtime2500MiB floor block or stop the engine. Memory samples are still recorded. `--enforce-memory-floor` explicitly restores both checks. The3GiB/no-swap Docker limit, exclusive-ledger rejection, budget admission, startup deadline and30minute expiry remain unchanged.
Validation:11 budget/supervisor tests passed in0.40s, including default low-memory launch continuing until the time limit and opt-in memory enforcement. No engine restart or paid call was made. The previously stopped engine remains stopped; any new paid launch still needs verified billing-linked carry. Earlier requests to free RAM are superseded by this explicit user override.
@@ -0,0 +1,206 @@
{
"name": "rag-local-s2s-windows-test",
"services": {
"candidate_db": {
"image": "pgvector/pgvector:pg16",
"environment": {
"POSTGRES_DB": "windows_local_s2s_test",
"POSTGRES_USER": "windows_s2s_test",
"POSTGRES_PASSWORD": "isolated-windows-only"
},
"volumes": [
"windows_postgres:/var/lib/postgresql/data"
],
"healthcheck": {
"test": [
"CMD-SHELL",
"pg_isready -U windows_s2s_test -d windows_local_s2s_test"
],
"interval": "3s",
"timeout": "3s",
"retries": 20
},
"mem_limit": "512m",
"memswap_limit": "512m"
},
"candidate_migrations": {
"image": "sha256:66aceba8e58ad53e6a912352b4471f7bed5db8cd270f41901d1db6affd1240a1",
"environment": {
"PROVIDER": "local_s2s",
"VOICE_PROVIDER": "local_s2s",
"VOICE_SELECTABLE_PROVIDERS": "[\"openai\",\"local_s2s\"]",
"LOCAL_S2S_ENABLED": "true",
"LOCAL_S2S_RETAIN_INTERRUPTED_ANSWERS": "true",
"VOICE_TRANSPORT_TESTING": "true",
"LOCAL_S2S_ENDPOINT": "ws://local-s2s-engine:8765/v1/realtime",
"LOCAL_S2S_TOKEN": "${LOCAL_S2S_TOKEN:?Private test token required}",
"LOCAL_S2S_STT_MODEL": "openai/whisper-large-v3",
"LOCAL_S2S_LLM_MODEL": "openai/gpt-4.1-mini",
"LOCAL_S2S_TTS_MODEL": "gpt-4o-mini-tts-2025-12-15",
"LOCAL_S2S_TTS_VOICE": "alloy",
"LOCAL_S2S_MAX_OUTPUT_TOKENS": "128",
"LOCAL_S2S_REQUEST_TIMEOUT_SECONDS": "30",
"LIVE_SESSION_SECONDS": "60",
"LIVE_DIAGNOSTIC_TRACE_ENABLED": "1",
"MAX_PROVIDER_SESSIONS": "1",
"TRUSTED_ORIGINS": "[\"http://127.0.0.2:4201\",\"http://127.0.0.2:8092\"]",
"TRUSTED_HOSTS": "[\"127.0.0.2:4201\",\"127.0.0.2:8092\"]",
"COOKIE_SECURE": "false",
"OPENAI_API_KEY": "",
"OPENAI_REALTIME_API_KEY": "",
"INGEST_DATABASE_URL": "postgresql+psycopg://windows_s2s_test:isolated-windows-only@candidate_db:5432/windows_local_s2s_test",
"INGEST_ORIGINAL_DIRECTORY": "/app/data/local-s2s-test/originals",
"INGEST_EXTRACTION_DIRECTORY": "/app/data/local-s2s-test/extractions",
"INGEST_EMBEDDING_PROVIDER": "openai",
"INGEST_EMBEDDING_ENDPOINT": "http://127.0.0.1:9/v1",
"INGEST_EMBEDDING_MODEL": "text-embedding-3-small",
"INGEST_EMBEDDING_DIMENSIONS": "1536",
"INGEST_EMBEDDING_API_KEY": "transport-no-inference",
"INGEST_EMBEDDING_LIMITS": "{\"unit\":\"utf8_bytes\",\"max_input_units\":4096,\"max_batch_units\":4096,\"max_batch_inputs\":1}"
},
"command": [
"alembic",
"upgrade",
"head"
],
"volumes": [
"./.local-s2s-build/windows-empty.env:/app/.env:ro"
],
"depends_on": {
"candidate_db": {
"condition": "service_healthy"
}
},
"mem_limit": "512m",
"memswap_limit": "512m"
},
"candidate_api": {
"image": "sha256:66aceba8e58ad53e6a912352b4471f7bed5db8cd270f41901d1db6affd1240a1",
"environment": {
"PROVIDER": "local_s2s",
"VOICE_PROVIDER": "local_s2s",
"VOICE_SELECTABLE_PROVIDERS": "[\"openai\",\"local_s2s\"]",
"LOCAL_S2S_ENABLED": "true",
"LOCAL_S2S_RETAIN_INTERRUPTED_ANSWERS": "true",
"VOICE_TRANSPORT_TESTING": "true",
"LOCAL_S2S_ENDPOINT": "ws://local-s2s-engine:8765/v1/realtime",
"LOCAL_S2S_TOKEN": "${LOCAL_S2S_TOKEN:?Private test token required}",
"LOCAL_S2S_STT_MODEL": "openai/whisper-large-v3",
"LOCAL_S2S_LLM_MODEL": "openai/gpt-4.1-mini",
"LOCAL_S2S_TTS_MODEL": "gpt-4o-mini-tts-2025-12-15",
"LOCAL_S2S_TTS_VOICE": "alloy",
"LOCAL_S2S_MAX_OUTPUT_TOKENS": "128",
"LOCAL_S2S_REQUEST_TIMEOUT_SECONDS": "30",
"LIVE_SESSION_SECONDS": "60",
"LIVE_DIAGNOSTIC_TRACE_ENABLED": "1",
"MAX_PROVIDER_SESSIONS": "1",
"TRUSTED_ORIGINS": "[\"http://127.0.0.2:4201\",\"http://127.0.0.2:8092\"]",
"TRUSTED_HOSTS": "[\"127.0.0.2:4201\",\"127.0.0.2:8092\"]",
"COOKIE_SECURE": "false",
"OPENAI_API_KEY": "",
"OPENAI_REALTIME_API_KEY": "",
"INGEST_DATABASE_URL": "postgresql+psycopg://windows_s2s_test:isolated-windows-only@candidate_db:5432/windows_local_s2s_test",
"INGEST_ORIGINAL_DIRECTORY": "/app/data/local-s2s-test/originals",
"INGEST_EXTRACTION_DIRECTORY": "/app/data/local-s2s-test/extractions",
"INGEST_EMBEDDING_PROVIDER": "openai",
"INGEST_EMBEDDING_ENDPOINT": "http://127.0.0.1:9/v1",
"INGEST_EMBEDDING_MODEL": "text-embedding-3-small",
"INGEST_EMBEDDING_DIMENSIONS": "1536",
"INGEST_EMBEDDING_API_KEY": "transport-no-inference",
"INGEST_EMBEDDING_LIMITS": "{\"unit\":\"utf8_bytes\",\"max_input_units\":4096,\"max_batch_units\":4096,\"max_batch_inputs\":1}"
},
"command": [
"python",
"-m",
"app.server",
"--host",
"0.0.0.0",
"--port",
"8000"
],
"volumes": [
"./.local-s2s-build/windows-empty.env:/app/.env:ro",
"windows_originals:/app/data/local-s2s-test/originals",
"windows_extractions:/app/data/local-s2s-test/extractions"
],
"ports": [
"127.0.0.2:8092:8000"
],
"depends_on": {
"candidate_migrations": {
"condition": "service_completed_successfully"
}
},
"mem_limit": "768m",
"memswap_limit": "768m"
},
"local-s2s-engine": {
"image": "sha256:66aceba8e58ad53e6a912352b4471f7bed5db8cd270f41901d1db6affd1240a1",
"entrypoint": [
"python",
"/checks/phase4-browser-engine.py"
],
"command": [
"--allow-paid-startup"
],
"environment": {
"LOCAL_S2S_ENABLED": "true",
"LOCAL_S2S_RETAIN_INTERRUPTED_ANSWERS": "true",
"LOCAL_S2S_ENDPOINT": "ws://local-s2s-engine:8765/v1/realtime",
"LOCAL_S2S_TOKEN": "${LOCAL_S2S_TOKEN:?Private test token required}",
"LOCAL_S2S_STT_MODEL": "openai/whisper-large-v3",
"LOCAL_S2S_LLM_MODEL": "openai/gpt-4.1-mini",
"LOCAL_S2S_TTS_MODEL": "gpt-4o-mini-tts-2025-12-15",
"LOCAL_S2S_TTS_VOICE": "alloy",
"LOCAL_S2S_MAX_OUTPUT_TOKENS": "128",
"LOCAL_S2S_REQUEST_TIMEOUT_SECONDS": "30",
"LOCAL_S2S_ALLOW_PAID_STARTUP": "true",
"OPENROUTER_API_KEY": "",
"LOCAL_S2S_SILERO_SOURCE": "/vad/silero-vad",
"LOCAL_S2S_NLTK_DATA": "/assets/nltk",
"LOCAL_S2S_ASSET_MANIFEST": "/assets/assets.json",
"LOCAL_S2S_ASSET_MANIFEST_SHA256": "869eb6be1f444ecded8908b9339078cc5845df367207a63ed28173c4974dca26",
"OMP_NUM_THREADS": "1",
"OPENBLAS_NUM_THREADS": "1",
"PYTHONPATH": "/app",
"PROVIDER": "local_s2s",
"VOICE_PROVIDER": "local_s2s",
"VOICE_TRANSPORT_TESTING": "true"
},
"volumes": [
"./.local-s2s-build/windows-empty.env:/app/.env:ro",
"./.local-s2s-build/windows-openrouter-test.key:/secret/openrouter-test.key:ro",
"./.local-s2s-build/windows-openai-test.key:/secret/openai-test.key:ro",
"./.local-s2s-build/windows-browser-paid:/evidence:rw",
"./.local-s2s-build/assets-linux/nltk:/assets/nltk:ro",
"./.local-s2s-build/assets-linux/vad:/vad/silero-vad:ro",
"./.local-s2s-build/windows-continuation-20261017/assets-lf.json:/assets/assets.json:ro",
"./services/local_s2s/components.py:/app/services/local_s2s/components.py:ro",
"./docs/evaluation/local-s2s/phase4-browser-engine.py:/checks/phase4-browser-engine.py:ro",
"./docs/evaluation/local-s2s/phase4-browser-budget.py:/checks/phase4-browser-budget.py:ro",
"./docs/evaluation/local-s2s/browser-budget.py:/checks/browser-budget.py:ro",
"./docs/evaluation/local-s2s/native-budget-transport.py:/checks/native-budget-transport.py:ro"
],
"read_only": true,
"cap_drop": [
"ALL"
],
"security_opt": [
"no-new-privileges:true"
],
"tmpfs": [
"/tmp:rw,noexec,nosuid,size=64m"
],
"mem_limit": "3g",
"memswap_limit": "3g",
"cpus": 2,
"pids_limit": 128,
"restart": "no"
}
},
"volumes": {
"windows_postgres": {},
"windows_originals": {},
"windows_extractions": {}
}
}
@@ -0,0 +1,47 @@
# Windows continuation preparation — 2026-10-17
Status: isolated candidate image rebuilt; supervised native retention fixture passed; paid/browser preparation pending; Phase 3 and Phase 4 live acceptance remain pending.
The user confirmed that previous real tests ran on another computer and authorized continuation on this Windows host. Previous private ledgers and native candidate images are not present here. Existing test PostgreSQL/original/extraction volumes remain available and have not been reset. Docker Desktop was started; existing unrelated restart-policy containers started automatically and were left unchanged.
## Recovered inputs
- Clean upstream pin `619e3fe4f71d1c6f35c15870d588a3638de34722`, acquired in `tmp/local-s2s-upstream-619e3fe4`; all 17 recorded SHA-256 fingerprints match after disabling Git archive CRLF conversion.
- Reviewed 134-package Linux CPU lock copied unchanged into `.local-s2s-build/requirements.lock`; original pinned Python base retained.
- All 14 NLTK/Silero asset fingerprints match the existing Linux asset manifest, under `.local-s2s-build/assets-linux`. The Silero directory in this reconstruction is `vad`, not `silero-vad`; mounts must use the actual path.
- Existing Angular checkout `D:/raymand/projects/faq_chatbot_frontend` contains provider selection at commit `a26c597`. Its existing package.json modification was preserved.
- Build succeeded: `rag-local-s2s-candidate:windows-rebuild-20261017`, image ID `sha256:66aceba8e58ad53e6a912352b4471f7bed5db8cd270f41901d1db6affd1240a1`. Original base/lock were retained; native validation remains unrun. A Dockerfile warning about the unset default base ARG remains; the build supplied the explicit pinned base.
## Budget
Carry the full conservative exposure **$0.704504399** from `phase-04-interruption-incident.md`; no release based on missing invoices. Remaining headroom before new reservations is **$0.295495601**, within the original **$1** authorization. This is a documentary carry, not recovered per-request billing evidence or a functioning inference admission ledger.
Public endpoint metadata for all three component models was refreshed without inference. Existing `native-budget-transport.py` price validation passed. Private preparation evidence is `.local-s2s-build/windows-continuation-20261017/`. Do not fabricate old attempt rows to satisfy an old ledger constructor, reset old ledgers, or enable unguarded OpenAI. A fresh exclusive admission ledger must explicitly support this documentary carry before paid startup.
## Checks and remaining gates
- `.venv/Scripts/python -m pytest -q -p no:cacheprovider tests/unit/test_local_s2s_history.py tests/unit/test_local_s2s_evaluation.py tests/unit/test_phase2_provider_selection.py`: **54 passed in 9.63s**.
- `git diff --check`: passed before this report.
- No new paid provider request, engine startup, audio tuning or operational provider switch.
- Windows available physical RAM fell below 1GiB during dependency download; Linux VM MemAvailable alone is insufficient evidence of Windows host headroom. Do not start the native engine until host and VM memory admission is satisfied. Original Linux runners use `/proc/meminfo` and require a Windows-compatible supervisor before reuse here.
- Native fixture validation, bounded cost admission, Windows-specific Compose mounts/images, browser authentication/handoff, approved RAG corpus and bounded embeddings, paired provider measurements and actual restoration remain pending. Existing Linux overrides reference unavailable image digests and `/dev/null`; do not launch them unchanged on this host.
## Completed image check
`docker run --rm --pull never --network none --read-only --memory 128m --memory-swap 128m --pids-limit 64 --cap-drop ALL --security-opt no-new-privileges --entrypoint python rag-local-s2s-candidate:windows-rebuild-20261017 -m pip check`: exit 0, `No broken requirements found.` No key mounted and no engine initialized.
Final Windows physical memory available: **393MiB**; native/paid/browser startup was not attempted. User was asked to free nonessential applications. Build and asset downloads are complete and retained. No unrelated process or container was stopped.
## Supervised native retention run with 4.8GB reported RAM
The user authorized testing after freeing memory. Actual preflight: Windows 5,038,092,288 bytes available, Docker VM 6,191,755,264 bytes. One controlled Windows trial admitted at >=4500MiB Windows / >5GiB VM, with the original 3GiB/no-swap container limit, 2 CPUs, network disabled and no provider key. The supervisor sampled both memory domains and stopped only its owned container if either fell below2500MiB or180s elapsed. This trial does not change existing launch defaults or establish a universal minimum.
**Passed in35.555s, exit0**, no memory abort. Minimum available: Windows4,111,507,456 bytes; VM4,471,754,752 bytes. Active cancellation, two retained-history receipts, next generation, stale-output exclusion, intent correlation, normal completion and unit release passed. Client error null; all cleanup errors/pending requests zero; paid calls zero. See [sanitized result](windows-native-retention-20261017.json). No actual browser, Persian quality or original transient error acceptance follows from fixture I/O.
The Windows checkout's mounted asset manifest has CRLF bytes; its LF-normalized digest matches the historical869eb6be1f444ecded8908b9339078cc5845df367207a63ed28173c4974dca26. A normalized private copy was prepared as `windows-continuation-20261017/assets-lf.json` for later pinned live startup; tracked manifest unchanged. All14 asset payload hashes matched before execution.
Next: a fresh exclusive inference budget guard supporting documentary carry (without fabricated old attempts), Windows Compose/profiles and browser handoff. No paid inference is enabled by this native success; OpenAI admission and real RAG preparation remain pending.
## Later browser preparation
Superseded for readiness by [actual browser handoff](windows-browser-handoff-20261017.md): startup and authenticated proxied connection passed, current reserve$0.763504399. Human microphone/interruption and Phase3/4 acceptance remain pending. Earlier missing-key and preparation-only statements describe their historical checkpoint.
@@ -0,0 +1,67 @@
{
"date": "2026-10-17",
"session_id": "bcc45066-2ddc-4182-8a48-043a571d2194",
"user_confirmed_intentional_speech_interruptions": 2,
"user_confirmed_no_stale_audio": true,
"subsequent_turn_completed": true,
"last_played_ms": 14336,
"generation_active_cancellation": "not_exercised_both_responses_completed_before_playback_interruption",
"same_answer_repeat": "not_tested",
"asr_accuracy": "two_user_confirmed_short_utterance_errors",
"rag": "not_tested",
"phase3": "in_progress",
"phase4": "pending",
"new_billed_usd": "0.006186253",
"prior_exposure_held_usd": "0.704698199",
"reconciled_conservative_exposure_usd": "0.710884452",
"trace": [
"2026-10-17 06:41:58 [INFO] [app.modules.voice.diagnostics] Voice trace session=bcc45066-2ddc-4182-8a48-043a571d2194 stage=terminal_processed turn=live-turn-1 audio=none state=backlog_bytes=298512 elapsed_ms=10256 lock_wait_ms=0 peak_backlog_bytes=298512 terminal_cancelled=0 terminal_completed=1 terminal_limited=0",
"2026-10-17 06:41:59 [INFO] [app.modules.voice.diagnostics] Voice trace session=bcc45066-2ddc-4182-8a48-043a571d2194 stage=audio_discard_interruption turn=live-turn-1 audio=live-audio-50ca3096e62349d9b685614f10593b78 state=backlog_bytes=202272 credit_bytes=72000 discarded_bytes=130272 elapsed_ms=11878 generated_bytes=322560 peak_backlog_bytes=298512 played_ms=2506 queued_bytes=130272 reserved_bytes=0 sent_bytes=192288",
"2026-10-17 06:41:59 [INFO] [app.modules.voice.diagnostics] Voice trace session=bcc45066-2ddc-4182-8a48-043a571d2194 stage=turn_interrupted_sent turn=live-turn-1 audio=none state=authority_ms=0 backlog_bytes=72000 elapsed_ms=11888 emit_ms=9 peak_backlog_bytes=298512 queued_controls=1",
"2026-10-17 06:42:00 [INFO] [app.modules.voice.diagnostics] Voice trace session=bcc45066-2ddc-4182-8a48-043a571d2194 stage=truncate_acknowledged turn=live-turn-1 audio=live-audio-50ca3096e62349d9b685614f10593b78 state=backlog_bytes=67392 credit_bytes=67392 elapsed_ms=12900 generated_bytes=322560 peak_backlog_bytes=298512 played_ms=2602 queued_bytes=0 reserved_bytes=0 sent_bytes=192288",
"2026-10-17 06:42:05 [INFO] [app.modules.voice.diagnostics] Voice trace session=bcc45066-2ddc-4182-8a48-043a571d2194 stage=terminal_processed turn=live-turn-2 audio=none state=backlog_bytes=313632 elapsed_ms=17926 lock_wait_ms=0 peak_backlog_bytes=313632 terminal_cancelled=0 terminal_completed=1 terminal_limited=0",
"2026-10-17 06:42:10 [INFO] [app.modules.voice.diagnostics] Voice trace session=bcc45066-2ddc-4182-8a48-043a571d2194 stage=audio_discard_interruption turn=live-turn-2 audio=live-audio-f023853c650f4b0d8a363321863cde31 state=backlog_bytes=97056 credit_bytes=72000 discarded_bytes=25056 elapsed_ms=22300 generated_bytes=325632 peak_backlog_bytes=313632 played_ms=4762 queued_bytes=25056 reserved_bytes=0 sent_bytes=300576",
"2026-10-17 06:42:10 [INFO] [app.modules.voice.diagnostics] Voice trace session=bcc45066-2ddc-4182-8a48-043a571d2194 stage=turn_interrupted_sent turn=live-turn-2 audio=none state=authority_ms=0 backlog_bytes=72000 elapsed_ms=22306 emit_ms=5 peak_backlog_bytes=313632 queued_controls=1",
"2026-10-17 06:42:11 [INFO] [app.modules.voice.diagnostics] Voice trace session=bcc45066-2ddc-4182-8a48-043a571d2194 stage=truncate_acknowledged turn=live-turn-2 audio=live-audio-f023853c650f4b0d8a363321863cde31 state=backlog_bytes=68160 credit_bytes=68160 elapsed_ms=23309 generated_bytes=325632 peak_backlog_bytes=313632 played_ms=4842 queued_bytes=0 reserved_bytes=0 sent_bytes=300576",
"2026-10-17 06:42:22 [INFO] [app.modules.voice.diagnostics] Voice trace session=bcc45066-2ddc-4182-8a48-043a571d2194 stage=terminal_processed turn=live-turn-3 audio=none state=backlog_bytes=627984 elapsed_ms=34142 lock_wait_ms=0 peak_backlog_bytes=635394 terminal_cancelled=0 terminal_completed=1 terminal_limited=0",
"2026-10-17 06:42:33 [INFO] [app.modules.voice.diagnostics] Voice trace session=bcc45066-2ddc-4182-8a48-043a571d2194 stage=audio_ended_sent turn=live-turn-3 audio=none state=authority_ms=7 backlog_bytes=62496 elapsed_ms=45903 emit_ms=0 peak_backlog_bytes=635394 queued_controls=0"
],
"engine": "stopped_after_attempt_caps_reached",
"asr_observations": [
{
"intended": "?? ????",
"reported_transcript": "?????"
},
{
"intended": "?? ??? ???????",
"reported_transcript": "?? ??? ??? ????"
}
],
"latency": [
{
"turn": 1,
"speech_start_to_audio_started_ms": 7704,
"user_transcript_to_audio_started_ms": 4128,
"assistant_first_transcript_to_audio_started_ms": 2319,
"stt_headers_seconds": 2.36,
"tts_headers_seconds": 2.287
},
{
"turn": 2,
"speech_start_to_audio_started_ms": 5552,
"user_transcript_to_audio_started_ms": 3378,
"assistant_first_transcript_to_audio_started_ms": 2386,
"stt_headers_seconds": 1.472,
"tts_headers_seconds": 2.332
},
{
"turn": 3,
"speech_start_to_audio_started_ms": 10531,
"user_transcript_to_audio_started_ms": 4518,
"assistant_first_transcript_to_audio_started_ms": 3404,
"stt_headers_seconds": 5.119,
"tts_headers_seconds": 3.358
}
],
"latency_limits": "Server event timings, not browser audible onset; start-to-audio includes user speech and endpointing. Transcript roles inferred from native event ordering; trace does not log roles."
}
@@ -0,0 +1,25 @@
# Windows real browser interruption ? 2026-10-17
Status: **intentional playback interruption and continuation passed; Phase3/4 remain open**.
The user spoke over two assistant answers and explicitly confirmed both cuts were intentional and no old audio returned. Actual API trace for session `bcc45066-2ddc-4182-8a48-043a571d2194` records two playback discards, two interruption events and two matching context-repair acknowledgements. Each underlying response had already completed generation before the interruption; this is real completed-but-unplayed interruption evidence, not real active-generation cancellation evidence. Third response completed and playback reached14336ms. Normal close HTTP200; no session diagnostic error was found.
The transcript alone does not prove that a same-answer repetition was requested or preserved correctly. User ASR strings include malformed Persian; intended original utterances/audio are required before attributing or scoring errors. No spoken-original facts were invented and no pronunciation/model change was made.
All four admissions per STT/LLM/TTS were consumed (one startup and three user turns),12 total, all HTTP200. The completed engine was stopped to avoid another quota-denied session; API/frontend remain available. No budget increase, ledger reuse or audio tuning change. Memory prevention remains disabled per user.
Exact-ID lookup returned12 successful billing receipts: **$0.006186253** new actual cost. Prior exposure$0.704698199 remains held. Reconciled conservative exposure **$0.710884452**, leaving$0.289115548 before new reservations under the same$1 cap. Original live ledger is unchanged; this reconciliation belongs in the next exclusive carry. Private receipt file `.local-s2s-build/windows-browser-billing-02.json`. [Sanitized evidence](windows-live-interruption-20261017.json).
Remaining: clarify intended ASR utterances; real same-answer repeat and active-generation cancellation; approved corpus, bounded compatible embeddings/shared RAG, factual/source cases; bounded OpenAI comparison and restoration. Do not close either phase from this partial success.
## User-confirmed ASR and latency defects
The user confirmed intended utterances were ??? ????? and ??? ??? ????????; reported transcripts were malformed. These are now confirmed short-utterance transcription errors, not unscored guesses. Original audio was not retained for phonetic scoring.
Server speech-start to audio-started:7.704s,5.552s,10.531s. These include the user's speaking time and endpointing, not just model latency. First assistant transcript to audio-started:2.319s,2.386s,3.404s. User-transcript to audio-started:4.128s,3.378s,4.518s. Transcript roles are inferred from the native user/assistant-delta/assistant-done sequence; current trace records only event type. Browser audible onset was not measured.
Actual per-request upstream header timing: STT2.360/1.472/5.119s; TTS2.287/2.332/3.358s; LLM1.360/0.697/0.685s. First native audio receipt to browser audio-start event was14/19/13ms. Most of the observed text-to-first-audio gap aligns with upstream TTS response wait. Provider/model inference time versus networking cannot be separated by header timing alone. No evidence supports attributing these seconds to the frontend playback buffer.
Current configured STT is non-realtime Persian transcription; sequential STT/LLM/TTS stages add waits. Upstream default sentence batching is3; its contribution was not independently measured. `openai_tts_stream=false` is not evidence of fully buffered HTTP audio: the pinned handler already uses HTTP streaming/aiter_bytes, so flipping that flag blindly is not an established fix.
Latency and short-utterance ASR remain open acceptance defects. No speed/buffer/model change, image restart or paid request was made during this diagnosis. Next repair/evaluation should isolate endpointing/STT and upstream TTS first-audio delay with stage-level timing, preserving interruption/history and budget controls.
@@ -0,0 +1,68 @@
{
"date": "2026-10-17",
"scope": "actual native engine, fixture providers; no browser or human acceptance",
"image": "sha256:66aceba8e58ad53e6a912352b4471f7bed5db8cd270f41901d1db6affd1240a1",
"supervisor": {
"mode": "normal_retention_active",
"paid_calls": 0,
"external_network": "none",
"start_windows_available_bytes": 5038092288,
"start_vm_available_bytes": 6191755264,
"abort": null,
"exit_code": 0,
"elapsed_seconds": 35.555,
"minimum_windows_available_bytes": 4111507456,
"minimum_vm_available_bytes": 4471754752
},
"result": {
"active_retention_verified": true,
"retention_verified": true,
"client_error": null,
"normal_complete": true,
"unit_released": true,
"fixture_cancelled": true,
"mismatch_rejected": true,
"intent_correlated": true,
"runtime_state": "stopped",
"paid_calls": 0,
"events": {
"session.created": 1,
"session.updated": 3,
"input_audio_buffer.speech_started": 1,
"input_audio_buffer.speech_stopped": 1,
"input_audio_buffer.committed": 1,
"conversation.item.created": 1,
"conversation.item.input_audio_transcription.completed": 1,
"response.created": 3,
"response.output_item.added": 3,
"response.content_part.added": 3,
"response.output_audio_transcript.delta": 3,
"response.output_audio.delta": 7,
"response.output_audio.done": 3,
"response.output_audio_transcript.done": 3,
"response.content_part.done": 3,
"response.output_item.done": 3,
"response.done": 3,
"s2s.history.retained": 2
},
"final_cleanup": {
"stage": "close",
"cleanup": {
"gateway_shutdown": 0,
"gateway_close": 0,
"runtime_stop": 0,
"gateway_join": 0,
"gateway_alive": 0
},
"request_counts": {
"accepted": 10,
"/v1/audio/transcriptions": 2,
"released": 10,
"/v1/chat/completions": 4,
"/v1/audio/speech": 4,
"shutdown_pending": 0
}
}
},
"stdout_sha256": "cccca7b80b93822825e2be7482869b6809109100a1b12cb8e42ea2337e5ddfd5"
}
+111
View File
@@ -0,0 +1,111 @@
# Local Windows stack: consolidated handoff
Last recorded activation: 2026-10-18. Documentation reconciled: 2026-10-20.
This is the isolated Windows development stack, not an operational deployment.
No startup or paid call was performed while writing this guide.
## Routing and required profile
Set the following consistently for the API and engine's frozen profile:
~~~dotenv
VOICE_PROVIDER=local_s2s
LOCAL_S2S_ENABLED=true
LOCAL_S2S_COMPONENT_PROVIDER=gapgpt
LOCAL_S2S_STT_PROVIDER=elevenlabs
LOCAL_S2S_STT_MODEL=scribe_v2
LOCAL_S2S_LLM_MODEL=gpt-4.1-mini
LOCAL_S2S_TTS_PROVIDER=elevenlabs
LOCAL_S2S_TTS_MODEL=eleven_v3
LOCAL_S2S_TTS_VOICE=JBFqnCBsd6RMkjVDRZzb
LOCAL_S2S_TTS_SPEED=1.2
LOCAL_S2S_REQUEST_TIMEOUT_SECONDS=60
LOCAL_S2S_STRICT_GROUNDING=true
~~~
These settings describe the final recorded override, not defaults in
.env.example or docker-compose.local-s2s-test.yml. The tracked standalone Compose
starts with a non-inference embedding endpoint for transport fixtures and is not
a replacement for this host's RAG-enabled Compose. Preserve candidate isolation
guards, real frozen embedding identity, engine token and matching attestation.
Only the engine reads /run/secrets/gapgpt_api_key and
/run/secrets/elevenlabs_api_key. Host files are ignored
.local-s2s-build/gapgpt-api.key and .local-s2s-build/elevenlabs-api.key.
Never copy their contents into docs, source, frontend or Git. STT/TTS use native
ElevenLabs endpoints; only dialogue uses GapGPT. No automatic fallback is provided.
TTS explicitly requests mono 16-bit PCM at 24 kHz; ElevenLabs speed must be 0.7–1.2.
Strict grounding buffers completion output before TTS and validates current-turn,
reported, successfully retrieved/revalidated evidence. Unsupported prose becomes
a fixed abstention. Whole-chunk retrieval is bounded to ten sources/12,000
characters; preserve a calibration report matching whole-10-12000.
## Host prerequisites and startup
The existing stack uses isolated database rag_bge_local_s2s_test, durable original
and extraction volumes, host Ollama and the sibling Angular production build.
Its embedding identity is http://localhost:11434/v1. A namespace-sharing stdlib
TCP relay forwards this identity to host Ollama; do not rewrite frozen metadata
to host.docker.internal. Preserve documents, selection and embedding profiles.
Required ignored host artifacts include windows-gapgpt.compose.json,
gapgpt-compose.py, the provider key files, current calibration/engine assets,
preview configuration and test login file. Inspect their presence locally.
Do not print credentials. If these files are absent on a fresh checkout,
reconstruct the host configuration using the
[backend operations guide](phase4-backend-operations.md), tracked standalone
candidate Compose and [engine guide](../../services/local_s2s/README.md).
A portable recreation of the host wrapper is not present in Git.
With the previously provisioned artifacts, the recorded commands are:
~~~powershell
.venv/Scripts/python .local-s2s-build/gapgpt-compose.py up -d
.venv/Scripts/python .local-s2s-build/gapgpt-compose.py ps
.venv/Scripts/python .local-s2s-build/check-gapgpt.py
.venv/Scripts/python .local-s2s-build/check-lan.py
~~~
Starting/recreating the engine can issue real component warmups. Confirm the
applicable provider budget before running these commands; old exclusive ledgers
are historical records, not reusable authorization. Do not launch a worker against
an unrelated queue. Apply alembic upgrade head to the intended isolated database
before API startup; current Live head is 0006_voice_model_settings.
## Frontend, HTTPS and recovery
Loopback preview: http://127.0.0.2:4201/login, proxying API 127.0.0.2:8092.
LAN preview: https://192.168.180.151:4201/login, with same-origin API/WSS.
The sibling source is D:/raymand/projects/faq_chatbot_frontend.
Its build/test commands are npm.cmd run build and npm.cmd test -- --watch=false.
LAN configuration is ignored .local-s2s-build/lan-preview.config.mjs.
The firewall rule RAG-Local-LAN-HTTPS-4201 is restricted to LocalSubnet.
Each physical client needs the public development CA trusted and browser
microphone permission. The generated certificate lasts 30 days; check validity
before reuse. A changed IP requires certificate SAN, binding and trusted
origin/host updates. Restore the public CA copy after frontend rebuild if needed.
Never publish the private server key. See [LAN setup](local-lan-access-20261018.md).
Check /health/ready, authenticated document listing and knowledge selection,
F01 public provider/model inventory, then WSS session_ready and normal close.
A ready API is not evidence that embeddings are reachable from inside containers.
Use a new voice conversation after profile changes. On failure, inspect numeric
diagnostics without exposing provider keys or source bodies.
For recreation, retain database and original/extraction volumes; do not use
down -v or reset the embedding identity. Restore the exact compatible profile
and image/configuration, migrate forward and repeat readiness/connection checks.
A rollback to older runtime code must account for its schema-head requirements;
downgrading the database is not the documented recovery path.
## Validation boundaries
See [current status](../current-status.md) and the dated
[provider activation](local-gapgpt-20261018.md),
[source import](server-source-sync-20261018.md) and
[grounding](strict-grounding-20261018.md) evidence.
The latest profile still needs human microphone/spoken-RAG/interruption tests and
a second-client LAN check. Existing warmups, synthetic audio and host-local WSS
checks do not close those gates.
+195
View File
@@ -0,0 +1,195 @@
Current reading note (2026-10-20): the final recorded configuration is in
[the consolidated local runbook](current-local-stack.md). The initial all-GapGPT
activation and intermediate Gemini/TTS-only changes below are historical;
the final profile uses ElevenLabs STT/TTS and GapGPT dialogue only.
No new runtime verification was performed for this reading note.
# Local S2S through GapGPT — 2026-10-18
User-authorized local activation only. The Debian deployment was not contacted
or modified during this activation. All three Local S2S components now use
https://api.gapgpt.app/v1 in the local test stack:
- STT: whisper-1, Persian, final JSON transcription.
- LLM: gpt-4.1-mini, streaming Chat Completions and existing backend tools.
- TTS: gpt-4o-mini-tts, alloy, PCM 24kHz, existing speed 1.6.
## Configuration and routing
LOCAL_S2S_COMPONENT_PROVIDER=gapgpt must be set on both the API and engine.
The split default preserves existing deployments. The selected upstream is part
of frozen components/profile identity; switching it cannot silently reuse an old
session attestation. Actual initialized engine metadata is checked against it.
GapGPT routes never fall back to OpenAI or OpenRouter on error. Multipart STT,
streaming chat/tools, response bounds, deadlines and cancellation remain intact.
Only the engine reads GAPGPT_API_KEY or GAPGPT_API_KEY_FILE. The active local
stack mounts ignored .local-s2s-build/gapgpt-api.key read-only at
/run/secrets/gapgpt_api_key. The key is not embedded in source, image, API,
frontend or Compose environment. The fixed provider endpoint does not accept a
model-supplied destination. No additional package or migration was introduced.
Embedding remains local bge-m3 and document OCR remains its existing provider;
these are separate from the three speech pipeline components authorized here.
Existing documents, selection, embedding metadata and calibrated cutoff are
preserved. The local test UI exposes only Local S2S for this activation.
## Local run
Runtime uses image rag-local-gapgpt:20261018, built on the existing engine image
with the current app and services/local_s2s sources. The existing isolated
rag_bge_local_s2s_test database and original/extraction volumes are reused.
Start/check from the repository root:
.venv/Scripts/python .local-s2s-build/gapgpt-compose.py up -d
.venv/Scripts/python .local-s2s-build/gapgpt-compose.py ps
.venv/Scripts/python .local-s2s-build/check-gapgpt.py
Compose: .local-s2s-build/windows-gapgpt.compose.json. Runtime files are ignored
and contain host-specific paths; credentials are in the separate key file only.
Frontend preview is running at http://127.0.0.2:4201/login and proxies the local
API at 127.0.0.2:8092. It serves the current sibling Angular production build.
The existing test login is in .local-s2s-build/windows-browser-login.txt.
Preview config/PID/logs use the .local-s2s-build/gapgpt-preview prefix.
The migrated embedding identity pins http://localhost:11434/v1. A first startup
attempt using host.docker.internal correctly failed compatibility validation;
no profile or migrated metadata was rewritten. A local Python stdlib TCP relay
now shares the API/worker network namespace and forwards that same loopback
address to the host's Ollama. The relay has no provider key and no exposed
embedding port. The migration then succeeded and the API became ready.
## Actual verification
141 focused provider-free tests passed before the final added upstream-error
parameter cases. The earlier real feasibility checks verified streaming tool
arguments, PCM audio generation and the same audio transcribed as Persian
'سلام'. Native engine startup then made exactly three successful component
warmup requests, each logged with provider=gapgpt and status 200.
GET /health/ready returned 200 with ingestion available. The actual frontend
proxy login, allowed-provider inventory, public model catalog and WebSocket
session_ready/normal close passed. Evidence is retained in ignored
.local-s2s-build/combined-evidence/gapgpt-connection-20261018.json.
Human microphone quality, interruption and complete spoken RAG acceptance await
the user's browser test. These are not established by startup or mock tests.
Final focused command:
.venv/Scripts/python -m pytest tests/unit/test_local_s2s_gapgpt.py tests/unit/test_local_s2s_engine.py tests/unit/test_local_s2s_responsiveness.py tests/unit/test_local_s2s_boundary.py tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_repairs.py -m "not postgres" -q
Result: **144 passed**. Includes all three GapGPT routes with both successful
upstream responses and upstream 429 rejection, exactly one outbound attempt,
no fallback/credential mixing, profile mismatch rejection and prior-path coverage.
`git diff --check` passed. No tracked or pending source file contains the key.
The actual API container reached host Ollama through the loopback relay:
HTTP 200, 1024-dimensional bge-m3 output. Authenticated proxied document listing
returned HTTP 200 with four visible active documents; knowledge selection also
returned 200. No original content or selection was changed by these checks.
## Active Gemini TTS follow-up — 2026-10-18
User selected gemini-2.5-flash-preview-tts. The current local TTS model is now
that exact model, voice Kore. STT and LLM retain whisper-1 and gpt-4.1-mini.
The earlier gpt-4o-mini-tts activation above is historical.
GapGPT /audio/speech returned 503 channel:protocol_unsupported for Gemini TTS,
with and without speed. The native Gemini-style v1/models generateContent route
returned a successful response with empty audio parts. Actual usable audio was
verified through /v1/chat/completions with modalities=[audio], audio.voice=Kore,
audio.format=pcm16 and stream=false. The TTS gateway now uses that route only for
this exact model in GapGPT mode, validates the successful single-choice audio
envelope, bounds base64/decoded size, and passes PCM to the existing native TTS
handler. Valid mono 24kHz 16-bit WAV envelopes are unwrapped when present;
incompatible or empty/partial audio is rejected. No provider fallback exists.
Desired pace 1.6 is conveyed in the Gemini read-aloud instruction; unlike the
previous model's speed parameter this is not a measured guarantee of exact pace.
GapGPT's upstream inactivity wait now uses the configured total request deadline;
the old split-provider default remains 5 seconds. The current isolated local
profile uses 60 seconds (the existing validated maximum), preserving bounded
cancellation and no automatic retries. This removes the premature 5-second
cutoff observed in the user's STT/TTS logs. It does not guarantee the provider
will always reply within the total deadline.
Final focused suite: 152 passed (same six local_s2s test modules as above).
Actual native startup succeeded with all three component warmups: Gemini TTS
returned status 200, 48,526 PCM bytes, approximately 3.16 seconds for that one
request. Frontend-proxied session_ready and normal close passed again; F01
reports the requested Gemini TTS model. API/worker/engine were recreated locally
with the current sources. The server was not modified. Browser remains at
http://127.0.0.2:4201/login; refresh and start a new voice conversation.
## Active ElevenLabs TTS follow-up — 2026-10-18
User replaced Gemini TTS with ElevenLabs for the local test only. Current settings:
LOCAL_S2S_COMPONENT_PROVIDER=gapgpt, LOCAL_S2S_TTS_PROVIDER=elevenlabs,
LOCAL_S2S_TTS_MODEL=eleven_v3, LOCAL_S2S_TTS_VOICE=JBFqnCBsd6RMkjVDRZzb
(George), LOCAL_S2S_TTS_SPEED=1.2. STT and LLM remain whisper-1 and
gpt-4.1-mini through GapGPT. The previous Gemini TTS activation is historical.
A tiny actual Persian synthesis request returned HTTP 200, audio/pcm,
107,520 bytes (2.24 seconds at 24kHz mono 16-bit), in about 3.51 seconds.
The request explicitly selects output_format=pcm_24000 on ElevenLabs' native
text-to-speech endpoint. No MP3 decoding or sample-rate inference is used.
The API format contract is documented at
https://elevenlabs.io/docs/api-reference/text-to-speech/convert and
https://elevenlabs.io/docs/help-center/troubleshooting/what-audio-formats-do-you-support.
Human Persian listening/quality acceptance remains pending.
The supplied key permits synthesis but denies models_read, voices_read and
user_read; discovery endpoints returned missing_permissions. No extra permission
is needed to run the successful synthesis request using the documented George
voice. No key/account permission was changed.
Only the engine mounts ignored .local-s2s-build/elevenlabs-api.key at
/run/secrets/elevenlabs_api_key. The gateway uses xi-api-key for ElevenLabs only,
never forwards the GapGPT bearer key there, and never falls back to Gemini or
other providers. TTS provider/model/voice/speed are frozen in session identity.
Provider/model changes require a new voice conversation. Existing packet,
backlog, cancellation and total timeout limits remain in place. Speed outside
0.7–1.2 is rejected for ElevenLabs instead of silently clamped.
159 focused provider-free tests passed, including successful native TTS mapping,
401/429 with no fallback, credential separation, PCM 24kHz request parameters,
attestation mismatch and speed/credential validation. One new test fixture
initially omitted its handler speed; it was supplied to match runtime setup.
No runtime assertion was weakened. The API, worker and engine image were rebuilt
and restarted locally. Server deployment was not contacted or modified.
## Active ElevenLabs STT follow-up — 2026-10-18
The user also moved STT to ElevenLabs. The active local profile now uses
LOCAL_S2S_STT_PROVIDER=elevenlabs and LOCAL_S2S_STT_MODEL=scribe_v2.
TTS remains ElevenLabs eleven_v3/George at speed 1.2 with PCM 24000Hz.
Only the dialogue LLM remains gpt-4.1-mini through GapGPT.
A small Persian synthetic audio round trip succeeded with the existing key:
Scribe v2 returned 'سلام. خوش آمدید', language fas, HTTP 200, in about 1.07
seconds for that sample. The key does not require extra permissions for this
successful speech-to-text request.
The engine gateway maps its existing OpenAI-compatible multipart transport to
POST https://api.elevenlabs.io/v1/speech-to-text. Audio bytes are preserved;
model becomes model_id=scribe_v2, language_code=fa, event tagging/diarization
are disabled and timestamps_granularity=none. Whisper response_format, prompt
and temperature are not sent to ElevenLabs. The frozen STT profile no longer
claims those Whisper-specific settings for this route; sentence-at-a-time LLM
handling remains enabled. The final JSON text response uses the existing native
handler path. No second search implementation, migration or package was added.
STT provider is included in session identity and verified against engine setup.
The existing engine-only ElevenLabs key file is shared by STT/TTS; GapGPT
credentials are not forwarded to ElevenLabs. Authentication/rate failures do not
fall back to GapGPT or OpenAI. Existing total request bounds/cancellation remain.
164 focused tests passed across test_local_s2s_elevenlabs, gapgpt, engine,
responsiveness, boundary, phase2 and repairs. New coverage verifies multipart
field translation, original audio preservation, no credential mixing or fallback,
provider attestation, invalid duplicate fields and omitted Whisper-only policy.
Native engine warmup succeeded with STT ElevenLabs HTTP 200 (~0.97s), LLM
GapGPT HTTP 200 and TTS ElevenLabs HTTP 200. These are individual measurements,
not latency guarantees or human Persian-quality acceptance. No server changed.
+55
View File
@@ -0,0 +1,55 @@
# Local LAN access — 2026-10-18
User requested access to the local test service from the internal network.
Active URL: https://192.168.180.151:4201/login (Ethernet IPv4 on this computer).
The existing http://127.0.0.2:4201/login loopback preview remains available.
The Debian deployment was not contacted or modified.
A separate Vite HTTPS preview binds only 192.168.180.151:4201 and serves the
current sibling frontend production build. Same-origin /api HTTP and WSS proxy
to the existing loopback-only API at 127.0.0.2:8092. The API trusted origins/hosts
now explicitly include this LAN HTTPS origin/authority. No wildcard origin was
introduced. The engine, database and API ports were not exposed to the LAN.
The Windows inbound rule RAG-Local-LAN-HTTPS-4201 allows TCP 4201 only on local
address 192.168.180.151 with remote address LocalSubnet. Direct creation initially
failed without Administrator rights. The known local script was run via UAC;
a process-only PowerShell execution-policy exception was required. No persistent
PowerShell policy or global firewall setting was changed. The result file
.local-s2s-build/lan-firewall-result.json confirms the rule exists and is enabled.
## Client certificate setup
The local development CA and server certificate expire after 30 days. Private
server key stays in ignored .local-s2s-build/lan-tls/server.key and is outside the
served frontend directory. Only the public CA certificate is downloadable:
https://192.168.180.151:4201/local-dev-ca.cer
On the second Windows computer, install this public development CA for Current
User in Trusted Root Certification Authorities, then restart/reload the browser.
For the initial download the browser can display an untrusted-certificate page
because this local CA is not yet trusted. Confirm the address is this LAN host.
For microphone use, HTTPS must be trusted on that client and microphone access
must be granted. No certificate was silently installed in any device trust store.
Other operating systems require their own local-CA trust setup.
The application uses the existing test account. No account/password was changed.
## Verification and runtime files
Strict TLS verification with the generated CA succeeded for the login page and
CA download (both HTTP 200). Existing loopback page also returned 200.
Authenticated login, provider/model catalog and actual WSS session_ready plus
normal close succeeded through the LAN HTTPS origin. Evidence is in ignored
.local-s2s-build/combined-evidence/lan-connection-20261018.json.
The check was from this host; a separate physical client remains to be verified.
No new paid component initialization was needed; only the local API was recreated.
Configuration: .local-s2s-build/lan-preview.config.mjs.
PID/stdout/stderr: .local-s2s-build/lan-preview.*.
API Compose: .local-s2s-build/windows-gapgpt.compose.json.
Validation command: .venv/Scripts/python .local-s2s-build/check-lan.py.
The public CA copy in the Angular dist directory must be restored after a rebuild
if it is still needed for client installation. The LAN IP is the current address;
a different IP requires updating binding, certificate SAN and trusted origins.
+3 -1
View File
@@ -1,3 +1,5 @@
Current local profile: see [consolidated Windows runbook](current-local-stack.md) and [current status](../current-status.md). The temporary Gemini selection and fixture results below describe their dated checkpoint. Current Live schema head is 0006_voice_model_settings; apply forward migrations before startup.
# Phase 4 backend startup and recovery # Phase 4 backend startup and recovery
This guide describes the modular document/voice backend. The older prototype This guide describes the modular document/voice backend. The older prototype
@@ -99,7 +101,7 @@ python -m app.worker
Password commands prompt securely; automation can use `--password-stdin` from a Password commands prompt securely; automation can use `--password-stdin` from a
secure pipe. Bootstrap is only for a new installation and refuses to reset an secure pipe. Bootstrap is only for a new installation and refuses to reset an
existing organization. Never downgrade or edit applied migrations 0001–0005. existing organization. Never downgrade or edit applied migrations 0001–0006.
Existing production Compose starts migrations before one API and the separate Existing production Compose starts migrations before one API and the separate
worker, with shared durable original/extraction directories. Build with worker, with shared durable original/extraction directories. Build with
@@ -0,0 +1,89 @@
# Deployed source import — 2026-10-18
User scope: import the server's stronger S2S logging, document deletion and model
settings into the existing local backend and sibling Angular source tree.
## Provenance
All seven imported runtime Python sources matched SHA-256 hashes read from the
running API and S2S engine containers. Release directories are not assumed to
represent the live code without that comparison. No deployed service was changed.
Server environment files, provider keys, data and host-specific Compose settings
were excluded from the import.
Backend files: `app/api/v1/documents.py`, `app/modules/documents/deletion.py`,
`app/api/v1/knowledge.py`, `app/modules/voice/model_catalog.py`,
`app/modules/voice/runtime.py`, `app/modules/voice/diagnostics.py`,
`services/local_s2s/components.py`. The supplied deletion regression suite was
imported as `tests/integration/test_document_deletion.py`.
Angular source: `D:/raymand/projects/faq_chatbot_frontend/src/`, from the final
server deletion release (which includes the preceding model settings changes).
Only six differing existing files and one new test were transferred; 100 source
files were already identical after line-ending normalization. Changed files:
`app/pages/settings/settings.page.ts`, `settings.page.html`,
`settings.live.spec.ts`, `app/services/documents/documents.service.ts`,
`documents.types.ts`, `app/services/http-request/http.service.ts`, and
`app/shared/ui/ai-model-config-card/ai-model-config-card.component.ts`.
Previous frontend files are backed up under ignored
`temp/server-sync-20261018/frontend-before/`.
Deletion retains original content/chunks, removes search eligibility, increments
revision/epoch when removing active knowledge, fences worker publication and
invalidates older conversations/sessions. It does not physically purge content.
Model settings display deployment-owned identifiers and reuse existing Live
provider selection. Provider secrets remain on the backend.
## Validation
Validation is recorded below after completion. No real provider inference or
browser microphone acceptance is implied by mock/provider-free tests.
Initial focused run: 157 passed, 3 failed. The three failures in
`test_voice_search_interruption.py::test_profile_cancellation_diagnostics` also
reproduce with the original `HEAD` runtime loaded in memory (3 failed, 1 passed).
They are pre-existing expectations around cancellation diagnostic profile flags
and the coral cancellation policy; assertions and policy were not changed.
`npm.cmd run build`: passed (one CommonJS warning for existing moment-jalaali).
PowerShell blocks npm.ps1 on this host; npm.cmd runs the same installed tool.
Final focused backend command:
`.venv/Scripts/python -m pytest tests/unit/test_server_source_sync.py tests/unit/test_local_s2s_responsiveness.py tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_repairs.py tests/unit/test_voice_session_incident.py -m "not postgres" -q`
Result: **146 passed**. Covers public model-role gating, secret suppression,
component completion trace fields, existing S2S lifecycle and incident behavior.
PostgreSQL command (TEST_DATABASE_URL pointing only at the disposable
`rag_sync_20261018_test` database on localhost:55439):
`.venv/Scripts/python -m pytest tests/integration/test_document_deletion.py -m postgres --require-postgres -q`
Result: **7 passed**, no skips. Active/inactive deletion, recorded replay and
changed-payload conflict, stale revision, organization/role authorization,
concurrent replay, worker fencing, authenticated HTTP/CSRF all passed.
The `rag-sync-20261018-postgres` container used --rm with no persistent volume and
was stopped/removed afterward. Local Docker Desktop was started for these tests;
its existing configured containers also resumed automatically. No server-side
service was restarted or modified.
Frontend commands, from `D:/raymand/projects/faq_chatbot_frontend`:
- `npm.cmd run build`: passed.
- `npm.cmd test -- --watch=false --include=src/app/pages/settings/*.spec.ts --include=src/app/services/documents/*.spec.ts`: **20 passed** across three files.
The first frontend test run found two test integration defects: the imported Live
spec lacked zoneless configuration, and the existing deletion test expected the
old unsupported-action notice with no delete mock. Both were updated for the
intentional feature activation. Added HTTP DELETE body/credentials/CSRF/key
coverage and ambiguous-failure retry identity coverage. Runtime frontend sources
remain identical to the supplied final source release; only tests were adapted.
Two further frontend test files changed during validation:
`app/pages/settings/settings.page.spec.ts` and
`app/services/documents/documents.service.spec.ts`.
Provenance limit: the server's currently selected `frontend-dist` index loads
`main-RIHA5TKM.js`, whereas the final source release includes
`main-FK3BDLSA.js`. Thus the frontend import is attributed to the final release
source artifact, not claimed as a reconstruction verified against the currently
served minified bundle. The backend source matches were verified against running
containers. No remote bundle or deployment setting was replaced.
No full-suite, production deletion, browser microphone or real-provider inference
claim is made. The three baseline cancellation-test failures remain open.
+36
View File
@@ -0,0 +1,36 @@
# User-authorized grounding correction (2026-10-18)
Scope: stop unsupported voice answers and send up to ten retrieved passages. The reported incorrect hours and offered appointment coordination were not supported by the supplied evidence. The earlier phone case had its supporting FAQ at rank eight and only five sources reached the model.
## Behavior
Shared retrieval now admits up to ten whole chunks within the existing 12,000-character evidence budget; eligibility, document identities, access scope, exact matching and embeddings are unchanged. Fewer than ten may be returned because of cutoff or the text budget. Retrieval policy identity changes to `whole-10-12000`.
The common voice instruction requires current-turn evidence for every factual claim, ignores source-order authority, forbids invented hours/prices/current open status and unsupported action promises, and requires extractive answers. It distinguishes static documented hours from current day/time/holiday status.
For the local engine, `LOCAL_S2S_STRICT_GROUNDING=true` activates a gateway gate before assistant text can reach TTS. It accepts answer text only when it is a contiguous excerpt of evidence reported and successfully retrieved/revalidated after the most recent user message, or one of a few fixed nonfactual greetings/clarifications/abstention messages. FAQ question premises are excluded. If there is exactly one cited FAQ with a bounded answer, a generated paraphrase is replaced by that FAQ answer verbatim. Otherwise unsupported output is replaced by a fixed Persian abstention. Tool calls pass through; accompanying unverified assistant prose is removed. Previous assistant prose and previous turns cannot supply evidence. This gate is local-engine-specific; common instructions also affect other voice adapters.
Chat completion responses are bounded and buffered before forwarding, including SSE, so partial hallucinated sentences cannot reach TTS before validation. This adds waiting until completion and restricts paraphrasing/multi-passage synthesis. It prevents newly generated wording from passing the gate, but does not establish truth of the uploaded text or semantic relevance of every literal excerpt.
## Validation
108 focused provider-free tests passed, covering ten-source admission, the former rank-eight phone case, prompt propagation, numeric/hour/appointment rejection, prior-turn and unreported-source rejection, and streamed tool-call preservation.
The old synthetic calibration report was re-evaluated, then replaced locally by a fresh measured calibration against the active uploaded FAQ and actual current eligible corpus. Six source-bound support cases (phone, CEO contact procedure, hours, land pricing conditions, address and IT extension) and four out-of-domain negative cases produced 6/6 complete support and 0/4 unsupported retrieval positives, at measured cosine cutoff 0.5498457982262681. These are calibration observations, not held-out quality acceptance. Original report and diagnostic reanalysis remain in ignored local evidence files. No document was re-embedded or modified.
A real-provider prompt-only trial still produced unsupported claims, which motivated the deterministic gate. Do not present prompt instructions alone as a guarantee. Local evidence: `production-ten-calibration.json`, `grounded-provider-answers.json` under ignored `.local-s2s-build/combined-evidence`.
Final live-provider gateway checks used the actual retrieved passages and current GapGPT `gpt-4.1-mini`, with normal tool reporting. Phone: returned literal `031 - 3125`; CEO: returned the literal documented contact procedure; current open/closed status and land total price: refused unsupported generated output with the fixed insufficient-evidence message. These checks verify Chat Completions/gateway output, not a human microphone/TTS quality acceptance. Actual backend/engine WebSocket admission also returned `session_ready` and closed normally. Extractive refusal may reject a valid paraphrase or a multi-source answer; this is the deliberate strict mode tradeoff requested here.
### Search-query normalization (reconciled 2026-10-20)
The shared SearchInput validator strips recognized Persian forms of the Isfahan
industrial-parks organization name from a longer query, trims adjacent leading
or trailing prepositions and collapses whitespace. A removal is retained only
when at least three characters remain; an organization-only query is preserved.
This reduces repeated organization-name expansion in entity/contact searches.
It changes retrieval query text, not authenticated organization scope, document
eligibility or the optional context field. The tool description also asks the
model not to append the organization name. This code path is separate from the
extractive output gate and does not establish measured relevance improvement.
+23
View File
@@ -1,3 +1,26 @@
# Current checklist reconciliation — 2026-10-20
The checklist below is the historical 2026-10-08 snapshot. Its unchecked runtime
items are superseded where implemented in the [current status](../current-status.md).
This separation preserves the distinction between implementation and acceptance.
- [x] Modular authenticated API and separate worker; uploaded-document search.
- [x] Backend upload/status, retained review/resume, retry and active selection.
- [x] Owned voice sessions, backend WSS, trusted tool dispatch and profile pinning.
- [x] D05 soft deletion, F01 public model inventory and permitted provider selection.
- [x] Local GapGPT dialogue plus ElevenLabs STT/TTS and strict extractive gate.
- [x] Schema head 0006 and consolidated local startup dependencies documented.
- [ ] Human acceptance of the final ElevenLabs/strict-grounding profile.
- [ ] Second physical LAN client with trusted HTTPS and microphone.
- [ ] Held-out Persian RAG quality and bounded paired-provider evaluation.
- [ ] Resolve/revalidate the three documented cancellation-diagnostic baseline failures.
- [ ] Full MVP acceptance and operational promotion; component checks do not prove these.
Use [current evidence and limitations](../current-status.md) for dated results.
General settings/model editing and full text history remain deferred.
---
# Live document MVP TODO # Live document MVP TODO
Updated 2026-10-08 against the revision 1.3 specifications and scoped-search repair review. Updated 2026-10-08 against the revision 1.3 specifications and scoped-search repair review.
+17
View File
@@ -1,3 +1,20 @@
# Latest reconciliation — 2026-10-20
The last recorded local activation (2026-10-18) uses ElevenLabs scribe_v2 STT,
GapGPT gpt-4.1-mini dialogue and ElevenLabs eleven_v3/George TTS at speed 1.2,
with a 60-second request deadline and strict current-turn extractive grounding.
Retrieval admits ten whole chunks within 12,000 characters.
See [current status](../current-status.md) and the
[consolidated runbook](../guides/current-local-stack.md).
The 2026-10-17 [combined evidence](../evaluation/local-s2s/combined-ready-20261017.md)
and 2026-10-18 activation reports supersede earlier preparation-only statements.
Human acceptance of the final profile, paired evaluation and operational
promotion remain open. Earlier budgets/stopped/running statements below apply
only to their dated runs; do not restart an old exclusive ledger.
---
## 2026-10-16 — interruption incident follow-up ## 2026-10-16 — interruption incident follow-up
[Evidence and scoped budget-denial repair](../evaluation/local-s2s/phase-04-interruption-incident.md): 100 focused checks passed; actual native active cancellation/retained history/next response passed offline,71.037s, zero paid calls. Browser transient error code remains unavailable; do not claim full incident or human acceptance. Exhausted engine and test API/frontend stopped. Old ledger remains exclusive; reserve$0.704504399 held. No tuning changes. [Evidence and scoped budget-denial repair](../evaluation/local-s2s/phase-04-interruption-incident.md): 100 focused checks passed; actual native active cancellation/retained history/next response passed offline,71.037s, zero paid calls. Browser transient error code remains unavailable; do not claim full incident or human acceptance. Exhausted engine and test API/frontend stopped. Old ledger remains exclusive; reserve$0.704504399 held. No tuning changes.
+26 -3
View File
@@ -43,7 +43,7 @@ Proposed field limits: deferred text message 8000 characters; assistant name 120
| D02 | GET `/documents` | Admin | 200 | MVP | | D02 | GET `/documents` | Admin | 200 | MVP |
| D03 | GET `/documents/{document_id}` | Admin | 200 | MVP | | D03 | GET `/documents/{document_id}` | Admin | 200 | MVP |
| D04 | POST `/documents/{document_id}/retry` | Admin | 202 | MVP | | D04 | POST `/documents/{document_id}/retry` | Admin | 202 | MVP |
| D05 | DELETE `/documents/{document_id}?expected_revision=N` | Admin | 202 | Deferred | | D05 | DELETE `/documents/{document_id}` | Admin | 202 | User-authorized server import (2026-10-18) |
| D06 | GET `/documents/{document_id}/extraction-review` | Admin | 200 | MVP | | D06 | GET `/documents/{document_id}/extraction-review` | Admin | 200 | MVP |
| D07 | POST `/documents/{document_id}/extraction-review/decisions` | Admin | 200 | MVP | | D07 | POST `/documents/{document_id}/extraction-review/decisions` | Admin | 200 | MVP |
| K01 | GET `/knowledge-selection` | Admin | 200 | MVP | | K01 | GET `/knowledge-selection` | Admin | 200 | MVP |
@@ -183,9 +183,9 @@ paths, models or reviewer fields. Rejecting keeps zero publication and a safe
failure reason. Lost worker ownership cannot attach candidates; an admin cannot failure reason. Lost worker ownership cannot attach candidates; an admin cannot
approve a fresh OCR response using an old digest. approve a fresh OCR response using an old digest.
### D05 — Delete (deferred HTTP/UI) ### D05 — Delete (enabled HTTP/UI, 2026-10-18)
Required `expected_revision` is the current knowledge revision; required idempotency key. Transaction locks selection and document. Mark deleted and inactive; if formerly active, increment knowledge revision and access epoch and invalidate sessions. Physical cleanup is not promised by this response. JSON body: `{"expected_revision": N}` (positive strict integer; extra fields rejected). Required `expected_revision` is the current knowledge revision; required idempotency key. The authenticated administrator route requires Origin/CSRF validation and uses a bounded 1024-byte JSON body. Transaction locks selection and document. Mark deleted and inactive; if formerly active, increment knowledge revision and access epoch and invalidate sessions. Physical cleanup is not promised by this response.
```json ```json
{"document_id":"10000000-0000-4000-8000-000000000001","deleted":true,"knowledge_revision":3,"access_epoch":2,"cleanup_status":"pending_policy"} {"document_id":"10000000-0000-4000-8000-000000000001","deleted":true,"knowledge_revision":3,"access_epoch":2,"cleanup_status":"pending_policy"}
@@ -922,3 +922,26 @@ for this explicitly requested capability. It does not authorize promotion.
Provider secrets and tuned OpenAI speech settings stay server-side. Selection adds Provider secrets and tuned OpenAI speech settings stay server-side. Selection adds
no tables/migrations or document-content versioning. no tables/migrations or document-content versioning.
## Server source import amendment (2026-10-18)
The user explicitly authorized importing deployed document deletion, S2S diagnostics
and model settings. D05 HTTP/UI is enabled under its existing soft-deletion,
revision/epoch, replay and retention rules. The deployed request sends the
revision in the JSON body, not the historical query placeholder. This amendment
records that intentional contract and its Angular consumer.
F01 adds `models`, an array of `{id, label, model}` public identifiers. Roles are
`embedding`, `ocr`, and, when enabled/selectable, `dialogue`, `stt`, `tts`,
`openai` and `gemini`. It contains no credentials or service URLs and does not
promise that provider readiness has passed. The settings UI displays deployed
models; its Live card uses the existing permitted provider selector for the next
conversation. This does not add F02 model/credential editing or a selectable
arbitrary-model API. Existing model profile/revision pinning remains intact.
See [import evidence](../guides/server-source-sync-20261018.md).
## User-authorized evidence admission amendment (2026-10-18)
`search_knowledge` and shared search inspection now return up to ten whole eligible source chunks (previously five), within the unchanged 12,000-character text budget. Cutoff filtering may yield fewer. Schema and source identities are unchanged. Retrieval-policy fingerprint includes `whole-10-12000`; calibration reports must match. Current-turn source reporting remains mandatory; source order does not establish relevance. Local voice enables a bounded extractive output gate before TTS; unsupported text becomes a fixed insufficient-evidence response. See [grounding correction and validation](../guides/strict-grounding-20261018.md).
@@ -103,6 +103,7 @@ Composite FK to users. CHECK expires_at > created_at. Index expires_at for clean
| revision | bigint 1 | Settings optimistic revision | | revision | bigint 1 | Settings optimistic revision |
| knowledge_revision | bigint 1 | Selected-set revision | | knowledge_revision | bigint 1 | Selected-set revision |
| access_epoch | bigint 1 | Invalidation counter for removals | | access_epoch | bigint 1 | Invalidation counter for removals |
| voice_models | jsonb NOT NULL, empty object | Object-valued schema preparation added by 0006; public model display uses deployment settings |
| updated_by | uuid nullable | Actor; scoped FK to users | | updated_by | uuid nullable | Actor; scoped FK to users |
| updated_at | timestamptz | Last configuration/selection mutation | | updated_at | timestamptz | Last configuration/selection mutation |
@@ -518,3 +519,23 @@ close-on-interruption policy fields are frozen too. No schema migration is neede
old rows/snapshots are not rewritten and credentials/secret-derived hashes are old rows/snapshots are not rewritten and credentials/secret-derived hashes are
excluded. Replays retain their original profile; changed/missing effective state excluded. Replays retain their original profile; changed/missing effective state
rejects stream admission. See [Phase 2 evidence](../evaluation/local-s2s/phase-02.md). rejects stream admission. See [Phase 2 evidence](../evaluation/local-s2s/phase-02.md).
### Model-settings schema amendment (documented 2026-10-20)
The imported forward revision `0006_voice_model_settings` follows
`0005_live_owner_chain` and adds `organization_settings.voice_models jsonb
NOT NULL DEFAULT '{}'`, with `CHECK (jsonb_typeof(voice_models)='object')`.
It does not add a table or document-content version. Existing rows receive the
empty object; existing embedding/session profile metadata is not rewritten.
Current Live reservation admission requires revision 0006. Ingestion compatibility
also recognizes the new head; its broader compatibility allowance does not imply
that older schemas satisfy Live admission. Apply online forward migrations before
starting the updated API, preserving all applied revisions.
The column is schema preparation: current F01 public model inventory is derived
from deployment settings through the model catalog, not arbitrary values in this
column. F02/model mutation endpoints remain deferred. No provider credentials
belong in this JSON object. Downgrade removes the column and is not a routine
recovery procedure. See [current status](../current-status.md) and
[source-import evidence](../guides/server-source-sync-20261018.md).
@@ -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')
+4
View File
@@ -0,0 +1,4 @@
# COPY-only candidate; dependencies and upstream remain from the verified local base.
FROM rag-local-s2s-candidate:windows-rebuild-20261017
COPY app /app/app
COPY services/local_s2s /app/services/local_s2s
@@ -0,0 +1,9 @@
**
!app/
!app/**
!services/
!services/local_s2s/
!services/local_s2s/**
**/__pycache__
**/*.pyc
**/.env
+14
View File
@@ -1,3 +1,12 @@
Current handoff (documentation 2026-10-20; runtime evidence 2026-10-18):
[local Windows runbook](../../docs/guides/current-local-stack.md) and
[current status](../../docs/current-status.md).
Final recorded routing is ElevenLabs scribe_v2 STT, GapGPT gpt-4.1-mini dialogue,
and ElevenLabs eleven_v3/George TTS, speed 1.2, PCM 24 kHz, deadline 60 seconds.
The local strict extractive gate validates current-turn evidence before TTS.
Older build/acceptance checkpoints below describe their dated profiles.
Human acceptance of this final profile and operational promotion remain open.
# Phase 2 local engine (development only) # Phase 2 local engine (development only)
Current preparation (2026-10-16): [Phase 4 frontend/provider selection and paired evaluation tooling](../../docs/evaluation/local-s2s/phase-04.md). Current preparation (2026-10-16): [Phase 4 frontend/provider selection and paired evaluation tooling](../../docs/evaluation/local-s2s/phase-04.md).
@@ -407,3 +416,8 @@ restored its stopped state. No runtime assertion was relaxed. Phase 2 remains
NOT ACCEPTED until complete engine/SDK/POSIX, component audio and Persian browser NOT ACCEPTED until complete engine/SDK/POSIX, component audio and Persian browser
evidence exists along with Phase 1 acceptance. There were no paid calls, downloads, evidence exists along with Phase 1 acceptance. There were no paid calls, downloads,
image builds or operational changes in this preparation checkpoint. image builds or operational changes in this preparation checkpoint.
## Isolated responsiveness candidate (2026-10-17)
`LOCAL_S2S_RESPONSIVE=true` pins sentence-at-a-time output and ASR decode options. Default false retains baseline identities. See [implementation, checks and live comparison gate](../../docs/evaluation/local-s2s/responsive-candidate-20261017.md). No measured Persian latency/accuracy improvement is claimed before human comparison.
+143 -8
View File
@@ -1,5 +1,9 @@
"""Owned local HTTP gateway: total connection deadlines and bounded async I/O.""" """Owned local HTTP gateway: total connection deadlines and bounded async I/O."""
import asyncio import asyncio
import json
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
@@ -9,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)}
@@ -19,11 +32,27 @@ class EvaluationBudgetExhausted(ValueError):
class ComponentServer: class ComponentServer:
def __init__(self, key, *, port=8766, transport=None, timeout=30, inactivity=None): 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.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()
@@ -99,28 +128,114 @@ class ComponentServer:
pass pass
async def _forward(self, client, writer, path, fields, body, response): async def _forward(self, client, writer, path, fields, body, response):
request = client.build_request('POST', 'https://openrouter.ai/api' + path, url = ('https://api.gapgpt.app' if self.provider == 'gapgpt' else 'https://openrouter.ai/api') + path
headers={'Authorization': 'Bearer ' + self.key, auth_key = self.key
forward_body = bytes(body)
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'):
from email.parser import BytesParser
from email.policy import default
message = BytesParser(policy=default).parsebytes(
('Content-Type: ' + fields.get('content-type', '') + '\r\n\r\n').encode() + forward_body)
models = [part.get_payload(decode=True).decode() for part in message.iter_parts()
if part.get_param('name', header='content-disposition') == 'model']
if len(models) != 1:
raise ValueError('LOCAL_ASR_MODEL_REQUIRED')
direct_asr = models[0] in ('gpt-4o-transcribe', 'gpt-4o-mini-transcribe',
'gpt-4o-mini-transcribe-2025-12-15', 'whisper-1')
if path.endswith('/speech'):
payload = json.loads(forward_body)
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-'))
if direct_tts and model_name.startswith('openai/'):
payload['model'] = model_name.removeprefix('openai/')
forward_body = json.dumps(payload).encode()
else:
direct_tts = False
if ((direct_asr and not eleven_stt) or (direct_tts and tts_provider != 'elevenlabs')) and self.provider == 'split':
url = 'https://api.openai.com' + path
auth_key = os.environ.get('OPENAI_API_KEY', '')
if not auth_key:
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,
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=bytes(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.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
request = transcription_request(request)
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)
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)
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:
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)
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):
@@ -129,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()
@@ -155,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.
@@ -171,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:
@@ -189,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)
@@ -199,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():
@@ -224,8 +359,8 @@ class ComponentServer:
self.socket.close() self.socket.close()
def start_components(key, timeout=30): def start_components(key, timeout=30, **options):
server = ComponentServer(key, timeout=timeout) server = ComponentServer(key, timeout=timeout, **options)
thread = Thread(target=server.serve_forever, daemon=True) thread = Thread(target=server.serve_forever, daemon=True)
thread.start() thread.start()
if not server.ready.wait(5): if not server.ready.wait(5):
+32
View File
@@ -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
+27 -5
View File
@@ -1,4 +1,4 @@
"""Development engine launcher; local asset preflight precedes every paid probe.""" """Development engine launcher; local asset preflight precedes every paid probe."""
import argparse import argparse
import json import json
import logging import logging
@@ -33,6 +33,13 @@ def build_runtime(config, stop):
pipeline.Queue = PipelineQueue pipeline.Queue = PipelineQueue
# Base setup invokes warmup from inside construction; install before it runs. # Base setup invokes warmup from inside construction; install before it runs.
install_client_policy(base_llm, config) install_client_policy(base_llm, config)
import speech_to_speech.TTS.openai_compatible_handler as native_tts
from services.local_s2s.request_policy import install_tts_speed
install_tts_speed(native_tts, config.local_s2s_tts_speed)
if config.local_s2s_responsive and config.local_s2s_stt_provider == 'upstream':
import speech_to_speech.STT.openai_compatible_handler as native_stt
from services.local_s2s.responsiveness import install_stt_policy
install_stt_policy(native_stt)
# The pinned output processor also detects language for fixed session configs. # The pinned output processor also detects language for fixed session configs.
# Its first lazy Lingua preload can hold the GIL beyond the media send deadline. # Its first lazy Lingua preload can hold the GIL beyond the media send deadline.
# Prime the same cache before exposing the listener, within the startup budget. # Prime the same cache before exposing the listener, within the startup budget.
@@ -59,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')
@@ -84,10 +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': 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__':
+13
View File
@@ -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,6 +32,18 @@ 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']:
actual['tts']['speed'] = tts.speed
if 'temperature' in expected['stt']:
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
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
or str(llm.client.base_url).rstrip('/') != stt.base_url or str(llm.client.base_url).rstrip('/') != stt.base_url
+34
View File
@@ -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
+76
View File
@@ -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()
+3 -1
View File
@@ -171,7 +171,9 @@ def install_retained_history():
if raw.get('type') == 'response.cancel': if raw.get('type') == 'response.cancel':
st = service._state(session_id) st = service._state(session_id)
if not st.in_response or raw.get('response_id') != st.current_response_id: if not st.in_response or raw.get('response_id') != st.current_response_id:
error = service.make_error('Cancellation identity mismatch', 's2s_history_failed') error = service.make_error('Cancellation identity mismatch', 'invalid_request_error')
error.error.code = 'response_cancel_not_active'
error.error.param = None
error.error.event_id = raw.get('event_id') error.error.event_id = raw.get('event_id')
await transport.send_events([error]) await transport.send_events([error])
return return
+2 -2
View File
@@ -50,12 +50,12 @@ def cleanup(runtime, guard, thread, stop, *, timeout=2, emit=print):
return any(counters.values()) return any(counters.values())
def run_owned(build, key, request_timeout, *, startup_timeout=90, cleanup_timeout=2, emit=print): def run_owned(build, key, request_timeout, *, startup_timeout=90, cleanup_timeout=2, emit=print, component_options=None):
stop, constructed, finished, abandoned, lock = Event(), Event(), Event(), Event(), Lock() stop, constructed, finished, abandoned, lock = Event(), Event(), Event(), Event(), Lock()
runtime = None runtime = None
result = {} result = {}
with termination_signals(stop): with termination_signals(stop):
guard, thread = start_components(key, request_timeout) guard, thread = start_components(key, request_timeout, **(component_options or {}))
def drive(): def drive():
nonlocal runtime nonlocal runtime
if stop.is_set(): if stop.is_set():
+10
View File
@@ -36,6 +36,16 @@ def install_client_policy(base_module, config):
native_setup = base.setup native_setup = base.setup
def setup(self, *args, **kwargs): def setup(self, *args, **kwargs):
kwargs['request_timeout_s'] = config.local_s2s_request_timeout_seconds kwargs['request_timeout_s'] = config.local_s2s_request_timeout_seconds
if getattr(config, 'local_s2s_responsive', False):
kwargs['stream_batch_sentences'] = 1
return native_setup(self, *args, **kwargs) return native_setup(self, *args, **kwargs)
base.setup = setup base.setup = setup
return native return native
def install_tts_speed(module, speed):
native = module.OpenAICompatibleTTSHandler.setup
def setup(self, *args, **kwargs):
kwargs['speed'] = speed
return native(self, *args, **kwargs)
module.OpenAICompatibleTTSHandler.setup = setup
+36
View File
@@ -0,0 +1,36 @@
"""Opt-in applied ASR policy; provider routing remains in the engine gateway."""
import base64
from email.parser import BytesParser
from email.policy import default
import json
import httpx
from app.modules.voice.local_s2s import RESPONSIVE_ASR_PROMPT
def install_stt_policy(module):
native=module.OpenAICompatibleSTTHandler.setup
def setup(self,*args,**kwargs):
kwargs['gen_kwargs']={**kwargs.get('gen_kwargs',{}),'temperature':0,'prompt':RESPONSIVE_ASR_PROMPT}
return native(self,*args,**kwargs)
module.OpenAICompatibleSTTHandler.setup=setup
def transcription_request(request):
"""Map pinned multipart to documented JSON provider.options; never change audio."""
if not request.headers.get('content-type','').startswith('multipart/form-data;'):
raise ValueError('LOCAL_ASR_MULTIPART_REQUIRED')
message=BytesParser(policy=default).parsebytes(('Content-Type: '+request.headers['content-type']+'\r\nMIME-Version: 1.0\r\n\r\n').encode()+request.content)
fields={}
for part in message.iter_parts():
name=part.get_param('name',header='content-disposition')
if name in fields:raise ValueError('LOCAL_ASR_DUPLICATE_FIELD')
fields[name]=part.get_payload(decode=True)
if (set(fields)!={'file','model','language','response_format','temperature','prompt'} or
fields['language']!=b'fa' or fields['response_format']!=b'json' or
fields['temperature'] not in (b'0',b'0.0') or fields['prompt'].decode()!=RESPONSIVE_ASR_PROMPT):
raise ValueError('LOCAL_ASR_PROFILE_MISMATCH')
data=dict(model=fields['model'].decode(),language='fa',response_format='json',temperature=0,
input_audio=dict(data=base64.b64encode(fields['file']).decode('ascii'),format='wav'),
provider=dict(options={'groq':{'prompt':RESPONSIVE_ASR_PROMPT}}))
return httpx.Request(request.method,request.url,
headers={k:v for k,v in request.headers.items() if k not in ('content-type','content-length')},json=data)
+39
View File
@@ -0,0 +1,39 @@
---
title: Whisper Persian v4 - Speech Recognition Demo
emoji: 🎙️
colorFrom: indigo
colorTo: purple
sdk: gradio
sdk_version: 5.50.0
app_file: app.py
pinned: false
license: apache-2.0
short_description: Persian ASR with Whisper Large v3 (WER 8.73%)
tags:
- audio
- speech-recognition
- whisper
- persian
- farsi
- asr
---
# 🎙️ Whisper Persian v4 - Automatic Speech Recognition Demo
### دمو بازشناسی گفتار فارسی با مدل Whisper Persian v4
این فضا یک دموی پیشرفته و بهینه‌شده برای مدل **[nezamisafa/whisper-persian-v4](https://huggingface.co/nezamisafa/whisper-persian-v4)** است.
## 📌 ویژگی‌های مدل (Model Highlights)
- **مدل پایه (Base Model):** `openai/whisper-large-v3` (~1.54 میلیارد پارامتر)
- **مجموعه داده آموزش (Training Dataset):** `nezamisafa/ASR_fa_v1`
- **معیار خطای کلمه (Word Error Rate - WER):** **8.73%** روی مجموعه تست
- **بهینه‌سازی:** پشتیبانی از ZeroGPU برای اجرای بلادرنگ، ورودی صوتی زنده (میکروفون) و فایل، تولید زمان‌بندی (Timestamps) و خروجی زیرنویس (SRT).
## 🚀 قابلیت‌های دمو
1. **تایپ خودکار گفتار:** تبدیل گفتار فارسی به متن با دقت بسیار بالا و نگارش صحیح.
2. **برچسب‌گذاری زمانی (Timestamps):** استخراج بازه‌های زمانی کلمات و عبارات.
3. **پشتیبانی از فرمت‌های صوتی مختلف:** MP3, WAV, M4A, FLAC, OGG و ضبط زنده میکروفون.
4. **رابط کاربری مدرن:** پشتیبانی کامل از چینش راست‌به‌چپ (RTL)، کپی سریع متن و دانلود زیرنویس.
---
Built with ❤️ using [Gradio](https://github.com/gradio-app/gradio) and [Transformers](https://github.com/huggingface/transformers).
+297
View File
@@ -0,0 +1,297 @@
import os
import time
# ZeroGPU requires spaces to be imported before any CUDA-dependent libraries
try:
import spaces
except ImportError:
class spaces:
@staticmethod
def GPU(duration=60):
def decorator(fn):
return fn
return decorator
import gradio as gr
import torch
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
# Model configuration
MODEL_ID = "nezamisafa/whisper-persian-v4"
device = "cuda" if torch.cuda.is_available() else "cpu"
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
print(f"Loading model {MODEL_ID} on device: {device} (dtype: {torch_dtype})...")
model = AutoModelForSpeechSeq2Seq.from_pretrained(
MODEL_ID,
torch_dtype=torch_dtype,
low_cpu_mem_usage=True,
use_safetensors=True,
)
if torch.cuda.is_available():
model = model.to("cuda")
processor = AutoProcessor.from_pretrained(MODEL_ID)
pipe = pipeline(
"automatic-speech-recognition",
model=model,
tokenizer=processor.tokenizer,
feature_extractor=processor.feature_extractor,
chunk_length_s=30,
stride_length_s=5,
batch_size=8,
torch_dtype=torch_dtype,
ignore_warning=True,
device="cuda" if torch.cuda.is_available() else "cpu",
)
def format_timestamp(seconds: float) -> str:
"""Format seconds into SRT timestamp HH:MM:SS,mmm."""
hrs = int(seconds // 3600)
mins = int((seconds % 3600) // 60)
secs = int(seconds % 60)
millis = int((seconds - int(seconds)) * 1000)
return f"{hrs:02d}:{mins:02d}:{secs:02d},{millis:03d}"
def generate_srt(chunks: list[dict]) -> str:
"""Convert chunk list with timestamps to standard SRT format."""
srt_lines = []
for i, chunk in enumerate(chunks, 1):
timestamp = chunk.get("timestamp", (0.0, 0.0))
start = timestamp[0] if timestamp and timestamp[0] is not None else 0.0
end = timestamp[1] if timestamp and timestamp[1] is not None else (start + 2.0)
text = chunk.get("text", "").strip()
srt_lines.append(f"{i}\n{format_timestamp(start)} --> {format_timestamp(end)}\n{text}\n")
return "\n".join(srt_lines)
def generate_segments_html(chunks: list[dict]) -> str:
"""Generate a clean and responsive HTML table for timestamped segments."""
if not chunks:
return """
<div style="padding: 30px; text-align: center; color: #94a3b8; font-size: 0.95rem;">
هنوز فایلی پردازش نشده یا گزینه‌ی زمان‌بندی غیرفعال بوده است.
</div>
"""
rows = []
for i, chunk in enumerate(chunks, 1):
ts = chunk.get("timestamp", (0.0, 0.0))
s = round(ts[0], 2) if ts and ts[0] is not None else 0.0
e = round(ts[1], 2) if ts and ts[1] is not None else s
text = chunk.get("text", "").strip()
rows.append(f"""
<tr style="border-bottom: 1px solid #f1f5f9; transition: background 0.2s;">
<td style="padding: 10px 14px; font-weight: 700; color: #6366f1; width: 45px;">#{i}</td>
<td style="padding: 10px 14px; direction: ltr; text-align: center; width: 140px;">
<span style="background: #eef2ff; color: #4338ca; padding: 3px 8px; border-radius: 6px; font-family: monospace; font-size: 0.85rem; font-weight: 600;">
{s:.2f}s - {e:.2f}s
</span>
</td>
<td style="padding: 10px 14px; font-size: 1rem; line-height: 1.7; text-align: right; color: #1e293b;">{text}</td>
</tr>
""")
return f"""
<div style="max-height: 380px; overflow-y: auto; border: 1px solid #e2e8f0; border-radius: 10px; background: #ffffff;">
<table style="width: 100%; border-collapse: collapse; text-align: right; direction: rtl;">
<thead>
<tr style="background: #f8fafc; border-bottom: 2px solid #e2e8f0; color: #475569; font-size: 0.88rem;">
<th style="padding: 10px 14px;">ردیف</th>
<th style="padding: 10px 14px; text-align: center;">بازه زمانی</th>
<th style="padding: 10px 14px;">متن پیاده‌سازی شده</th>
</tr>
</thead>
<tbody>
{''.join(rows)}
</tbody>
</table>
</div>
"""
@spaces.GPU(duration=60)
def transcribe(audio_path, return_timestamps=True):
"""
Transcribe Persian speech audio to text with timestamps using Whisper Persian v4.
"""
if not audio_path:
return (
"لطفاً ابتدا یک فایل صوتی آپلود کنید یا صدایتان را ضبط نمایید.",
generate_segments_html([]),
"",
"⚠️ لطفاً ورودی صوتی را مشخص کنید."
)
start_time = time.perf_counter()
try:
generate_kwargs = {
"language": "persian",
"task": "transcribe"
}
result = pipe(
audio_path,
return_timestamps=return_timestamps,
generate_kwargs=generate_kwargs
)
elapsed = round(time.perf_counter() - start_time, 2)
full_text = result.get("text", "").strip()
chunks = result.get("chunks", [])
segments_html = generate_segments_html(chunks)
srt_content = generate_srt(chunks) if chunks else ""
metrics = f"✅ پردازش موفق در {elapsed} ثانیه | مدل: nezamisafa/whisper-persian-v4"
return full_text, segments_html, srt_content, metrics
except Exception as e:
error_msg = str(e)
return (
f"خطا در پردازش صوت: {error_msg}",
generate_segments_html([]),
"",
f"❌ خطای سیستم: {error_msg}"
)
CUSTOM_CSS = """
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&display=swap');
body, .gradio-container {
font-family: 'Vazirmatn', system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important;
direction: rtl;
}
.persian-title {
text-align: center;
background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 50%, #db2777 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
font-size: 2.2rem;
font-weight: 800;
margin-bottom: 0.2rem;
}
.persian-subtitle {
text-align: center;
color: #64748b;
font-size: 1.05rem;
margin-bottom: 1.5rem;
}
.metric-badge-container {
display: flex;
justify-content: center;
gap: 12px;
flex-wrap: wrap;
margin-bottom: 1.5rem;
}
.metric-badge {
background: #f1f5f9;
border: 1px solid #e2e8f0;
border-radius: 9999px;
padding: 6px 14px;
font-size: 0.85rem;
font-weight: 600;
color: #334155;
}
.dark .metric-badge {
background: #1e293b;
border-color: #334155;
color: #cbd5e1;
}
.rtl-text-box textarea {
direction: rtl !important;
text-align: right !important;
font-size: 1.15rem !important;
line-height: 1.8 !important;
font-family: 'Vazirmatn', sans-serif !important;
}
.srt-text-box textarea {
direction: ltr !important;
text-align: left !important;
font-family: monospace !important;
font-size: 0.9rem !important;
}
footer {
display: none !important;
}
"""
with gr.Blocks(title="Whisper Persian v4 🎙️ دمو بازشناسی گفتار فارسی", css=CUSTOM_CSS, theme=gr.themes.Soft(primary_hue="indigo")) as demo:
gr.HTML("""
<div style="padding: 10px 0;">
<h1 class="persian-title">مدل بازشناسی گفتار فارسی ویسپر (نسخه ۴)</h1>
<p class="persian-subtitle">تبدیل گفتار و صوت فارسی به متن دقیق با بهره‌گیری از مدل بهینه‌شده Whisper Large v3</p>
<div class="metric-badge-container">
<span class="metric-badge">🏆 مدل پایه: Whisper Large v3</span>
<span class="metric-badge">🎯 نرخ خطا (WER): ۸.۷۳٪</span>
<span class="metric-badge">📦 دیتاست آموزش: ASR_fa_v1</span>
<span class="metric-badge">⚡ سخت‌افزار: ZeroGPU شتاب‌یافته</span>
</div>
</div>
""")
with gr.Row():
with gr.Column(scale=5):
audio_input = gr.Audio(
sources=["microphone", "upload"],
type="filepath",
label="ورودی صوت (میکروفون یا فایل صوتی)",
)
return_ts_checkbox = gr.Checkbox(
value=True,
label="استخراج زمان‌بندی دقیق بخش‌ها (Timestamps)",
info="ایجاد برچسب زمانی و ساخت زیرنویس خودکار"
)
transcribe_btn = gr.Button("🚀 شروع بازشناسی گفتار", variant="primary", size="lg")
metrics_display = gr.Markdown("آماده دریافت فایل یا صدای شما...")
with gr.Column(scale=6):
output_text = gr.Textbox(
label="متن استخراج‌شده (فارسی)",
lines=7,
elem_classes=["rtl-text-box"],
show_copy_button=True,
placeholder="متن پیاده‌سازی شده در اینجا نمایش داده خواهد شد..."
)
with gr.Tabs():
with gr.TabItem("📋 بخش‌ها و زمان‌بندی"):
segments_html_view = gr.HTML(
value=generate_segments_html([]),
label="جدول زمان‌بندی بخش‌ها"
)
with gr.TabItem("📄 فرمت زیرنویس (SRT)"):
srt_output = gr.Textbox(
label="فایل زیرنویس SRT",
lines=7,
elem_classes=["srt-text-box"],
show_copy_button=True
)
transcribe_btn.click(
fn=transcribe,
inputs=[audio_input, return_ts_checkbox],
outputs=[output_text, segments_html_view, srt_output, metrics_display],
api_name=False
)
gr.HTML("""
<div style="margin-top: 30px; padding: 15px; border-radius: 12px; background: rgba(99, 102, 241, 0.05); border: 1px solid rgba(99, 102, 241, 0.2); direction: rtl; text-align: right;">
<h4 style="margin-top: 0; color: #4338ca;">درباره مدل nezamisafa/whisper-persian-v4</h4>
<p style="font-size: 0.95rem; line-height: 1.7; margin-bottom: 0;">
این مدل نسخه بهبودیافته و fine-tune شده از مدل بزرگ <code>openai/whisper-large-v3</code> بر روی دیتاست جامع فارسی <code>nezamisafa/ASR_fa_v1</code> است که توانسته در ارزیابی نهایی به WER کم‌نظیر <strong>۸.۷۳٪</strong> دست یابد. این فضا مجهز به ساختار بهینه‌سازی‌شده ZeroGPU می‌باشد.
</p>
</div>
""")
if __name__ == "__main__":
demo.launch()
@@ -0,0 +1,6 @@
transformers>=4.40.0
torchaudio
accelerate
soundfile
librosa
pandas
@@ -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
+4 -3
View File
@@ -1,4 +1,4 @@
"""Real DB local profiles retain replay/owner/revocation authority.""" """Real DB local profiles retain replay/owner/revocation authority."""
from uuid import UUID, uuid4 from uuid import UUID, uuid4
from sqlalchemy import text from sqlalchemy import text
import pytest import pytest
@@ -6,11 +6,12 @@ from tests.integration.test_phase2_postgres import seeded_env
from tests.unit.test_local_s2s_phase2 import local_config from tests.unit.test_local_s2s_phase2 import local_config
def test_local_profile_replay_never_rewrites_frozen_components(seeded_env): @pytest.mark.parametrize('responsive',[False, True])
def test_local_profile_replay_never_rewrites_frozen_components(seeded_env,responsive):
e = seeded_env e = seeded_env
cid = UUID(e.lifecycle.create_conversation(e.user, uuid4())['id']) cid = UUID(e.lifecycle.create_conversation(e.user, uuid4())['id'])
request = uuid4() request = uuid4()
config = local_config() config = local_config(local_s2s_responsive=responsive)
first = e.lifecycle.create_live_session(e.user, cid, request, provider='local_s2s', first = e.lifecycle.create_live_session(e.user, cid, request, provider='local_s2s',
model=config.selected_model, execution_profile=config.profile()) model=config.selected_model, execution_profile=config.profile())
sid = UUID(first['session_id']) sid = UUID(first['session_id'])
+109
View File
@@ -0,0 +1,109 @@
"""Documentary carry must preserve prior exposure and exclusive live admission."""
import asyncio
import importlib.util
import json
from pathlib import Path
import httpx
import pytest
spec=importlib.util.spec_from_file_location('phase4_guard',Path(__file__).parents[2]/'docs/evaluation/local-s2s/phase4-browser-budget.py')
guard=importlib.util.module_from_spec(spec);spec.loader.exec_module(guard)
@pytest.fixture
def evidence(tmp_path):
checkpoint=dict(prior_conservative_exposure_usd='0.704504399',total_cap_usd='1',paid_calls_on_this_host=0,prior_private_ledgers_available=False,source='docs/evaluation/local-s2s/phase-04-interruption-incident.md',status='preparation_only_not_a_live_admission_ledger')
(tmp_path/'carried-budget-preparation.json').write_text(json.dumps(checkpoint))
endpoints=[dict(tag=tag,max_prompt_tokens=8192,max_completion_tokens=16384,pricing=dict(prompt='0.0000005',completion='0.000006')) for tag in ('google-ai-studio','google-vertex/global')]
(tmp_path/'endpoints-google-gemini-3.8-flash-lite-tts.json').write_text(json.dumps(dict(data=dict(endpoints=endpoints))))
(tmp_path/'endpoints-openai-whisper-large-v3.json').write_text(json.dumps(dict(data=dict(endpoints=[dict(pricing=dict(prompt='0.000001'))]))))
return tmp_path
def test_failures_remain_reserved_and_limit_precedes_provider(evidence):
async def run():
calls=[]
def upstream(request):
calls.append(request)
return httpx.Response(503)
transport=guard.BrowserBudget(evidence,upstream=httpx.MockTransport(upstream))
assert transport.state['maximum_cumulative_usd']=='0.940504399'
assert transport.state['carry_basis']=='documentary_checkpoint'
request=httpx.Request('POST','https://openrouter.ai/api/v1/audio/speech',json=dict(model='google/gemini-3.8-flash-lite-tts',voice='Kore',input='test',response_format='pcm'))
try:
for _ in range(4):await transport.handle_async_request(request)
with pytest.raises(guard.EvaluationBudgetExhausted):await transport.handle_async_request(request)
assert len(calls)==4
assert transport.state['reserved_usd']=='0.844504399'
assert len(transport.state['attempts'])==4
with pytest.raises(FileExistsError):guard.BrowserBudget(evidence,upstream=httpx.MockTransport(upstream))
finally:await transport.close_owned()
asyncio.run(run())
@pytest.mark.parametrize('field,value',[('prior_conservative_exposure_usd','0'),('total_cap_usd','5'),('paid_calls_on_this_host',1),('prior_private_ledgers_available',True)])
def test_changed_carry_rejected_before_ledger_creation(evidence,field,value):
p=evidence/'carried-budget-preparation.json';data=json.loads(p.read_text());data[field]=value;p.write_text(json.dumps(data))
with pytest.raises(ValueError):guard.BrowserBudget(evidence)
assert not (evidence/'browser-paid-ledger.json').exists()
def test_mixed_carry_evidence_rejected(evidence):
(evidence/'previous-phase4-ledger.json').write_text('{}')
with pytest.raises(ValueError):guard.BrowserBudget(evidence)
assert not (evidence/'browser-paid-ledger.json').exists()
@pytest.fixture
def billed_evidence(evidence):
attempts=[];bills=[]
for stage,reserve,cost in [('transcriptions','.004','0.0000075'),('completions','.02','0.0000228'),('speech','.035','0.0001635')]:
attempts.append(dict(stage=stage,reserved_usd=reserve,status='headers_received',http_status=200,generation_id='fixture-'+stage))
bills.append(dict(stage=stage,generation_id='fixture-'+stage,http_status=200,billing=dict(total_cost=cost)))
(evidence/'previous-windows-ledger.json').write_text(json.dumps(dict(previous_reserved_and_billed_usd='0.704504399',reserved_usd='0.763504399',carry_basis='documentary_checkpoint',attempts=attempts)))
(evidence/'previous-windows-billing.json').write_text(json.dumps(bills))
return evidence
def test_only_exact_billed_attempts_release_reserves(billed_evidence):
async def run():
transport=guard.BrowserBudget(billed_evidence,upstream=httpx.MockTransport(lambda r:httpx.Response(503)))
try:
assert transport.state['reserved_usd']=='0.704698199'
assert transport.state['maximum_cumulative_usd']=='0.940698199'
assert transport.state['carry_basis']=='documentary_checkpoint_with_local_bills'
finally:await transport.close_owned()
asyncio.run(run())
@pytest.mark.parametrize('change',['wrong_id','negative_cost','missing_receipt'])
def test_unverified_billing_cannot_release_reserves(billed_evidence,change):
path=billed_evidence/'previous-windows-billing.json';bills=json.loads(path.read_text())
if change=='wrong_id':bills[0]['generation_id']='unrelated'
elif change=='negative_cost':bills[0]['billing']['total_cost']='-1'
else:bills.pop()
path.write_text(json.dumps(bills))
with pytest.raises(ValueError):guard.BrowserBudget(billed_evidence)
assert not (billed_evidence/'browser-paid-ledger.json').exists()
@pytest.fixture
def chained_evidence(billed_evidence):
first=json.loads((billed_evidence/'previous-windows-ledger.json').read_text());bills=json.loads((billed_evidence/'previous-windows-billing.json').read_text())
second=json.loads(json.dumps(first));second['previous_reserved_and_billed_usd']='0.704698199';second['reserved_usd']='0.763698199'
for row in second['attempts']:row['generation_id']='second-'+row['generation_id']
second_bills=json.loads(json.dumps(bills))
for row in second_bills:row['generation_id']='second-'+row['generation_id']
(billed_evidence/'one-ledger.json').write_text(json.dumps(first));(billed_evidence/'one-bills.json').write_text(json.dumps(bills))
(billed_evidence/'two-ledger.json').write_text(json.dumps(second));(billed_evidence/'two-bills.json').write_text(json.dumps(second_bills))
(billed_evidence/'previous-windows-ledger.json').unlink();(billed_evidence/'previous-windows-billing.json').unlink()
(billed_evidence/'previous-windows-runs.json').write_text(json.dumps([dict(ledger='one-ledger.json',billing='one-bills.json'),dict(ledger='two-ledger.json',billing='two-bills.json')]))
return billed_evidence
def test_chained_receipts_carry_all_previous_calls(chained_evidence):
async def run():
g=guard.BrowserBudget(chained_evidence,upstream=httpx.MockTransport(lambda r:httpx.Response(503)))
try:
assert g.state['reserved_usd']=='0.704891999'
assert g.state['maximum_cumulative_usd']=='0.975891999'
finally:await g.close_owned()
asyncio.run(run())
def test_chain_cannot_skip_prior_cost(chained_evidence):
p=chained_evidence/'two-ledger.json';data=json.loads(p.read_text());data['previous_reserved_and_billed_usd']='0.704504399';p.write_text(json.dumps(data))
with pytest.raises(ValueError):guard.BrowserBudget(chained_evidence)
assert not (chained_evidence/'browser-paid-ledger.json').exists()
@@ -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())
+135
View File
@@ -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')
+132
View File
@@ -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())
+158
View File
@@ -0,0 +1,158 @@
"""Opt-in policy must reach real wire bytes and remain frozen/attested."""
import asyncio
import base64
from io import BytesIO
import importlib.util
import json
from pathlib import Path
from threading import Thread
from types import SimpleNamespace
import wave
import httpx
import pytest
from app.modules.voice.local_s2s import RESPONSIVE_ASR_PROMPT
from services.local_s2s.responsiveness import install_stt_policy,transcription_request
from services.local_s2s.extension import active_components
from services.local_s2s.components import ComponentServer
from services.local_s2s.request_policy import install_client_policy
from tests.unit.test_local_s2s_phase2 import local_config,confirmed
from tests.unit.test_local_s2s_engine import handlers
from app.infrastructure.local_s2s import LocalS2SAdapter
from app.modules.voice.settings import RuntimeSettings
def audio():
out=BytesIO()
with wave.open(out,'wb') as w:
w.setnchannels(1);w.setsampwidth(2);w.setframerate(16000);w.writeframes(bytes(3200))
return out.getvalue()
def request():
r=httpx.Request('POST','https://openrouter.ai/api/v1/audio/transcriptions',data=dict(model='openai/whisper-large-v3',language='fa',response_format='json',temperature='0',prompt=RESPONSIVE_ASR_PROMPT),files={'file':('audio.wav',audio(),'audio/wav')})
r.read();return r
def test_profile_changes_identity_and_requires_applied_settings():
baseline=local_config();responsive=local_config(local_s2s_responsive=True)
assert baseline.profile()!=responsive.profile()
assert not LocalS2SAdapter(None,config=baseline,settings=RuntimeSettings(_env_file=None)).acknowledged(confirmed(LocalS2SAdapter(None,config=responsive,settings=RuntimeSettings(_env_file=None))))
unit=handlers(responsive);unit.handlers[1].gen_kwargs=dict(temperature=0,prompt=RESPONSIVE_ASR_PROMPT);unit.handlers[2].stream_batch_sentences=1
assert active_components(unit,responsive.components())==responsive.components()
unit.handlers[2].stream_batch_sentences=3
with pytest.raises(ValueError):active_components(unit,responsive.components())
def test_transcription_policy_preserves_audio_and_uses_supported_options():
r=transcription_request(request());d=json.loads(r.content)
assert base64.b64decode(d['input_audio']['data'])==audio()
assert d['temperature']==0 and d['language']=='fa'
assert d['provider']=={'options':{'groq':{'prompt':RESPONSIVE_ASR_PROMPT}}}
assert 'prompt' not in d
spec=importlib.util.spec_from_file_location('admission',Path(__file__).parents[2]/'docs/evaluation/local-s2s/native-budget-transport.py')
m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m)
assert m.validate_request(r)[0]=='transcriptions'
d['temperature']=1
with pytest.raises(ValueError):m.validate_request(httpx.Request(r.method,r.url,json=d))
def test_stt_settings_apply_before_native_setup_and_warmup():
calls=[]
class Handler:
def setup(self,**kwargs):calls.append(kwargs)
module=SimpleNamespace(OpenAICompatibleSTTHandler=Handler)
install_stt_policy(module);Handler().setup(gen_kwargs={'response_style':'plain'})
assert calls==[{'gen_kwargs':{'response_style':'plain','temperature':0,'prompt':RESPONSIVE_ASR_PROMPT}}]
def test_sentence_policy_applies_before_llm_warmup():
calls=[]
class Base:
def setup(self,**kwargs):calls.append(kwargs)
module=SimpleNamespace(OpenAI=lambda **kwargs:None,BaseOpenAICompatibleHandler=Base)
install_client_policy(module,local_config(local_s2s_responsive=True));Base().setup()
assert calls[0]['stream_batch_sentences']==1
def test_actual_gateway_transforms_request_without_rewriting_transcript(capsys):
observed=[]
def upstream(r):
observed.append(json.loads(r.content))
return httpx.Response(200,headers={'content-type':'application/json'},json={'text':'unchanged transcript'})
server=ComponentServer('fixture-key',port=0,transport=httpx.MockTransport(upstream),responsive=True)
thread=Thread(target=server.serve_forever,daemon=True);thread.start();assert server.ready.wait(3)
try:
r=request()
with httpx.Client(trust_env=False,timeout=5) as client:
result=client.post('http://127.0.0.1:'+str(server.server_port)+'/v1/audio/transcriptions',content=r.content,headers={'content-type':r.headers['content-type'],'authorization':'Bearer local-components'})
assert result.status_code==200 and result.json()['text']=='unchanged transcript'
assert observed[0]['provider']['options']['groq']['prompt']==RESPONSIVE_ASR_PROMPT
finally:
server.shutdown();server.server_close();thread.join(3)
output=capsys.readouterr().out
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
@pytest.mark.parametrize('component', ['transcriptions', 'speech'])
@pytest.mark.parametrize('has_key', [True, False])
def test_direct_openai_audio_routes_and_never_uses_router_key(monkeypatch, component, has_key):
if has_key:
monkeypatch.setenv('OPENAI_API_KEY', 'openai-fixture')
else:
monkeypatch.delenv('OPENAI_API_KEY', raising=False)
observed = []
def upstream(r):
observed.append(r)
return httpx.Response(200, headers={'content-type': 'application/json' if component == 'transcriptions' else 'audio/pcm'},
content=b'{"text":"unchanged"}' if component == 'transcriptions' else bytes(100))
if component == 'transcriptions':
r = httpx.Request('POST', 'http://fixture', data=dict(model='gpt-4o-transcribe', language='fa', response_format='json', temperature='0', prompt=RESPONSIVE_ASR_PROMPT), files={'file': ('audio.wav', audio(), 'audio/wav')})
r.read()
else:
r = httpx.Request('POST', 'http://fixture', json=dict(model='openai/gpt-4o-mini-tts', input='fixture', voice='alloy', response_format='pcm'))
server = ComponentServer('router-fixture', port=0, transport=httpx.MockTransport(upstream), responsive=True)
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:
try:
result = client.post(f'http://127.0.0.1:{server.server_port}/v1/audio/{component}', content=r.content,
headers={'content-type': r.headers['content-type'], 'authorization': 'Bearer local-components'})
except httpx.RemoteProtocolError:
assert not has_key
else:
assert has_key and result.status_code == 200
if has_key:
sent = observed[0]
assert str(sent.url) == f'https://api.openai.com/v1/audio/{component}'
assert sent.headers['authorization'] == 'Bearer openai-fixture'
if component == 'transcriptions':
assert sent.content == r.content
assert sent.headers['content-type'].startswith('multipart/form-data;')
else:
assert json.loads(sent.content)['model'] == 'gpt-4o-mini-tts'
else:
assert observed == []
finally:
server.shutdown(); server.server_close(); thread.join(3)
def test_faster_tts_applies_before_warmup_and_is_attested():
from services.local_s2s.request_policy import install_tts_speed
from app.modules.voice.local_s2s import setup_session
calls = []
class Handler:
def setup(self, **kwargs):
self.speed = kwargs['speed']; calls.append(kwargs)
module = SimpleNamespace(OpenAICompatibleTTSHandler=Handler)
install_tts_speed(module, 1.3); handler = Handler(); handler.setup()
assert calls == [{'speed': 1.3}]
config = local_config(local_s2s_tts_speed=1.3)
assert setup_session(config)['audio']['output']['speed'] == 1.3
assert config.profile() != local_config().profile()
unit = handlers(config); unit.handlers[-1].speed = handler.speed
assert active_components(unit, config.components())['tts']['speed'] == 1.3
unit.handlers[-1].speed = 1.0
with pytest.raises(ValueError): active_components(unit, config.components())
+1 -1
View File
@@ -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():
+34
View File
@@ -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
+58
View File
@@ -0,0 +1,58 @@
"""The Windows handoff supervisor must fail closed and stop only its engine."""
import importlib.util
import json
from pathlib import Path
import pytest
@pytest.fixture
def watcher(tmp_path,monkeypatch):
spec=importlib.util.spec_from_file_location('windows_watch',Path(__file__).parents[2]/'docs/evaluation/local-s2s/watch-windows-browser.py')
m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m)
monkeypatch.setattr(m,'EVIDENCE',tmp_path)
monkeypatch.setattr(m,'REPORT',tmp_path/'report.json')
monkeypatch.setattr(m,'available',lambda:4*1024**3)
monkeypatch.setattr(m,'vm_available',lambda:6*1024**3)
monkeypatch.setattr(m.signal,'signal',lambda *args:None)
calls=[]
monkeypatch.setattr(m.subprocess,'run',lambda command,**kwargs:calls.append(command))
return m,calls
def test_existing_ledger_never_restarts(watcher):
m,calls=watcher;(m.EVIDENCE/'browser-paid-ledger.json').write_text('{}')
with pytest.raises(SystemExit):m.main()
assert calls==[]
def test_low_memory_makes_no_launch(watcher,monkeypatch):
m,calls=watcher;monkeypatch.setattr(m,'available',lambda:1024**3)
with pytest.raises(SystemExit):m.main(enforce_memory=True)
assert calls==[]
assert json.loads(m.REPORT.read_text())['reason']=='prestart_memory'
@pytest.mark.parametrize('reason',['memory_floor','handoff_expired_30_minutes'])
def test_runtime_guard_stops_only_owned_engine(watcher,monkeypatch,reason):
m,calls=watcher
if reason=='memory_floor':
readings=iter([4*1024**3,2*1024**3]);monkeypatch.setattr(m,'available',lambda:next(readings))
monkeypatch.setattr(m.time,'monotonic',lambda:0)
else:
times=iter([0,1801,1801]);monkeypatch.setattr(m.time,'monotonic',lambda:next(times))
m.main(enforce_memory=True)
assert len(calls)==2
assert calls[0][-5:]==['--pull','never','--no-deps','-d','local-s2s-engine']
assert calls[1][-4:]==['stop','--timeout','5','local-s2s-engine']
assert json.loads(m.REPORT.read_text())['reason']==reason
def test_default_observes_low_memory_without_blocking_or_stopping(watcher,monkeypatch):
m,calls=watcher
monkeypatch.setattr(m,'available',lambda:1024**3)
monkeypatch.setattr(m,'vm_available',lambda:1024**3)
times=iter([0,1801,1801]);monkeypatch.setattr(m.time,'monotonic',lambda:next(times))
m.main()
report=json.loads(m.REPORT.read_text())
assert report['memory_enforcement'] is False
assert report['reason']=='handoff_expired_30_minutes'
assert report['minimum_windows_available_bytes']==1024**3
assert len(calls)==2
assert calls[0][-1]=='local-s2s-engine'
assert calls[1][-4:]==['stop','--timeout','5','local-s2s-engine']