feat(voice): add isolated Local S2S v3 candidate and acceptance evidence
Extract the provider boundary while retaining OpenAI/Gemini contracts. Add an opt-in isolated Local S2S adapter, pinned engine extension, bounded component gateway and frozen effective configuration profiles. Enforce request token limits, zero retries, local asset validation, connection deadlines, disconnect ownership, bounded cleanup and signals. Include regression coverage, pinned source fixtures, operator guidance, asset fingerprints and guarded disposable PostgreSQL acceptance tooling. Preserve immutable fixture bytes across Git line-ending conversion. Validation recorded in the reports: - 74 repair, 107 combined and 242 preservation checks passed. - Fresh PostgreSQL local checks: 2 passed. - Expanded PostgreSQL: 57 passed, 6 documented baseline failures. - Compose configurations, staged whitespace and fixture hashes passed. Phase 1 live listening and Phase 2 complete engine/SDK/POSIX, real component audio and Persian browser acceptance remain pending. No operational switch, paid call, model download or Phase 3 implementation is included.
This commit is contained in:
+201
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [2024] [The HuggingFace Inc. team]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+1128
File diff suppressed because it is too large
Load Diff
+389
@@ -0,0 +1,389 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from collections.abc import Iterator
|
||||
from typing import Any, cast
|
||||
|
||||
from openai import Stream
|
||||
from openai.types.chat import (
|
||||
ChatCompletionChunk,
|
||||
ChatCompletionContentPartImageParam,
|
||||
ChatCompletionContentPartParam,
|
||||
ChatCompletionContentPartTextParam,
|
||||
ChatCompletionNamedToolChoiceParam,
|
||||
ChatCompletionToolChoiceOptionParam,
|
||||
ChatCompletionToolParam,
|
||||
)
|
||||
from openai.types.chat.chat_completion_content_part_image_param import ImageURL
|
||||
from openai.types.chat.chat_completion_named_tool_choice_param import Function as NamedToolChoiceFunction
|
||||
from openai.types.realtime.realtime_conversation_item_assistant_message import (
|
||||
Content as AssistantContent,
|
||||
)
|
||||
from openai.types.responses import ResponseFunctionToolCall
|
||||
from openai.types.shared_params import FunctionDefinition
|
||||
|
||||
from speech_to_speech.LLM.base_openai_compatible_language_model import (
|
||||
WARMUP_MAX_RETRIES,
|
||||
AssistantMessage,
|
||||
BaseOpenAICompatibleHandler,
|
||||
ProviderEvent,
|
||||
ProviderResponseEnd,
|
||||
TextDelta,
|
||||
ToolCall,
|
||||
Usage,
|
||||
)
|
||||
from speech_to_speech.LLM.chat import Chat
|
||||
from speech_to_speech.LLM.compaction_prompt import CompactGenerateFn
|
||||
from speech_to_speech.utils.utils import _generate_id
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _to_chat_tools(req_tools: Any) -> list[ChatCompletionToolParam] | None:
|
||||
"""Convert Responses-API function tools to Chat-Completions tool format.
|
||||
|
||||
Responses tools are flat ``{type:"function", name, description, parameters}``;
|
||||
Chat Completions nests them under a ``function`` key. Items already in the
|
||||
nested form (or non-function tools) are passed through untouched.
|
||||
"""
|
||||
if not req_tools:
|
||||
return None
|
||||
chat_tools: list[ChatCompletionToolParam] = []
|
||||
for t in req_tools:
|
||||
d = t if isinstance(t, dict) else t.model_dump(exclude_none=True)
|
||||
if d.get("type") == "function" and "function" not in d:
|
||||
fn = FunctionDefinition(name=d["name"])
|
||||
if d.get("description") is not None:
|
||||
fn["description"] = d["description"]
|
||||
if d.get("parameters") is not None:
|
||||
fn["parameters"] = d["parameters"]
|
||||
chat_tools.append(ChatCompletionToolParam(type="function", function=fn))
|
||||
else:
|
||||
chat_tools.append(cast("ChatCompletionToolParam", d))
|
||||
return chat_tools
|
||||
|
||||
|
||||
def _to_chat_tool_choice(tool_choice: Any) -> ChatCompletionToolChoiceOptionParam:
|
||||
"""Convert a Responses-API tool_choice to Chat-Completions form.
|
||||
|
||||
The string forms ("auto"/"required"/"none") are identical across both APIs;
|
||||
only the forced-function object differs (flat ``name`` vs nested ``function``).
|
||||
"""
|
||||
if isinstance(tool_choice, dict) and tool_choice.get("type") == "function" and "name" in tool_choice:
|
||||
return ChatCompletionNamedToolChoiceParam(
|
||||
type="function", function=NamedToolChoiceFunction(name=tool_choice["name"])
|
||||
)
|
||||
if tool_choice is not None and not isinstance(tool_choice, (str, dict)):
|
||||
d = tool_choice.model_dump(exclude_none=True)
|
||||
if d.get("type") == "function" and "name" in d:
|
||||
return ChatCompletionNamedToolChoiceParam(type="function", function=NamedToolChoiceFunction(name=d["name"]))
|
||||
return cast("ChatCompletionToolChoiceOptionParam", d)
|
||||
return cast("ChatCompletionToolChoiceOptionParam", tool_choice)
|
||||
|
||||
|
||||
def _build_chat_optional_kwargs(req_tools: Any, req_tool_choice: Any) -> dict[str, Any]:
|
||||
"""Build Chat Completions tool arguments from the Responses-style session config."""
|
||||
optional_kwargs: dict[str, Any] = {}
|
||||
chat_tools = _to_chat_tools(req_tools)
|
||||
if chat_tools is not None:
|
||||
optional_kwargs["tools"] = chat_tools
|
||||
if req_tool_choice is not None:
|
||||
optional_kwargs["tool_choice"] = _to_chat_tool_choice(req_tool_choice)
|
||||
return optional_kwargs
|
||||
|
||||
|
||||
def _to_chat_content_part(
|
||||
part: dict[str, Any],
|
||||
audio_content_type: str = "input_audio",
|
||||
) -> ChatCompletionContentPartParam:
|
||||
"""Convert one Realtime/transformers content part to Chat Completions shape."""
|
||||
ptype = part.get("type")
|
||||
if ptype == "input_text":
|
||||
return ChatCompletionContentPartTextParam(type="text", text=part.get("text") or "")
|
||||
if ptype == "input_image":
|
||||
raw_url: Any = part.get("image_url")
|
||||
if isinstance(raw_url, dict):
|
||||
image_url = cast("ImageURL", raw_url)
|
||||
else:
|
||||
image_url = ImageURL(url=raw_url)
|
||||
detail = part.get("detail")
|
||||
if detail is not None:
|
||||
image_url["detail"] = detail
|
||||
return ChatCompletionContentPartImageParam(type="image_url", image_url=image_url)
|
||||
if ptype == "input_audio":
|
||||
audio_b64 = part.get("audio") or ""
|
||||
if audio_content_type == "audio_url":
|
||||
return cast(
|
||||
"ChatCompletionContentPartParam",
|
||||
{
|
||||
"type": "audio_url",
|
||||
"audio_url": {
|
||||
"url": f"data:audio/wav;base64,{audio_b64}",
|
||||
},
|
||||
},
|
||||
)
|
||||
return cast(
|
||||
"ChatCompletionContentPartParam",
|
||||
{
|
||||
"type": "input_audio",
|
||||
"input_audio": {
|
||||
"data": audio_b64,
|
||||
"format": "wav",
|
||||
},
|
||||
},
|
||||
)
|
||||
return cast("ChatCompletionContentPartParam", part)
|
||||
|
||||
|
||||
def _chat_messages(
|
||||
chat: Chat,
|
||||
audio_content_type: str = "input_audio",
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Serialise chat history, including media and tool messages, for Chat Completions."""
|
||||
messages = chat.to_transformers_chat()
|
||||
for message in messages:
|
||||
for tool_call in message.get("tool_calls") or []:
|
||||
fn = tool_call.get("function")
|
||||
if fn is not None and not isinstance(fn.get("arguments"), str):
|
||||
fn["arguments"] = json.dumps(fn.get("arguments") or {}, ensure_ascii=False)
|
||||
content = message.get("content")
|
||||
if isinstance(content, list):
|
||||
message["content"] = [
|
||||
_to_chat_content_part(part, audio_content_type=audio_content_type) for part in content
|
||||
]
|
||||
if message.get("role") == "tool":
|
||||
message.pop("name", None)
|
||||
return messages
|
||||
|
||||
|
||||
def _request_chat_completions(
|
||||
*,
|
||||
client: Any,
|
||||
model_name: str,
|
||||
messages: list[dict[str, Any]],
|
||||
stream: bool,
|
||||
extra_body: dict[str, Any] | None,
|
||||
timeout: Any,
|
||||
optional_kwargs: dict[str, Any],
|
||||
) -> Any:
|
||||
"""Issue a Chat Completions request with consistent streaming usage accounting."""
|
||||
create_kwargs = dict(optional_kwargs)
|
||||
if stream:
|
||||
create_kwargs["stream_options"] = {"include_usage": True}
|
||||
return client.chat.completions.create(
|
||||
model=model_name,
|
||||
messages=messages,
|
||||
stream=stream,
|
||||
extra_body=extra_body,
|
||||
timeout=timeout,
|
||||
**create_kwargs,
|
||||
)
|
||||
|
||||
|
||||
def _tool_calls_from_accum(tool_accum: dict[int, dict[str, str]]) -> Iterator[ToolCall]:
|
||||
"""Turn accumulated Chat Completions tool deltas into normalized tool-call events."""
|
||||
for index in sorted(tool_accum):
|
||||
entry = tool_accum[index]
|
||||
if not entry["name"]:
|
||||
continue
|
||||
yield ToolCall(
|
||||
item=ResponseFunctionToolCall(
|
||||
type="function_call",
|
||||
name=entry["name"],
|
||||
arguments=entry["args"] or "{}",
|
||||
call_id=_generate_id("call"),
|
||||
id=_generate_id("fc"),
|
||||
status="completed",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _chat_response_end(finish_reason: str) -> ProviderResponseEnd:
|
||||
if finish_reason == "length":
|
||||
return ProviderResponseEnd(status="incomplete", reason="max_output_tokens")
|
||||
if finish_reason == "content_filter":
|
||||
return ProviderResponseEnd(status="incomplete", reason="content_filter")
|
||||
return ProviderResponseEnd()
|
||||
|
||||
|
||||
def _iter_chat_stream_events(api_response: Stream[ChatCompletionChunk]) -> Iterator[ProviderEvent]:
|
||||
"""Normalize a streaming Chat Completions response."""
|
||||
tool_accum: dict[int, dict[str, str]] = {}
|
||||
usage: Usage | None = None
|
||||
text_segment = ""
|
||||
ending: ProviderResponseEnd | None = None
|
||||
|
||||
def flush_tools() -> Iterator[ProviderEvent]:
|
||||
nonlocal text_segment
|
||||
if text_segment:
|
||||
yield AssistantMessage(content=[AssistantContent(type="output_text", text=text_segment)])
|
||||
text_segment = ""
|
||||
yield from _tool_calls_from_accum(tool_accum)
|
||||
tool_accum.clear()
|
||||
|
||||
def accumulate_tools(tool_calls: Any) -> None:
|
||||
for tool_call in tool_calls or []:
|
||||
entry = tool_accum.setdefault(tool_call.index, {"name": "", "args": "", "id": ""})
|
||||
if tool_call.id:
|
||||
entry["id"] = tool_call.id
|
||||
if tool_call.function is not None:
|
||||
if tool_call.function.name:
|
||||
entry["name"] = tool_call.function.name
|
||||
if tool_call.function.arguments:
|
||||
entry["args"] += tool_call.function.arguments
|
||||
|
||||
for chunk in api_response:
|
||||
if chunk.usage is not None:
|
||||
usage = Usage(
|
||||
input_tokens=chunk.usage.prompt_tokens or 0,
|
||||
output_tokens=chunk.usage.completion_tokens or 0,
|
||||
)
|
||||
if not chunk.choices:
|
||||
continue
|
||||
finish_reason = getattr(chunk.choices[0], "finish_reason", None)
|
||||
if finish_reason is not None:
|
||||
ending = _chat_response_end(finish_reason)
|
||||
yield ending
|
||||
delta = chunk.choices[0].delta
|
||||
text_piece = delta.content or getattr(delta, "refusal", None)
|
||||
continuing_tool = bool(tool_accum)
|
||||
if continuing_tool:
|
||||
accumulate_tools(delta.tool_calls)
|
||||
if text_piece:
|
||||
if continuing_tool:
|
||||
yield from flush_tools()
|
||||
text_segment += text_piece
|
||||
yield TextDelta(text=text_piece)
|
||||
if not continuing_tool:
|
||||
accumulate_tools(delta.tool_calls)
|
||||
|
||||
if ending is None:
|
||||
logger.warning("Chat Completions stream ended without a finish_reason")
|
||||
if tool_accum and (ending is None or ending.status == "completed"):
|
||||
yield from flush_tools()
|
||||
if text_segment:
|
||||
yield AssistantMessage(content=[AssistantContent(type="output_text", text=text_segment)])
|
||||
if usage is not None:
|
||||
yield usage
|
||||
|
||||
|
||||
def _iter_chat_response_events(api_response: Any) -> Iterator[ProviderEvent]:
|
||||
"""Normalize a non-streaming Chat Completions response."""
|
||||
usage = api_response.usage
|
||||
if usage:
|
||||
yield Usage(input_tokens=usage.prompt_tokens or 0, output_tokens=usage.completion_tokens or 0)
|
||||
if api_response.choices:
|
||||
finish_reason = getattr(api_response.choices[0], "finish_reason", None)
|
||||
if finish_reason is not None:
|
||||
yield _chat_response_end(finish_reason)
|
||||
message = api_response.choices[0].message if api_response.choices else None
|
||||
if message is None:
|
||||
return
|
||||
raw_content = message.content or getattr(message, "refusal", None)
|
||||
if raw_content:
|
||||
yield AssistantMessage(content=[AssistantContent(type="output_text", text=raw_content)])
|
||||
yield TextDelta(text=raw_content)
|
||||
tool_accum: dict[int, dict[str, str]] = {}
|
||||
for tool_call in message.tool_calls or []:
|
||||
tool_accum[len(tool_accum)] = {
|
||||
"name": tool_call.function.name or "",
|
||||
"args": tool_call.function.arguments or "",
|
||||
"id": tool_call.id or "",
|
||||
}
|
||||
yield from _tool_calls_from_accum(tool_accum)
|
||||
|
||||
|
||||
class ChatCompletionsApiModelHandler(BaseOpenAICompatibleHandler):
|
||||
"""LLM handler that talks to an OpenAI-compatible ``/v1/chat/completions`` server.
|
||||
|
||||
Functionally mirrors :class:`ResponsesApiModelHandler` but uses the mature
|
||||
Chat Completions streaming tool-call protocol (``choices[].delta.tool_calls``)
|
||||
instead of ``/v1/responses``. This is the robust path for vLLM + Qwen tool
|
||||
calling. The conversation is serialised with :meth:`Chat.to_transformers_chat`,
|
||||
which already emits OpenAI chat messages including ``tool_calls``/``tool`` roles.
|
||||
"""
|
||||
|
||||
def warmup(self) -> None:
|
||||
logger.info(f"Warming up {self.__class__.__name__}")
|
||||
start = time.time()
|
||||
self.client.with_options(max_retries=WARMUP_MAX_RETRIES).chat.completions.create(
|
||||
model=self.model_name,
|
||||
messages=[
|
||||
{"role": "system", "content": "You are a helpful assistant"},
|
||||
{"role": "user", "content": "Hello"},
|
||||
],
|
||||
extra_body=self._extra_body,
|
||||
timeout=self.request_timeout,
|
||||
)
|
||||
end = time.time()
|
||||
logger.info(f"{self.__class__.__name__}: warmed up! time: {(end - start):.3f} s")
|
||||
|
||||
def _build_compaction_generate_fn(self) -> CompactGenerateFn:
|
||||
"""Return a generate fn that calls Chat Completions for compaction."""
|
||||
client = self.client
|
||||
model_name = self.model_name
|
||||
timeout = self.request_timeout
|
||||
extra_body = self._extra_body
|
||||
|
||||
def generate(system: str, user: str) -> str:
|
||||
response = client.chat.completions.create(
|
||||
model=model_name,
|
||||
messages=[
|
||||
{"role": "system", "content": system},
|
||||
{"role": "user", "content": user},
|
||||
],
|
||||
extra_body=extra_body,
|
||||
timeout=timeout,
|
||||
)
|
||||
return response.choices[0].message.content or ""
|
||||
|
||||
return generate
|
||||
|
||||
@staticmethod
|
||||
def _to_chat_content_part(
|
||||
part: dict[str, Any],
|
||||
audio_content_type: str = "input_audio",
|
||||
) -> ChatCompletionContentPartParam:
|
||||
return _to_chat_content_part(part, audio_content_type=audio_content_type)
|
||||
|
||||
@classmethod
|
||||
def _chat_messages(
|
||||
cls,
|
||||
chat: Chat,
|
||||
audio_content_type: str = "input_audio",
|
||||
) -> list[dict[str, Any]]:
|
||||
return _chat_messages(chat, audio_content_type=audio_content_type)
|
||||
|
||||
# ── base hooks ──────────────────────────────────────────────────────────--
|
||||
|
||||
def _serialize(self, active_chat: Chat) -> list[dict[str, Any]]:
|
||||
return self._chat_messages(active_chat, audio_content_type=self.audio_content_type)
|
||||
|
||||
def _build_optional_kwargs(self, req_tools: Any, req_tool_choice: Any) -> dict[str, Any]:
|
||||
return _build_chat_optional_kwargs(req_tools, req_tool_choice)
|
||||
|
||||
def _request(self, api_input: list[dict[str, Any]], optional_kwargs: dict[str, Any]) -> Any:
|
||||
return _request_chat_completions(
|
||||
client=self.client,
|
||||
model_name=self.model_name,
|
||||
messages=api_input,
|
||||
stream=self.stream,
|
||||
extra_body=self._extra_body,
|
||||
timeout=self.request_timeout,
|
||||
optional_kwargs=optional_kwargs,
|
||||
)
|
||||
|
||||
def _iter_stream_events(self, api_response: Stream[ChatCompletionChunk]) -> Iterator[ProviderEvent]:
|
||||
yield from _iter_chat_stream_events(api_response)
|
||||
|
||||
def _iter_response_events(self, api_response: Any) -> Iterator[ProviderEvent]:
|
||||
yield from _iter_chat_response_events(api_response)
|
||||
|
||||
@staticmethod
|
||||
def _tool_calls_from_accum(tool_accum: dict[int, dict[str, str]]) -> Iterator[ToolCall]:
|
||||
yield from _tool_calls_from_accum(tool_accum)
|
||||
|
||||
def on_session_end(self) -> None:
|
||||
logger.debug("Chat Completions API language model session state reset")
|
||||
@@ -0,0 +1,389 @@
|
||||
"""Explicit configured construction and lifecycle. Construction can load models."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import signal
|
||||
from copy import deepcopy
|
||||
from dataclasses import fields
|
||||
from ipaddress import ip_address
|
||||
from threading import Event, RLock, Thread, current_thread
|
||||
from time import monotonic
|
||||
from typing import TYPE_CHECKING, Any, Literal
|
||||
|
||||
from speech_to_speech.config import ConfigurationError, ResolvedConfig
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from speech_to_speech.api.openai_realtime.audio_client import RealtimeAudioClientConfig
|
||||
from speech_to_speech.api.openai_realtime.pipeline_unit import PipelineUnit
|
||||
from speech_to_speech.s2s_pipeline import ParsedArguments
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
_JOIN_TIMEOUT_S = 5.0
|
||||
|
||||
|
||||
class ConfiguredRuntimeError(RuntimeError):
|
||||
"""A runtime error that does not include provider diagnostics or credentials."""
|
||||
|
||||
|
||||
def _explicit(config: ResolvedConfig, *path: str) -> bool:
|
||||
return config.sources.get(path, "default") != "default"
|
||||
|
||||
|
||||
def _cleanup(resource: Any) -> None:
|
||||
try:
|
||||
cleanup = getattr(resource, "cleanup", None) or getattr(resource, "reset", None)
|
||||
if cleanup is None and hasattr(resource, "diarizer"):
|
||||
cleanup = resource.diarizer.reset
|
||||
if cleanup is not None:
|
||||
cleanup()
|
||||
except Exception:
|
||||
logger.warning("Configured resource cleanup failed")
|
||||
|
||||
|
||||
def _validate_counts(config: ResolvedConfig) -> None:
|
||||
if not config.pipelines:
|
||||
raise ConfigurationError("Select at least one pipeline definition.")
|
||||
for pipeline in config.pipelines.values():
|
||||
if type(pipeline.num_pipelines) is not int or pipeline.num_pipelines < 1:
|
||||
raise ConfigurationError("Use positive integer pipeline instance counts.")
|
||||
|
||||
|
||||
def _adapt(config: ResolvedConfig) -> dict[str, ParsedArguments]:
|
||||
from speech_to_speech import s2s_pipeline as pipeline_module
|
||||
from speech_to_speech.arguments_classes.local_audio_arguments import LocalAudioArguments
|
||||
from speech_to_speech.arguments_classes.module_arguments import ModuleArguments
|
||||
from speech_to_speech.arguments_classes.realtime_server_arguments import RealtimeServerArguments
|
||||
from speech_to_speech.arguments_classes.vad_arguments import VADHandlerArguments
|
||||
from speech_to_speech.backend_registry import LLM_BACKENDS, STT_BACKENDS, TTS_BACKENDS, BackendSelection
|
||||
|
||||
adapted = {}
|
||||
for name, pipeline in config.pipelines.items():
|
||||
options = deepcopy(pipeline.options)
|
||||
preset = (
|
||||
pipeline_module._mac_preset_defaults(pipeline.stages["llm"].backend)
|
||||
if options.get("mac_optimal_settings")
|
||||
else {}
|
||||
)
|
||||
for key, value in preset.items():
|
||||
if key in options and not _explicit(config, "pipelines", name, "options", key):
|
||||
options[key] = value
|
||||
options.update(
|
||||
stt=pipeline.stages["stt"].backend,
|
||||
llm_backend=pipeline.stages["llm"].backend,
|
||||
tts=pipeline.stages["tts"].backend,
|
||||
num_pipelines=pipeline.num_pipelines,
|
||||
log_level=config.runtime.get("log_level", "info"),
|
||||
log_transcripts=config.runtime.get("log_transcripts", False),
|
||||
torch_num_threads=config.runtime.get("torch_num_threads"),
|
||||
)
|
||||
if options.get("diarization") and options.get("diarization_model_name") is None:
|
||||
options["diarization_model_name"] = "nvidia/Nemotron-3-Diarization"
|
||||
selections = {}
|
||||
for kind, registry in (("stt", STT_BACKENDS), ("llm", LLM_BACKENDS), ("tts", TTS_BACKENDS)):
|
||||
stage = pipeline.stages[kind]
|
||||
spec = registry[stage.backend]
|
||||
settings = deepcopy(stage.settings)
|
||||
for key in {field.name for field in fields(spec.config_type)} & preset.keys():
|
||||
if not _explicit(config, "blocks", stage.block_id, "settings", key):
|
||||
settings[key] = deepcopy(preset[key])
|
||||
selections[kind] = BackendSelection(spec, spec.normalize(spec.config_type(**settings)))
|
||||
args = pipeline_module.ParsedArguments(
|
||||
module_kwargs=ModuleArguments(**options),
|
||||
realtime_server_kwargs=RealtimeServerArguments(**deepcopy(config.runtime.get("server", {}))),
|
||||
local_audio_kwargs=LocalAudioArguments(),
|
||||
vad_handler_kwargs=VADHandlerArguments(**deepcopy(pipeline.stages["vad"].settings)),
|
||||
stt_backend=selections["stt"],
|
||||
llm_backend=selections["llm"],
|
||||
tts_backend=selections["tts"],
|
||||
)
|
||||
try:
|
||||
pipeline_module.prepare_all_args(args)
|
||||
except ValueError:
|
||||
raise ConfigurationError("The selected pipeline settings are incompatible.") from None
|
||||
adapted[name] = args
|
||||
if pipeline_module.platform == "darwin" and sum(p.num_pipelines for p in config.pipelines.values()) > 1:
|
||||
for args in adapted.values():
|
||||
args.module_kwargs.enable_live_transcription = False
|
||||
return adapted
|
||||
|
||||
|
||||
def build_configured_client(config: ResolvedConfig, *, local: bool = False) -> RealtimeAudioClientConfig:
|
||||
"""Build independent packaged client settings and load explicitly selected tools."""
|
||||
from speech_to_speech.api.openai_realtime.audio_client import (
|
||||
RealtimeAudioClientConfig,
|
||||
build_session_update,
|
||||
load_realtime_tool_module,
|
||||
)
|
||||
|
||||
settings = deepcopy(config.client or {})
|
||||
module = settings.pop("tool_module", None)
|
||||
process_explicit = _explicit(config, "runtime", "log_transcripts")
|
||||
client_explicit = _explicit(config, "runtime", "client", "log_transcripts")
|
||||
process_log = config.runtime.get("log_transcripts", False)
|
||||
if process_explicit and client_explicit and settings.get("log_transcripts", False) != process_log:
|
||||
raise ConfigurationError("Process and client transcript settings must agree.")
|
||||
if process_explicit or not client_explicit:
|
||||
settings["log_transcripts"] = process_log
|
||||
if module and _explicit(config, "runtime", "client", "tools"):
|
||||
raise ConfigurationError("Use either a tool module or explicit client tools.")
|
||||
if local:
|
||||
if len(config.pipelines) != 1:
|
||||
raise ConfigurationError("Local startup requires exactly one pipeline definition.")
|
||||
server = config.runtime.get("server", {})
|
||||
host = server.get("host", "127.0.0.1")
|
||||
try:
|
||||
loopback = host == "localhost" or ip_address(host).is_loopback
|
||||
except ValueError:
|
||||
loopback = False
|
||||
if _explicit(config, "runtime", "server", "host") and not loopback:
|
||||
raise ConfigurationError("Local startup requires a loopback server host.")
|
||||
url = f"ws://127.0.0.1:{server.get('port', 8765)}/v1/realtime"
|
||||
if _explicit(config, "runtime", "client", "url") and settings.get("url") != url:
|
||||
raise ConfigurationError("Local client URL must match the loopback server port.")
|
||||
settings["url"] = url
|
||||
if not _explicit(config, "runtime", "client", "playback_buffer_ms"):
|
||||
pipeline = next(iter(config.pipelines.values()))
|
||||
settings["playback_buffer_ms"] = 196.0 if pipeline.stages["tts"].backend == "openai" else 0.0
|
||||
if module:
|
||||
tools, executor, create_response = load_realtime_tool_module(module)
|
||||
settings.update(tools=tools, tool_executor=executor)
|
||||
if not _explicit(config, "runtime", "client", "tool_response_create"):
|
||||
settings["tool_response_create"] = create_response
|
||||
try:
|
||||
client = RealtimeAudioClientConfig(**settings)
|
||||
build_session_update(client)
|
||||
except ValueError:
|
||||
raise ConfigurationError("Invalid packaged client settings or tool contract.") from None
|
||||
return client
|
||||
|
||||
|
||||
class ConfiguredRuntime:
|
||||
"""Own named worker pools and optional server/client resources without installing signals.
|
||||
|
||||
Running means managed threads have started. It does not indicate listener readiness.
|
||||
"""
|
||||
|
||||
def __init__(self, stop_event: Event) -> None:
|
||||
self.pools: dict[str, list[PipelineUnit]] = {}
|
||||
self.server: Any = None
|
||||
self.client: Any = None
|
||||
self.state = "constructed"
|
||||
self._caller_stop = stop_event
|
||||
self._stop = Event()
|
||||
self._events: list[Event] = []
|
||||
self._resources: list[Any] = []
|
||||
self._handlers: list[Any] = []
|
||||
self._threads: list[Thread] = []
|
||||
self._started: set[int] = set()
|
||||
self._monitor: Thread | None = None
|
||||
self._failure: str | None = None
|
||||
self._lock = RLock()
|
||||
|
||||
def _signal_stop(self) -> None:
|
||||
self._stop.set()
|
||||
for event in self._events:
|
||||
event.set()
|
||||
|
||||
def _run(self, handler: Any) -> None:
|
||||
try:
|
||||
if handler is self.client:
|
||||
from speech_to_speech.api.openai_realtime.audio_client import listen_and_play_realtime
|
||||
|
||||
asyncio.run(listen_and_play_realtime(handler.config, stop_event=handler.stop_event))
|
||||
else:
|
||||
handler.run()
|
||||
except BaseException:
|
||||
self._failure = "A configured worker, listener, or client failed."
|
||||
self._signal_stop()
|
||||
finally:
|
||||
if handler is self.server or handler is self.client:
|
||||
self._signal_stop()
|
||||
|
||||
def _watch(self) -> None:
|
||||
while not self._stop.wait(0.05):
|
||||
if self._caller_stop.is_set() or any(event.is_set() for event in self._events):
|
||||
self._signal_stop()
|
||||
|
||||
def start(self) -> None:
|
||||
with self._lock:
|
||||
if self.state == "running":
|
||||
return
|
||||
if self.state != "constructed":
|
||||
raise ConfiguredRuntimeError("A stopped or failed configured runtime cannot restart.")
|
||||
if self._caller_stop.is_set():
|
||||
self.stop()
|
||||
return
|
||||
try:
|
||||
for handler in self._handlers:
|
||||
if self._stop.is_set():
|
||||
raise ConfiguredRuntimeError("Configured startup stopped before completion.")
|
||||
thread = Thread(target=self._run, args=(handler,))
|
||||
thread.start()
|
||||
self._threads.append(thread)
|
||||
self._started.add(id(handler))
|
||||
monitor = Thread(target=self._watch, daemon=True)
|
||||
monitor.start()
|
||||
self._monitor = monitor
|
||||
self.state = "running"
|
||||
except BaseException:
|
||||
self._failure = "Configured thread startup failed."
|
||||
self.stop()
|
||||
raise ConfiguredRuntimeError(self._failure) from None
|
||||
|
||||
def stop(self) -> None:
|
||||
with self._lock:
|
||||
if self.state in {"stopped", "failed"}:
|
||||
return
|
||||
self.state = "stopping"
|
||||
self._signal_stop()
|
||||
deadline = monotonic() + _JOIN_TIMEOUT_S
|
||||
for thread in self._threads:
|
||||
if thread is not current_thread():
|
||||
thread.join(max(0.0, deadline - monotonic()))
|
||||
if self._monitor is not None and self._monitor is not current_thread():
|
||||
self._monitor.join(max(0.0, deadline - monotonic()))
|
||||
survivors = sum(thread.is_alive() for thread in self._threads)
|
||||
if self._monitor is not None and self._monitor.is_alive():
|
||||
survivors += 1
|
||||
if survivors:
|
||||
logger.warning("Configured shutdown has %d surviving threads", survivors)
|
||||
raise ConfiguredRuntimeError("Configured shutdown has threads still running.")
|
||||
for resource in reversed(self._resources):
|
||||
if id(resource) not in self._started:
|
||||
_cleanup(resource)
|
||||
self.pools.clear()
|
||||
self.server = self.client = None
|
||||
self._resources.clear()
|
||||
self._handlers.clear()
|
||||
self._threads.clear()
|
||||
self._started.clear()
|
||||
self._events.clear()
|
||||
self._monitor = None
|
||||
self.state = "failed" if self._failure else "stopped"
|
||||
|
||||
def wait(self) -> None:
|
||||
if self.state == "constructed":
|
||||
return
|
||||
while self.state == "running" and any(thread.is_alive() for thread in self._threads):
|
||||
if self._caller_stop.wait(0.05) or self._stop.is_set():
|
||||
break
|
||||
self.stop()
|
||||
if self._failure:
|
||||
raise ConfiguredRuntimeError(self._failure)
|
||||
|
||||
|
||||
def build_configured_runtime(config: ResolvedConfig, stop_event: Event) -> ConfiguredRuntime:
|
||||
"""Construct independent named workers. Models can initialize before start()."""
|
||||
_validate_counts(config)
|
||||
return _build_runtime(_adapt(config), stop_event)
|
||||
|
||||
|
||||
def _build_runtime(arguments: dict[str, ParsedArguments], stop_event: Event) -> ConfiguredRuntime:
|
||||
from speech_to_speech.s2s_pipeline import _build_pipeline_unit
|
||||
|
||||
result = ConfiguredRuntime(stop_event)
|
||||
index = 0
|
||||
try:
|
||||
for name, args in arguments.items():
|
||||
event = Event()
|
||||
result._events.append(event)
|
||||
result.pools[name] = []
|
||||
for _ in range(args.module_kwargs.num_pipelines):
|
||||
unit = _build_pipeline_unit(
|
||||
index=index,
|
||||
stop_event=event,
|
||||
module_kwargs=deepcopy(args.module_kwargs),
|
||||
vad_handler_kwargs=deepcopy(args.vad_handler_kwargs),
|
||||
stt_backend=args.stt_backend.copy_for_pipeline(),
|
||||
llm_backend=args.llm_backend.copy_for_pipeline(),
|
||||
tts_backend=args.tts_backend.copy_for_pipeline(),
|
||||
resource_ledger=result._resources,
|
||||
)
|
||||
result.pools[name].append(unit)
|
||||
result._handlers.extend(unit.handlers)
|
||||
index += 1
|
||||
except BaseException as exc:
|
||||
result._failure = f"Configured pipeline {name} construction failed."
|
||||
result.stop()
|
||||
raise ConfiguredRuntimeError(result._failure) from exc
|
||||
return result
|
||||
|
||||
|
||||
def build_configured_server(config: ResolvedConfig, stop_event: Event, *, local: bool = False) -> ConfiguredRuntime:
|
||||
"""Publish one definition through a server, with an optional loopback client."""
|
||||
_validate_counts(config)
|
||||
if len(config.pipelines) != 1:
|
||||
raise ConfigurationError("Serving requires exactly one selected pipeline definition.")
|
||||
client_config = build_configured_client(config, local=True) if local else None
|
||||
arguments = _adapt(config)
|
||||
result = _build_runtime(arguments, stop_event)
|
||||
try:
|
||||
from speech_to_speech.api.openai_realtime.audio_client import RealtimeAudioClient
|
||||
from speech_to_speech.api.openai_realtime.server import RealtimeServer
|
||||
from speech_to_speech.s2s_pipeline import build_llm_proxy_config
|
||||
|
||||
args = next(iter(arguments.values()))
|
||||
event = result._events[0]
|
||||
result.server = RealtimeServer(
|
||||
stop_event=event,
|
||||
pool=next(iter(result.pools.values())),
|
||||
host="127.0.0.1" if local else args.realtime_server_kwargs.host,
|
||||
port=args.realtime_server_kwargs.port,
|
||||
llm_proxy_config=build_llm_proxy_config(args.module_kwargs, args.llm_backend)
|
||||
if args.module_kwargs.enable_llm_proxy
|
||||
else None,
|
||||
)
|
||||
result._resources.append(result.server)
|
||||
result._handlers.append(result.server)
|
||||
if client_config is not None:
|
||||
result.client = RealtimeAudioClient(event, client_config)
|
||||
result._resources.append(result.client)
|
||||
result._handlers.append(result.client)
|
||||
except BaseException as exc:
|
||||
result._failure = "Configured server construction failed."
|
||||
result.stop()
|
||||
raise ConfiguredRuntimeError(result._failure) from exc
|
||||
return result
|
||||
|
||||
|
||||
def run_configured_command(command: Literal["serve", "local", "talk"], config: ResolvedConfig) -> None:
|
||||
"""Own CLI signal handlers and always stop constructed resources."""
|
||||
from speech_to_speech.pipeline.transcript_logging import set_log_transcripts, warn_if_log_transcripts_enabled
|
||||
|
||||
stop_event = Event()
|
||||
result: ConfiguredRuntime | None = None
|
||||
previous = {sig: signal.getsignal(sig) for sig in (signal.SIGINT, signal.SIGTERM)}
|
||||
try:
|
||||
for sig in previous:
|
||||
signal.signal(sig, lambda *_: stop_event.set())
|
||||
if command == "talk":
|
||||
from speech_to_speech.api.openai_realtime.audio_client import listen_and_play_realtime
|
||||
|
||||
client = build_configured_client(config)
|
||||
logging.basicConfig(level=config.runtime.get("log_level", "info").upper())
|
||||
set_log_transcripts(client.log_transcripts)
|
||||
warn_if_log_transcripts_enabled()
|
||||
asyncio.run(listen_and_play_realtime(client, stop_event=stop_event))
|
||||
else:
|
||||
from speech_to_speech.s2s_pipeline import setup_logger
|
||||
|
||||
setup_logger(config.runtime.get("log_level", "info"))
|
||||
result = build_configured_server(config, stop_event, local=command == "local")
|
||||
set_log_transcripts(
|
||||
result.client.config.log_transcripts
|
||||
if command == "local"
|
||||
else config.runtime.get("log_transcripts", False)
|
||||
)
|
||||
warn_if_log_transcripts_enabled()
|
||||
result.start()
|
||||
result.wait()
|
||||
finally:
|
||||
stop_event.set()
|
||||
try:
|
||||
if result is not None:
|
||||
result.stop()
|
||||
finally:
|
||||
for sig, handler in previous.items():
|
||||
signal.signal(sig, handler)
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"commit": "619e3fe4f71d1c6f35c15870d588a3638de34722",
|
||||
"files": {
|
||||
"chat.py.source": {
|
||||
"path": "src/speech_to_speech/LLM/chat_completions_language_model.py",
|
||||
"sha256": "ce5e0c05881288f20e236c549cc7b85ae08603667b50dab38d21a23636ed1015"
|
||||
},
|
||||
"base.py.source": {
|
||||
"path": "src/speech_to_speech/LLM/base_openai_compatible_language_model.py",
|
||||
"sha256": "238c8cfaa2a15de75c1ecc6f4eb63e9b103216eed6be2f35538d1d0d41882609"
|
||||
},
|
||||
"pipeline.py.source": {
|
||||
"path": "src/speech_to_speech/s2s_pipeline.py",
|
||||
"sha256": "6daf4311d8e0d610dc16d0e3eb0992b564572f99729993993ee78e07b37866e7"
|
||||
},
|
||||
"lifecycle.py.source": {
|
||||
"path": "src/speech_to_speech/configured_runtime.py",
|
||||
"sha256": "7d3408991b9cc8d20c20051521e5d106f4831d018251c92a71c8ba75243613a6"
|
||||
},
|
||||
"LICENSE": {
|
||||
"path": "LICENSE",
|
||||
"sha256": "1db290a6ce5d11e74a63c05adbc1490da08688a300d6b4b19818bcfc4901af46"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,843 @@
|
||||
import argparse
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import signal
|
||||
import sys
|
||||
from copy import deepcopy
|
||||
from dataclasses import dataclass, fields, replace
|
||||
from pathlib import Path
|
||||
from queue import Queue
|
||||
from sys import modules, platform
|
||||
from threading import Event
|
||||
from types import FrameType
|
||||
from typing import Any, Literal, Optional, Sequence
|
||||
|
||||
import nltk
|
||||
import torch
|
||||
from rich.console import Console
|
||||
from transformers import HfArgumentParser
|
||||
|
||||
from speech_to_speech.api.openai_realtime.pipeline_unit import PipelineUnit
|
||||
from speech_to_speech.arguments_classes.language_model_arguments import MLX_DEFAULT_LM_MODEL
|
||||
from speech_to_speech.arguments_classes.local_audio_arguments import LocalAudioArguments
|
||||
from speech_to_speech.arguments_classes.module_arguments import ModuleArguments
|
||||
from speech_to_speech.arguments_classes.realtime_server_arguments import (
|
||||
LocalRealtimeServerArguments,
|
||||
RealtimeServerArguments,
|
||||
)
|
||||
from speech_to_speech.arguments_classes.vad_arguments import VADHandlerArguments
|
||||
from speech_to_speech.backend_registry import (
|
||||
LLM_BACKENDS,
|
||||
STT_BACKENDS,
|
||||
TTS_BACKENDS,
|
||||
BackendSelection,
|
||||
BackendSpec,
|
||||
HandlerContext,
|
||||
create_backend_handler,
|
||||
)
|
||||
from speech_to_speech.pipeline.cancel_scope import CancelScope
|
||||
from speech_to_speech.pipeline.queue_types import (
|
||||
AudioInItem,
|
||||
AudioOutItem,
|
||||
LMOutItem,
|
||||
STTOutItem,
|
||||
TextEventItem,
|
||||
TextPromptItem,
|
||||
TTSInItem,
|
||||
VADOutItem,
|
||||
)
|
||||
from speech_to_speech.pipeline.speculative_turns import SpeculativeTurnTracker
|
||||
from speech_to_speech.pipeline.transcript_logging import (
|
||||
set_log_transcripts,
|
||||
warn_if_log_transcripts_enabled,
|
||||
)
|
||||
from speech_to_speech.pipeline.turn_latency import TurnLatencyStore
|
||||
from speech_to_speech.STT.transcription_notifier import TranscriptionNotifier
|
||||
from speech_to_speech.utils.thread_manager import ThreadManager
|
||||
from speech_to_speech.utils.utils import resolve_device
|
||||
from speech_to_speech.VAD.vad_handler import VADHandler
|
||||
|
||||
# Ensure that the necessary NLTK resources are available
|
||||
try:
|
||||
nltk.data.find("tokenizers/punkt_tab")
|
||||
except (LookupError, OSError):
|
||||
nltk.download("punkt_tab")
|
||||
try:
|
||||
nltk.data.find("taggers/averaged_perceptron_tagger_eng")
|
||||
except (LookupError, OSError):
|
||||
nltk.download("averaged_perceptron_tagger_eng")
|
||||
|
||||
# caching allows ~50% compilation time reduction
|
||||
# see https://docs.google.com/document/d/1y5CRfMLdwEoF1nTk9q8qEu1mgMUuUtvhklPKJ2emLU8/edit#heading=h.o2asbxsrp1ma
|
||||
CURRENT_DIR = Path(__file__).resolve().parent
|
||||
os.environ["TORCHINDUCTOR_CACHE_DIR"] = os.path.join(CURRENT_DIR, "tmp")
|
||||
|
||||
console = Console()
|
||||
logger = logging.getLogger(__name__)
|
||||
logging.getLogger("numba").setLevel(logging.WARNING) # quiet down numba logs
|
||||
|
||||
OPENAI_TTS_PLAYBACK_BUFFER_MS = 196.0
|
||||
|
||||
|
||||
def _mac_preset_defaults(llm_backend: str) -> dict[str, Any]:
|
||||
"""Return macOS parser defaults, leaving explicit arguments free to override them."""
|
||||
|
||||
defaults: dict[str, Any] = {
|
||||
"stt": "parakeet-tdt",
|
||||
"llm_backend": "mlx-lm",
|
||||
"tts": "qwen3",
|
||||
"stt_device": "mps",
|
||||
"diarization_device": "mps",
|
||||
"paraformer_stt_device": "mps",
|
||||
"facebook_mms_device": "mps",
|
||||
"qwen3_tts_device": "mps",
|
||||
}
|
||||
if llm_backend not in {"responses-api", "chat-completions"}:
|
||||
defaults["llm_device"] = "mps"
|
||||
if llm_backend == "mlx-lm":
|
||||
defaults["model_name"] = MLX_DEFAULT_LM_MODEL
|
||||
return defaults
|
||||
|
||||
|
||||
@dataclass
|
||||
class ParsedArguments:
|
||||
module_kwargs: ModuleArguments
|
||||
realtime_server_kwargs: RealtimeServerArguments
|
||||
local_audio_kwargs: LocalAudioArguments
|
||||
vad_handler_kwargs: VADHandlerArguments
|
||||
stt_backend: BackendSelection
|
||||
llm_backend: BackendSelection
|
||||
tts_backend: BackendSelection
|
||||
|
||||
|
||||
def build_llm_proxy_config(
|
||||
module_kwargs: ModuleArguments,
|
||||
llm_backend: BackendSelection,
|
||||
) -> Any:
|
||||
"""Build proxy settings from the selected LLM's normalized configuration."""
|
||||
from speech_to_speech.api.openai_realtime.llm_proxy import LLMProxyConfig
|
||||
|
||||
if not llm_backend.spec.capabilities.supports_llm_proxy:
|
||||
supported = ", ".join(name for name, spec in LLM_BACKENDS.items() if spec.capabilities.supports_llm_proxy)
|
||||
raise ValueError(
|
||||
f"The LLM proxy requires a backend with proxy support; choose one of: {supported}. "
|
||||
f"Got {llm_backend.name!r}."
|
||||
)
|
||||
config = llm_backend.config
|
||||
return LLMProxyConfig(
|
||||
enabled=module_kwargs.enable_llm_proxy,
|
||||
llm_backend=module_kwargs.llm_backend,
|
||||
upstream_base_url=config["base_url"],
|
||||
upstream_api_key=config["api_key"],
|
||||
model_name=config["model_name"],
|
||||
connect_timeout_s=module_kwargs.llm_proxy_connect_timeout_s,
|
||||
)
|
||||
|
||||
|
||||
def _parse_selected_cli_configs(
|
||||
parser: HfArgumentParser,
|
||||
pipeline_args: list[str],
|
||||
selected_specs: Sequence[BackendSpec],
|
||||
) -> tuple[Any, ...]:
|
||||
"""Parse selected configs while accepting legacy options for inactive backends."""
|
||||
|
||||
*parsed, remaining = parser.parse_args_into_dataclasses(
|
||||
args=pipeline_args,
|
||||
return_remaining_strings=True,
|
||||
)
|
||||
if not remaining:
|
||||
return tuple(parsed)
|
||||
|
||||
selected_types = {spec.config_type for spec in selected_specs}
|
||||
inactive_types: list[type[Any]] = []
|
||||
for registry in (STT_BACKENDS, LLM_BACKENDS, TTS_BACKENDS):
|
||||
for spec in registry.values():
|
||||
if spec.config_type not in selected_types and spec.config_type not in inactive_types:
|
||||
inactive_types.append(spec.config_type)
|
||||
|
||||
compatibility_parser = HfArgumentParser(
|
||||
tuple(inactive_types), # type: ignore[arg-type]
|
||||
add_help=False,
|
||||
allow_abbrev=False,
|
||||
conflict_handler="resolve",
|
||||
)
|
||||
known_options = compatibility_parser._option_string_actions
|
||||
_, unknown = compatibility_parser.parse_known_args(remaining)
|
||||
if unknown:
|
||||
raise ValueError(f"Some specified arguments are not used by the HfArgumentParser: {unknown}")
|
||||
|
||||
ignored_options = sorted({token.split("=", 1)[0] for token in remaining if token.split("=", 1)[0] in known_options})
|
||||
logger.warning(
|
||||
"Ignoring options for inactive backends: %s",
|
||||
", ".join(ignored_options),
|
||||
)
|
||||
return tuple(parsed)
|
||||
|
||||
|
||||
def parse_arguments(
|
||||
argv: Sequence[str] | None = None,
|
||||
*,
|
||||
command: Literal["serve", "local"] = "serve",
|
||||
) -> ParsedArguments:
|
||||
module_defaults = ModuleArguments()
|
||||
assert module_defaults.stt is not None
|
||||
assert module_defaults.llm_backend is not None
|
||||
assert module_defaults.tts is not None
|
||||
|
||||
pipeline_args = list(sys.argv[1:] if argv is None else argv)
|
||||
_is_json = len(pipeline_args) == 1 and pipeline_args[0].endswith(".json")
|
||||
pipeline_json: dict[str, Any] | None = None
|
||||
if _is_json:
|
||||
with open(pipeline_args[0]) as _f:
|
||||
pipeline_json = json.load(_f)
|
||||
_mac_preset_enabled = bool(pipeline_json.get("mac_optimal_settings", False))
|
||||
_llm_name = pipeline_json.get("llm_backend") or (
|
||||
"mlx-lm" if _mac_preset_enabled else module_defaults.llm_backend
|
||||
)
|
||||
if _mac_preset_enabled:
|
||||
pipeline_json = {**_mac_preset_defaults(_llm_name), **pipeline_json}
|
||||
_stt_name = pipeline_json.get("stt") or module_defaults.stt
|
||||
_tts_name = pipeline_json.get("tts") or module_defaults.tts
|
||||
else:
|
||||
_pre = argparse.ArgumentParser(prog=f"speech-to-speech {command}", add_help=False)
|
||||
_pre.add_argument("--mac-optimal-settings", action="store_true")
|
||||
_pre.add_argument("--stt", choices=tuple(STT_BACKENDS))
|
||||
_pre.add_argument("--llm_backend", "--llm-backend", choices=tuple(LLM_BACKENDS))
|
||||
_pre.add_argument("--tts", choices=tuple(TTS_BACKENDS))
|
||||
_pre_args = _pre.parse_known_args(pipeline_args)[0]
|
||||
_mac_preset_enabled = _pre_args.mac_optimal_settings
|
||||
_stt_name = _pre_args.stt or module_defaults.stt
|
||||
_llm_name = _pre_args.llm_backend or ("mlx-lm" if _mac_preset_enabled else module_defaults.llm_backend)
|
||||
_tts_name = _pre_args.tts or module_defaults.tts
|
||||
|
||||
selected_specs = []
|
||||
for registry, name in (
|
||||
(STT_BACKENDS, _stt_name),
|
||||
(LLM_BACKENDS, _llm_name),
|
||||
(TTS_BACKENDS, _tts_name),
|
||||
):
|
||||
try:
|
||||
selected_specs.append(registry[name])
|
||||
except KeyError as exc:
|
||||
choices = ", ".join(registry)
|
||||
raise ValueError(f"Unsupported backend {name!r}; choose one of: {choices}.") from exc
|
||||
|
||||
logger.debug(
|
||||
"Backend pre-parse: stt=%s, llm=%s, tts=%s",
|
||||
_stt_name,
|
||||
_llm_name,
|
||||
_tts_name,
|
||||
)
|
||||
|
||||
server_arguments_class = RealtimeServerArguments if command == "serve" else LocalRealtimeServerArguments
|
||||
argument_classes: list[type[Any]] = [
|
||||
ModuleArguments,
|
||||
server_arguments_class,
|
||||
]
|
||||
if command == "local":
|
||||
argument_classes.append(LocalAudioArguments)
|
||||
argument_classes.extend(
|
||||
[
|
||||
VADHandlerArguments,
|
||||
*(spec.config_type for spec in selected_specs),
|
||||
]
|
||||
)
|
||||
parser = HfArgumentParser(tuple(argument_classes), prog=f"speech-to-speech {command}") # type: ignore[arg-type]
|
||||
mac_action = parser._option_string_actions.pop("--mac_optimal_settings")
|
||||
mac_action.option_strings = [option for option in mac_action.option_strings if option != "--mac_optimal_settings"]
|
||||
if _mac_preset_enabled:
|
||||
parser.set_defaults(**_mac_preset_defaults(_llm_name))
|
||||
|
||||
if _is_json:
|
||||
assert pipeline_json is not None
|
||||
parsed = parser.parse_dict(pipeline_json, allow_extra_keys=True)
|
||||
else:
|
||||
parsed = _parse_selected_cli_configs(parser, pipeline_args, selected_specs)
|
||||
|
||||
# Build a {type: instance} lookup so field assignment is order-independent.
|
||||
by_type: dict[type, Any] = {type(obj): obj for obj in parsed}
|
||||
logger.debug("Parsed %d argument classes: %s", len(by_type), [t.__name__ for t in by_type])
|
||||
if command == "serve":
|
||||
realtime_server_kwargs = by_type[RealtimeServerArguments]
|
||||
else:
|
||||
realtime_server_kwargs = RealtimeServerArguments(
|
||||
host="127.0.0.1",
|
||||
port=by_type[LocalRealtimeServerArguments].port,
|
||||
)
|
||||
|
||||
module_kwargs = by_type[ModuleArguments]
|
||||
if module_kwargs.diarization and module_kwargs.diarization_model_name is None:
|
||||
module_kwargs.diarization_model_name = "nvidia/Nemotron-3-Diarization"
|
||||
module_kwargs.stt = _stt_name
|
||||
module_kwargs.llm_backend = _llm_name
|
||||
module_kwargs.tts = _tts_name
|
||||
args = ParsedArguments(
|
||||
module_kwargs=module_kwargs,
|
||||
realtime_server_kwargs=realtime_server_kwargs,
|
||||
local_audio_kwargs=by_type.get(LocalAudioArguments, LocalAudioArguments()),
|
||||
vad_handler_kwargs=by_type[VADHandlerArguments],
|
||||
stt_backend=BackendSelection(
|
||||
selected_specs[0], selected_specs[0].normalize(by_type[selected_specs[0].config_type])
|
||||
),
|
||||
llm_backend=BackendSelection(
|
||||
selected_specs[1], selected_specs[1].normalize(by_type[selected_specs[1].config_type])
|
||||
),
|
||||
tts_backend=BackendSelection(
|
||||
selected_specs[2], selected_specs[2].normalize(by_type[selected_specs[2].config_type])
|
||||
),
|
||||
)
|
||||
return args
|
||||
|
||||
|
||||
def setup_logger(log_level: str) -> None:
|
||||
global logger
|
||||
from speech_to_speech.pipeline.log_context import PipelineLogFilter
|
||||
|
||||
logging.basicConfig(
|
||||
level=log_level.upper(),
|
||||
format="%(asctime)s - %(pipeline_prefix)s%(name)s - %(levelname)s - %(message)s",
|
||||
)
|
||||
# Attach the filter to every existing handler so each LogRecord gets a
|
||||
# `pipeline_prefix` attribute (matching the format string above).
|
||||
pipeline_filter = PipelineLogFilter()
|
||||
for h in logging.getLogger().handlers:
|
||||
h.addFilter(pipeline_filter)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# torch compile logs
|
||||
if log_level == "debug":
|
||||
torch._logging.set_logs(graph_breaks=True, recompiles=True, cudagraphs=True)
|
||||
|
||||
|
||||
def check_mac_settings(module_kwargs: ModuleArguments) -> None:
|
||||
if platform == "darwin":
|
||||
if module_kwargs.device == "cuda":
|
||||
raise ValueError("Cannot use CUDA on macOS. Please set the device to 'cpu' or 'mps'.")
|
||||
if module_kwargs.llm_backend != "mlx-lm":
|
||||
logger.warning(
|
||||
"For macOS users, it is recommended to use mlx-lm. You can activate it by passing --llm_backend mlx-lm."
|
||||
)
|
||||
if module_kwargs.tts not in ("pocket", "kokoro", "omnivoice", "qwen3"):
|
||||
logger.warning(
|
||||
"For macOS users, it is recommended to use qwen3 for TTS "
|
||||
"(pocket, kokoro, and omnivoice are also valid options)."
|
||||
)
|
||||
|
||||
|
||||
def validate_torch_num_threads(value: Any) -> None:
|
||||
if value is not None and (type(value) is not int or value < 1):
|
||||
raise ValueError(f"--torch_num_threads must be a positive integer; got {value!r}.")
|
||||
|
||||
|
||||
def apply_torch_num_threads(module_kwargs: ModuleArguments) -> None:
|
||||
"""Apply an explicit --torch_num_threads; with it unset, leave PyTorch's thread count alone."""
|
||||
if module_kwargs.torch_num_threads is not None:
|
||||
torch.set_num_threads(module_kwargs.torch_num_threads)
|
||||
|
||||
|
||||
def prepare_module_args(module_kwargs: ModuleArguments, llm_backend: BackendSelection) -> None:
|
||||
validate_torch_num_threads(module_kwargs.torch_num_threads)
|
||||
if module_kwargs.diarization_model_name and module_kwargs.stt == "none":
|
||||
raise ValueError("Speaker-aware conversation requires an STT backend; --stt none does not produce transcripts.")
|
||||
if module_kwargs.diarization_model_name and not 0 < module_kwargs.diarization_threshold < 1:
|
||||
raise ValueError("--diarization_threshold must be between 0 and 1.")
|
||||
if module_kwargs.tts is None:
|
||||
module_kwargs.tts = "qwen3"
|
||||
if module_kwargs.stt == "none" and not llm_backend.spec.capabilities.supports_audio_input:
|
||||
supported = ", ".join(name for name, spec in LLM_BACKENDS.items() if spec.capabilities.supports_audio_input)
|
||||
raise ValueError(f"--stt none requires an audio-input LLM backend; choose one of: {supported}.")
|
||||
if module_kwargs.enable_llm_proxy and not llm_backend.spec.capabilities.supports_llm_proxy:
|
||||
supported = ", ".join(name for name, spec in LLM_BACKENDS.items() if spec.capabilities.supports_llm_proxy)
|
||||
raise ValueError(
|
||||
f"The LLM proxy requires a backend with proxy support; choose one of: {supported}. "
|
||||
f"Got {llm_backend.name!r}."
|
||||
)
|
||||
if platform == "darwin":
|
||||
check_mac_settings(module_kwargs)
|
||||
|
||||
|
||||
def prepare_all_args(args: ParsedArguments) -> None:
|
||||
"""Validate selectors and apply the global device to selected configs only."""
|
||||
|
||||
prepare_module_args(args.module_kwargs, args.llm_backend)
|
||||
if args.module_kwargs.device is None:
|
||||
return
|
||||
for field_name in ("stt_backend", "llm_backend", "tts_backend"):
|
||||
selection = getattr(args, field_name)
|
||||
if "device" not in selection.config:
|
||||
continue
|
||||
config = {**selection.config, "device": args.module_kwargs.device}
|
||||
setattr(args, field_name, replace(selection, config=config))
|
||||
|
||||
|
||||
def _build_handlers(
|
||||
*,
|
||||
stop_event: Event,
|
||||
should_listen: Event,
|
||||
recv_audio_chunks_queue: Queue[AudioInItem],
|
||||
spoken_prompt_queue: Queue[VADOutItem],
|
||||
stt_output_queue: Queue[STTOutItem],
|
||||
text_prompt_queue: Queue[TextPromptItem],
|
||||
lm_response_queue: Queue[LMOutItem],
|
||||
lm_processed_queue: Queue[TTSInItem],
|
||||
send_audio_chunks_queue: Queue[AudioOutItem],
|
||||
text_output_queue: Queue[TextEventItem],
|
||||
module_kwargs: ModuleArguments,
|
||||
vad_handler_kwargs: VADHandlerArguments,
|
||||
stt_backend: BackendSelection,
|
||||
llm_backend: BackendSelection,
|
||||
tts_backend: BackendSelection,
|
||||
speculative_turns: SpeculativeTurnTracker,
|
||||
cancel_scope: CancelScope,
|
||||
pipeline_index: int,
|
||||
resource_ledger: list[Any] | None = None,
|
||||
) -> list[Any]:
|
||||
"""Build a handler chain: VAD → STT/AudioInput → LM → TTS."""
|
||||
from speech_to_speech.LLM.lm_output_processor import LMOutputProcessor
|
||||
|
||||
vad = VADHandler(
|
||||
stop_event,
|
||||
queue_in=recv_audio_chunks_queue,
|
||||
queue_out=spoken_prompt_queue,
|
||||
setup_args=(should_listen,),
|
||||
setup_kwargs={
|
||||
**{
|
||||
config_field.name: deepcopy(getattr(vad_handler_kwargs, config_field.name))
|
||||
for config_field in fields(vad_handler_kwargs)
|
||||
},
|
||||
"text_output_queue": text_output_queue,
|
||||
"speculative_turns": speculative_turns,
|
||||
},
|
||||
)
|
||||
|
||||
if resource_ledger is not None:
|
||||
resource_ledger.append(vad)
|
||||
# Loading Silero sets PyTorch to one thread for the whole process. Re-apply an explicit
|
||||
# --torch_num_threads after every VAD build, before the other models load and warm up.
|
||||
apply_torch_num_threads(module_kwargs)
|
||||
|
||||
side_handlers: list[Any] = []
|
||||
if module_kwargs.diarization_model_name:
|
||||
from speech_to_speech.diarization import StreamingDiarizer
|
||||
from speech_to_speech.diarization.streaming import DIARIZATION_DEVICES
|
||||
from speech_to_speech.diarization.worker import DiarizationWorker
|
||||
|
||||
diarization_device = resolve_device(
|
||||
module_kwargs.device or module_kwargs.diarization_device,
|
||||
DIARIZATION_DEVICES,
|
||||
"Nemotron diarization",
|
||||
)
|
||||
if diarization_device == "cpu":
|
||||
logger.warning(
|
||||
"Diarization is using CPU; sustained speech can outpace inference and disable speaker labels "
|
||||
"until reconnect. CUDA or MPS is recommended for live sessions."
|
||||
)
|
||||
diarizer = StreamingDiarizer.from_pretrained(
|
||||
module_kwargs.diarization_model_name,
|
||||
revision=module_kwargs.diarization_revision,
|
||||
device=diarization_device,
|
||||
dtype=module_kwargs.diarization_dtype,
|
||||
streaming_mode=module_kwargs.diarization_streaming_mode,
|
||||
threshold=module_kwargs.diarization_threshold,
|
||||
)
|
||||
if resource_ledger is not None:
|
||||
resource_ledger.append(diarizer)
|
||||
if diarizer.sample_rate != vad_handler_kwargs.sample_rate:
|
||||
raise ValueError("Diarization and VAD must use the same audio sample rate.")
|
||||
diarizer.warmup()
|
||||
logger.info(
|
||||
"Diarization ready: device=%s mode=%s; speaker labels will accompany completed transcriptions",
|
||||
diarization_device,
|
||||
module_kwargs.diarization_streaming_mode,
|
||||
)
|
||||
vad.diarization_worker = DiarizationWorker(diarizer, stop_event)
|
||||
if resource_ledger is not None:
|
||||
# The worker takes ownership after all model preparation succeeds.
|
||||
resource_ledger.remove(diarizer)
|
||||
resource_ledger.append(vad.diarization_worker)
|
||||
side_handlers.append(vad.diarization_worker)
|
||||
|
||||
needs_notifier = not stt_backend.spec.capabilities.bypasses_transcription_notifier
|
||||
stt_queue_out: Queue[Any] = stt_output_queue if needs_notifier else text_prompt_queue
|
||||
stt_context = HandlerContext(
|
||||
stop_event=stop_event,
|
||||
queue_in=spoken_prompt_queue,
|
||||
queue_out=stt_queue_out,
|
||||
text_output_queue=text_output_queue,
|
||||
should_listen=should_listen,
|
||||
cancel_scope=cancel_scope,
|
||||
speculative_turns=speculative_turns,
|
||||
pipeline_index=pipeline_index,
|
||||
sample_rate=vad_handler_kwargs.sample_rate,
|
||||
enable_live_transcription=module_kwargs.enable_live_transcription,
|
||||
live_transcription_update_interval=module_kwargs.live_transcription_update_interval,
|
||||
)
|
||||
stt_handler = create_backend_handler(stt_backend, stt_context)
|
||||
if resource_ledger is not None:
|
||||
resource_ledger.append(stt_handler)
|
||||
if stt_backend.spec.capabilities.streams_audio_chunks:
|
||||
vad.streaming_stt_sink = stt_handler
|
||||
speech_input_handlers = [stt_handler]
|
||||
if needs_notifier:
|
||||
transcription_notifier = TranscriptionNotifier(
|
||||
stop_event,
|
||||
queue_in=stt_output_queue,
|
||||
queue_out=text_prompt_queue, # type: ignore[arg-type]
|
||||
setup_kwargs={
|
||||
"text_output_queue": text_output_queue,
|
||||
"should_listen": should_listen,
|
||||
},
|
||||
)
|
||||
if resource_ledger is not None:
|
||||
resource_ledger.append(transcription_notifier)
|
||||
speech_input_handlers.append(transcription_notifier)
|
||||
|
||||
def handler_context(queue_in: Queue[Any], queue_out: Queue[Any]) -> HandlerContext:
|
||||
return HandlerContext(
|
||||
stop_event=stop_event,
|
||||
queue_in=queue_in,
|
||||
queue_out=queue_out,
|
||||
text_output_queue=text_output_queue,
|
||||
should_listen=should_listen,
|
||||
cancel_scope=cancel_scope,
|
||||
speculative_turns=speculative_turns,
|
||||
pipeline_index=pipeline_index,
|
||||
sample_rate=vad_handler_kwargs.sample_rate,
|
||||
enable_live_transcription=module_kwargs.enable_live_transcription,
|
||||
live_transcription_update_interval=module_kwargs.live_transcription_update_interval,
|
||||
detect_llm_output_language=module_kwargs.detect_llm_output_language,
|
||||
)
|
||||
|
||||
lm_context = handler_context(text_prompt_queue, lm_response_queue)
|
||||
lm = create_backend_handler(
|
||||
llm_backend,
|
||||
lm_context,
|
||||
)
|
||||
|
||||
if resource_ledger is not None:
|
||||
resource_ledger.append(lm)
|
||||
|
||||
lm_processor = LMOutputProcessor(
|
||||
stop_event,
|
||||
queue_in=lm_response_queue,
|
||||
queue_out=lm_processed_queue,
|
||||
setup_kwargs={
|
||||
"speculative_turns": speculative_turns,
|
||||
"text_output_queue": text_output_queue,
|
||||
"detect_llm_output_language": module_kwargs.detect_llm_output_language,
|
||||
},
|
||||
)
|
||||
|
||||
if resource_ledger is not None:
|
||||
resource_ledger.append(lm_processor)
|
||||
|
||||
tts_output_queue: Queue[AudioOutItem] = Queue() if module_kwargs.enable_visemes else send_audio_chunks_queue
|
||||
tts_context = handler_context(lm_processed_queue, tts_output_queue)
|
||||
tts = create_backend_handler(
|
||||
tts_backend,
|
||||
tts_context,
|
||||
)
|
||||
|
||||
if resource_ledger is not None:
|
||||
resource_ledger.append(tts)
|
||||
|
||||
handlers = [vad, *side_handlers, *speech_input_handlers, lm, lm_processor, tts]
|
||||
if module_kwargs.enable_visemes:
|
||||
from speech_to_speech.STV.w2v_stv_handler import Wav2Vec2STVHandler
|
||||
|
||||
handlers.append(
|
||||
Wav2Vec2STVHandler(
|
||||
stop_event,
|
||||
queue_in=tts_output_queue,
|
||||
queue_out=send_audio_chunks_queue,
|
||||
setup_kwargs={
|
||||
"model_name": module_kwargs.stv_model_name,
|
||||
"device": module_kwargs.device or module_kwargs.stv_device,
|
||||
"cancel_scope": cancel_scope,
|
||||
},
|
||||
)
|
||||
)
|
||||
if resource_ledger is not None:
|
||||
resource_ledger.append(handlers[-1])
|
||||
return handlers
|
||||
|
||||
|
||||
def _stt_session_languages(selection: BackendSelection, handler: Any) -> set[str] | None:
|
||||
if selection.name == "nemotron-streaming" and getattr(handler, "_is_farsi", False):
|
||||
return {"fa"}
|
||||
if selection.name == "faster-whisper":
|
||||
supported = getattr(getattr(handler, "model", None), "supported_languages", None)
|
||||
return set(supported) if supported is not None else None
|
||||
if selection.name == "whisper":
|
||||
generation_config = getattr(getattr(handler, "model", None), "generation_config", None)
|
||||
# Transformers rejects any language argument for an English-only checkpoint.
|
||||
return set() if getattr(generation_config, "is_multilingual", None) is False else None
|
||||
if selection.name == "qwen3-asr":
|
||||
return set(modules[type(handler).__module__].SUPPORTED_LANGUAGES)
|
||||
if selection.name in {"parakeet-tdt", "parakeet-unified", "paraformer", "openai-realtime", "vllm-realtime"}:
|
||||
return set()
|
||||
return None
|
||||
|
||||
|
||||
def _build_pipeline_unit(
|
||||
*,
|
||||
index: int,
|
||||
stop_event: Event,
|
||||
module_kwargs: ModuleArguments,
|
||||
vad_handler_kwargs: VADHandlerArguments,
|
||||
stt_backend: BackendSelection,
|
||||
llm_backend: BackendSelection,
|
||||
tts_backend: BackendSelection,
|
||||
resource_ledger: list[Any] | None = None,
|
||||
) -> "PipelineUnit":
|
||||
"""Build one isolated pipeline with its own state and queues.
|
||||
|
||||
Returns a PipelineUnit that lives inside RealtimeServer's pool. Handler instances
|
||||
are returned in `unit.handlers`; the caller threads them via ThreadManager. No uvicorn
|
||||
is created here — the single server is owned by RealtimeServer.
|
||||
"""
|
||||
from speech_to_speech.api.openai_realtime.service import RealtimeService
|
||||
|
||||
# Per-unit copies isolate any setup-time mutation performed by third-party libraries.
|
||||
vad_kw = deepcopy(vad_handler_kwargs)
|
||||
stt_selection = stt_backend.copy_for_pipeline()
|
||||
llm_selection = llm_backend.copy_for_pipeline()
|
||||
tts_selection = tts_backend.copy_for_pipeline()
|
||||
|
||||
should_listen = Event()
|
||||
response_playing = Event()
|
||||
cancel_scope = CancelScope()
|
||||
speculative_turns = SpeculativeTurnTracker()
|
||||
turn_latency_store = TurnLatencyStore()
|
||||
speculative_turns.wait_observer = turn_latency_store.record_smart_wait
|
||||
recv_audio_chunks_queue: Queue[AudioInItem] = Queue()
|
||||
send_audio_chunks_queue: Queue[AudioOutItem] = Queue()
|
||||
spoken_prompt_queue: Queue[VADOutItem] = Queue()
|
||||
stt_output_queue: Queue[STTOutItem] = Queue()
|
||||
text_prompt_queue: Queue[TextPromptItem] = Queue()
|
||||
lm_response_queue: Queue[LMOutItem] = Queue()
|
||||
lm_processed_queue: Queue[TTSInItem] = Queue()
|
||||
text_output_queue: Queue[TextEventItem] = Queue()
|
||||
|
||||
chat_size = llm_selection.config.get("chat_size", 10)
|
||||
default_instructions = llm_selection.config.get("init_chat_prompt")
|
||||
|
||||
service = RealtimeService(
|
||||
text_prompt_queue=text_prompt_queue,
|
||||
should_listen=should_listen,
|
||||
chat_size=chat_size,
|
||||
speculative_turns=speculative_turns,
|
||||
turn_latency_store=turn_latency_store,
|
||||
default_instructions=default_instructions,
|
||||
)
|
||||
|
||||
if module_kwargs.enable_live_transcription and not stt_selection.spec.capabilities.streams_audio_chunks:
|
||||
vad_kw.enable_realtime_transcription = True
|
||||
vad_kw.realtime_processing_pause = module_kwargs.live_transcription_update_interval
|
||||
|
||||
handlers = _build_handlers(
|
||||
stop_event=stop_event,
|
||||
should_listen=should_listen,
|
||||
recv_audio_chunks_queue=recv_audio_chunks_queue,
|
||||
spoken_prompt_queue=spoken_prompt_queue,
|
||||
stt_output_queue=stt_output_queue,
|
||||
text_prompt_queue=text_prompt_queue,
|
||||
lm_response_queue=lm_response_queue,
|
||||
lm_processed_queue=lm_processed_queue,
|
||||
send_audio_chunks_queue=send_audio_chunks_queue,
|
||||
text_output_queue=text_output_queue,
|
||||
module_kwargs=module_kwargs,
|
||||
vad_handler_kwargs=vad_kw,
|
||||
stt_backend=stt_selection,
|
||||
llm_backend=llm_selection,
|
||||
tts_backend=tts_selection,
|
||||
speculative_turns=speculative_turns,
|
||||
cancel_scope=cancel_scope,
|
||||
pipeline_index=index,
|
||||
**({"resource_ledger": resource_ledger} if resource_ledger is not None else {}),
|
||||
)
|
||||
for h in handlers:
|
||||
h.pipeline_index = index
|
||||
h.turn_latency_store = turn_latency_store
|
||||
|
||||
# Validate only against language sets already known to the active backends.
|
||||
# Faster Whisper reports the loaded checkpoint's actual language set.
|
||||
service.stt_supported_languages = _stt_session_languages(stt_selection, handlers[1])
|
||||
setup_language = stt_selection.config.get("language")
|
||||
service.stt_auto_reset_supported = not (
|
||||
stt_selection.name == "openai-realtime" and isinstance(setup_language, str) and bool(setup_language.strip())
|
||||
)
|
||||
|
||||
tts_handler = handlers[-2] if module_kwargs.enable_visemes else handlers[-1]
|
||||
tts_module = modules[type(tts_handler).__module__]
|
||||
if tts_selection.name == "kokoro":
|
||||
service.tts_supported_languages = {"en", "ja", "zh", "fr", "es", "it", "pt", "hi"}
|
||||
elif tts_selection.name == "facebookMMS":
|
||||
service.tts_supported_languages = set(tts_module.WHISPER_LANGUAGE_TO_FACEBOOK_LANGUAGE)
|
||||
elif tts_selection.name == "supertonic":
|
||||
service.tts_supported_languages = set(tts_module.SUPERTONIC_LANGUAGE_CODES)
|
||||
elif tts_selection.name == "qwen3":
|
||||
service.tts_supported_languages = {code for code in tts_module.QWEN3_LANGUAGE_ALIASES if len(code) == 2}
|
||||
elif tts_selection.name in {"chatTTS", "pocket"}:
|
||||
service.tts_supported_languages = set()
|
||||
|
||||
return PipelineUnit(
|
||||
index=index,
|
||||
service=service,
|
||||
cancel_scope=cancel_scope,
|
||||
should_listen=should_listen,
|
||||
response_playing=response_playing,
|
||||
input_queue=recv_audio_chunks_queue,
|
||||
output_queue=send_audio_chunks_queue,
|
||||
text_output_queue=text_output_queue,
|
||||
text_prompt_queue=text_prompt_queue,
|
||||
handlers=handlers,
|
||||
)
|
||||
|
||||
|
||||
def build_pipeline(
|
||||
args: ParsedArguments,
|
||||
stop_event: Event,
|
||||
*,
|
||||
host: str | None = None,
|
||||
) -> ThreadManager:
|
||||
"""Build a pool of pipeline units behind one server."""
|
||||
from speech_to_speech.api.openai_realtime.server import RealtimeServer
|
||||
|
||||
module_kwargs = args.module_kwargs
|
||||
pool = [
|
||||
_build_pipeline_unit(
|
||||
index=index,
|
||||
stop_event=stop_event,
|
||||
module_kwargs=module_kwargs,
|
||||
vad_handler_kwargs=args.vad_handler_kwargs,
|
||||
stt_backend=args.stt_backend,
|
||||
llm_backend=args.llm_backend,
|
||||
tts_backend=args.tts_backend,
|
||||
)
|
||||
for index in range(module_kwargs.num_pipelines)
|
||||
]
|
||||
|
||||
server = RealtimeServer(
|
||||
stop_event=stop_event,
|
||||
pool=pool,
|
||||
host=host or args.realtime_server_kwargs.host,
|
||||
port=args.realtime_server_kwargs.port,
|
||||
llm_proxy_config=(
|
||||
build_llm_proxy_config(module_kwargs, args.llm_backend) if module_kwargs.enable_llm_proxy else None
|
||||
),
|
||||
)
|
||||
|
||||
handlers: list[Any] = []
|
||||
for unit in pool:
|
||||
handlers.extend(unit.handlers)
|
||||
handlers.append(server)
|
||||
return ThreadManager(handlers)
|
||||
|
||||
|
||||
def build_local_pipeline(args: ParsedArguments, stop_event: Event) -> ThreadManager:
|
||||
"""Compose the canonical server and audio client over a forced loopback URL."""
|
||||
|
||||
from speech_to_speech.api.openai_realtime.audio_client import (
|
||||
RealtimeAudioClient,
|
||||
RealtimeAudioClientConfig,
|
||||
load_realtime_tool_module,
|
||||
)
|
||||
|
||||
local_audio = args.local_audio_kwargs
|
||||
playback_buffer_ms = local_audio.local_audio_playback_buffer_ms
|
||||
if playback_buffer_ms is None:
|
||||
playback_buffer_ms = OPENAI_TTS_PLAYBACK_BUFFER_MS if args.tts_backend.name == "openai" else 0.0
|
||||
tools: list[dict[str, Any]] = []
|
||||
tool_executor = None
|
||||
tool_response_create = True
|
||||
if local_audio.local_audio_tool_module:
|
||||
tools, tool_executor, tool_response_create = load_realtime_tool_module(local_audio.local_audio_tool_module)
|
||||
server_manager = build_pipeline(args, stop_event, host="127.0.0.1")
|
||||
client = RealtimeAudioClient(
|
||||
stop_event,
|
||||
RealtimeAudioClientConfig(
|
||||
url=f"ws://127.0.0.1:{args.realtime_server_kwargs.port}/v1/realtime",
|
||||
api_key="local",
|
||||
chunk_size=local_audio.local_audio_chunk_size,
|
||||
playback_buffer_ms=playback_buffer_ms,
|
||||
input_device=local_audio.local_audio_input_device,
|
||||
output_device=local_audio.local_audio_output_device,
|
||||
print_json=local_audio.local_audio_print_json,
|
||||
block_mic_during_playback=local_audio.local_audio_block_mic_during_playback,
|
||||
tools=tools,
|
||||
tool_executor=tool_executor,
|
||||
tool_response_create=tool_response_create,
|
||||
),
|
||||
)
|
||||
return ThreadManager([*server_manager.handlers, client])
|
||||
|
||||
|
||||
def run_pipeline_command(command: Literal["serve", "local"], argv: Sequence[str]) -> None:
|
||||
"""Run the server alone or compose it with the loopback audio client."""
|
||||
|
||||
args = parse_arguments(argv, command=command)
|
||||
|
||||
setup_logger(args.module_kwargs.log_level)
|
||||
# Set the transcript gate and warn before any conversation is processed, so an operator
|
||||
# sees the notice ahead of the first turn rather than after content is already logged.
|
||||
set_log_transcripts(args.module_kwargs.log_transcripts)
|
||||
warn_if_log_transcripts_enabled()
|
||||
|
||||
if args.module_kwargs.num_pipelines < 1:
|
||||
raise ValueError(f"--num_pipelines must be >= 1, got {args.module_kwargs.num_pipelines}")
|
||||
|
||||
prepare_all_args(args)
|
||||
# On Apple Silicon, all MLX inference serializes through a global lock (utils/mlx_lock.py).
|
||||
# The progressive STT path uses a short timeout and drops work under contention, producing
|
||||
# a flood of warnings without affecting final transcripts. With a pool, pre-emptively turn
|
||||
# it off so logs stay readable; the final STT path is unaffected. Non-darwin platforms
|
||||
# don't share this lock, so leave their live transcription alone.
|
||||
if args.module_kwargs.num_pipelines > 1 and platform == "darwin" and args.module_kwargs.enable_live_transcription:
|
||||
logger.info(
|
||||
"MLX contention: --num_pipelines=%d > 1 on Apple Silicon → disabling live transcription "
|
||||
"(progressive STT contends on the global MLX lock)",
|
||||
args.module_kwargs.num_pipelines,
|
||||
)
|
||||
args.module_kwargs.enable_live_transcription = False
|
||||
|
||||
stop_event = Event()
|
||||
pipeline_manager = (
|
||||
build_local_pipeline(args, stop_event) if command == "local" else build_pipeline(args, stop_event)
|
||||
)
|
||||
|
||||
# Set up graceful shutdown handler
|
||||
shutdown_requested = [False] # Use list for nonlocal mutation
|
||||
|
||||
def signal_handler(_sig: int, _frame: Optional[FrameType]) -> None:
|
||||
if not shutdown_requested[0]:
|
||||
shutdown_requested[0] = True
|
||||
console.print("\n[yellow]Shutting down gracefully...[/yellow]")
|
||||
pipeline_manager.stop()
|
||||
console.print("[green]✓ Pipeline stopped successfully[/green]")
|
||||
|
||||
signal.signal(signal.SIGINT, signal_handler)
|
||||
signal.signal(signal.SIGTERM, signal_handler)
|
||||
|
||||
try:
|
||||
pipeline_manager.start()
|
||||
pipeline_manager.wait()
|
||||
except KeyboardInterrupt:
|
||||
if not shutdown_requested[0]:
|
||||
console.print("\n[yellow]Shutting down gracefully...[/yellow]")
|
||||
pipeline_manager.stop()
|
||||
console.print("[green]✓ Pipeline stopped successfully[/green]")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Compatibility entry point for direct module execution."""
|
||||
|
||||
from speech_to_speech.cli import main as cli_main
|
||||
|
||||
cli_main()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Real DB local profiles retain replay/owner/revocation authority."""
|
||||
from uuid import UUID, uuid4
|
||||
from sqlalchemy import text
|
||||
import pytest
|
||||
from tests.integration.test_phase2_postgres import seeded_env
|
||||
from tests.unit.test_local_s2s_phase2 import local_config
|
||||
|
||||
|
||||
def test_local_profile_replay_never_rewrites_frozen_components(seeded_env):
|
||||
e = seeded_env
|
||||
cid = UUID(e.lifecycle.create_conversation(e.user, uuid4())['id'])
|
||||
request = uuid4()
|
||||
config = local_config()
|
||||
first = e.lifecycle.create_live_session(e.user, cid, request, provider='local_s2s',
|
||||
model=config.selected_model, execution_profile=config.profile())
|
||||
sid = UUID(first['session_id'])
|
||||
changed = local_config(local_s2s_tts_voice='different')
|
||||
replay = e.lifecycle.create_live_session(e.user, cid, request, provider='local_s2s',
|
||||
model=changed.selected_model, execution_profile=changed.profile())
|
||||
assert replay['session_id'] == first['session_id'] and replay['replayed']
|
||||
info = e.lifecycle.validate_stream(e.user, sid, initial=True)
|
||||
assert info['provider'] == 'local_s2s' and info['execution_profile'] == config.profile()
|
||||
assert info['execution_profile'] != changed.profile()
|
||||
with e.engine.begin() as conn:
|
||||
row = conn.execute(text('SELECT execution_profile FROM live_sessions WHERE id=:id'), {'id': sid}).scalar_one()
|
||||
assert row == config.profile()
|
||||
|
||||
|
||||
def test_local_profile_revocation_still_blocks_stream(seeded_env):
|
||||
e = seeded_env
|
||||
cid = UUID(e.lifecycle.create_conversation(e.user, uuid4())['id'])
|
||||
c = local_config()
|
||||
reservation = e.lifecycle.create_live_session(e.user, cid, uuid4(), provider='local_s2s', model=c.selected_model, execution_profile=c.profile())
|
||||
with e.engine.begin() as conn:
|
||||
conn.execute(text('UPDATE organization_settings SET access_epoch=access_epoch+1 WHERE organization_id=:org'), {'org': e.org})
|
||||
with pytest.raises(ValueError):
|
||||
e.lifecycle.validate_stream(e.user, UUID(reservation['session_id']), initial=True)
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Execute hash-checked pinned methods without installing upstream ML dependencies."""
|
||||
import ast
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1] / 'fixtures/local_s2s_upstream'
|
||||
|
||||
|
||||
def tree(name):
|
||||
manifest = json.loads((ROOT / 'manifest.json').read_text())
|
||||
data = (ROOT / name).read_bytes()
|
||||
assert hashlib.sha256(data).hexdigest() == manifest['files'][name]['sha256']
|
||||
return ast.parse(data.decode())
|
||||
|
||||
|
||||
def functions(name, selection, namespace):
|
||||
definitions = []
|
||||
for cls, method in selection:
|
||||
nodes = tree(name).body
|
||||
if cls:
|
||||
nodes = next(n for n in nodes if isinstance(n, ast.ClassDef) and n.name == cls).body
|
||||
node = next(n for n in nodes if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and n.name == method)
|
||||
node.decorator_list = []
|
||||
definitions.append(node)
|
||||
module = ast.Module(body=[ast.ImportFrom(module='__future__', names=[ast.alias(name='annotations')], level=0)] + definitions, type_ignores=[])
|
||||
exec(compile(ast.fix_missing_locations(module), str(ROOT / name), 'exec'), namespace)
|
||||
return namespace
|
||||
|
||||
|
||||
def constant(name, identifier):
|
||||
"""Read a literal from the hash-checked source, never a fixture override."""
|
||||
node = next(n for n in tree(name).body if isinstance(n, ast.Assign)
|
||||
and any(isinstance(t, ast.Name) and t.id == identifier for t in n.targets))
|
||||
return ast.literal_eval(node.value)
|
||||
@@ -0,0 +1,131 @@
|
||||
"""Provider-free Phase 1 replay: run unchanged before and after the boundary."""
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.unit.test_realtime_phase1 import (
|
||||
runner, persisted, make, input_turn, response, delta, done, until, commands,
|
||||
)
|
||||
from tests.unit.test_realtime_repairs import Clock, without_ticker
|
||||
|
||||
|
||||
@pytest.mark.parametrize("completed", [False, True], ids=["active", "completed-unplayed"])
|
||||
@pytest.mark.parametrize("receipt", ["matching", "wrong-item", "wrong-position", "missing", "late", "conflicting"])
|
||||
def test_interruption_replay(runner, persisted, completed, receipt):
|
||||
async def scenario():
|
||||
clock = Clock()
|
||||
runtime, transport, _ = await make(SimpleNamespace(engine=None), runner, persisted, clock=clock)
|
||||
await without_ticker(runtime)
|
||||
try:
|
||||
await input_turn(runtime)
|
||||
await response(runtime, transport)
|
||||
await runtime.handle(delta(48000))
|
||||
await until(lambda: next(iter(runtime.audio.values())).sent == 48000)
|
||||
audio = next(iter(runtime.audio.values()))
|
||||
await runtime.playback_progress(audio.ref, 100)
|
||||
if completed:
|
||||
await done(runtime)
|
||||
await input_turn(runtime, "u2", 10)
|
||||
assert len(commands(transport, "response.create")) == 1
|
||||
if not completed:
|
||||
await until(lambda: commands(transport, "response.cancel"))
|
||||
assert not runtime.responses["r1"].terminal
|
||||
await done(runtime, status="cancelled")
|
||||
clock.advance(1)
|
||||
await runtime.tick()
|
||||
await until(lambda: commands(transport, "conversation.item.truncate"))
|
||||
request = commands(transport, "conversation.item.truncate")[0]
|
||||
assert request["item_id"] == "a1" and request["audio_end_ms"] == 100
|
||||
assert runtime.responses["r1"].terminal
|
||||
assert len(commands(transport, "response.create")) == 1
|
||||
ack = dict(type="conversation.item.truncated", event_id="repair-ack",
|
||||
item_id="a1", content_index=0, audio_end_ms=100)
|
||||
if receipt == "missing":
|
||||
clock.now = audio.cleanup_deadline + .01
|
||||
await runtime.tick()
|
||||
else:
|
||||
if receipt == "wrong-item":
|
||||
ack["item_id"] = "unknown"
|
||||
if receipt == "wrong-position":
|
||||
ack["audio_end_ms"] = 101
|
||||
if receipt == "late":
|
||||
clock.now = audio.cleanup_deadline + .01
|
||||
await runtime.handle(ack)
|
||||
if receipt == "conflicting":
|
||||
await runtime.handle(dict(ack, audio_end_ms=101))
|
||||
if receipt == "matching":
|
||||
await runtime.handle(ack)
|
||||
await runtime.handle(dict(ack, event_id="duplicate-repair-ack"))
|
||||
await runtime.tick()
|
||||
await until(lambda: len(commands(transport, "response.create")) == 2)
|
||||
assert runtime.usable and audio.state == "retired"
|
||||
assert len(commands(transport, "response.create")) == 2
|
||||
print("REPLAY: generation stopped; repair matched at 100ms; duplicate ignored; exactly one next response")
|
||||
else:
|
||||
assert not runtime.usable
|
||||
# A matching ack can release before a later conflict arrives;
|
||||
# the conflict must close the session, never release further work.
|
||||
assert len(commands(transport, "response.create")) <= (2 if receipt == "conflicting" else 1)
|
||||
print(f"REPLAY: {receipt} repair => closed safely ({runtime.failure})")
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("provider", ["openai", "gemini"])
|
||||
def test_native_repair_contract(provider):
|
||||
from app.modules.voice.provider import HistoryRepair, ProviderProtocolError
|
||||
from app.infrastructure.realtime import RealtimeAdapter
|
||||
from app.infrastructure.gemini_live import GeminiLiveAdapter
|
||||
from tests.unit.test_realtime_phase1 import Transport
|
||||
adapter = (RealtimeAdapter if provider == "openai" else GeminiLiveAdapter)(Transport())
|
||||
repair = HistoryRepair("session", 2, "response", "operation", "item", 0, 100)
|
||||
assert adapter.cancellation_request("response", "cancel") == dict(
|
||||
type="response.cancel", response_id="response", event_id="cancel")
|
||||
assert adapter.history_repair_request(repair) == dict(type="conversation.item.truncate",
|
||||
event_id="operation", item_id="item", content_index=0, audio_end_ms=100)
|
||||
event = dict(type="conversation.item.truncated", event_id="native-ack",
|
||||
item_id="item", content_index=0, audio_end_ms=100)
|
||||
if provider == "gemini":
|
||||
with pytest.raises(ProviderProtocolError):
|
||||
adapter.confirm_history_repair(repair, event)
|
||||
return
|
||||
receipt = adapter.confirm_history_repair(repair, event)
|
||||
assert receipt.repair == repair and receipt.native_event_id == "native-ack"
|
||||
assert receipt.provenance == "openai.item_truncated"
|
||||
for changes in ({"item_id": "other"}, {"content_index": False},
|
||||
{"audio_end_ms": True}, {"audio_end_ms": 101}, {"type": "response.done"}):
|
||||
with pytest.raises(ProviderProtocolError):
|
||||
adapter.confirm_history_repair(repair, dict(event, **changes))
|
||||
|
||||
|
||||
def test_adapter_receipt_cannot_rebind_runtime_generation(runner, persisted, monkeypatch):
|
||||
from dataclasses import replace
|
||||
from app.infrastructure.realtime import RealtimeAdapter
|
||||
from app.modules.voice.provider import HistoryRepairReceipt
|
||||
async def scenario():
|
||||
clock = Clock()
|
||||
runtime, transport, _ = await make(SimpleNamespace(engine=None), runner, persisted, clock=clock)
|
||||
await without_ticker(runtime)
|
||||
try:
|
||||
await input_turn(runtime)
|
||||
await response(runtime, transport)
|
||||
await runtime.handle(delta(48000))
|
||||
await until(lambda: next(iter(runtime.audio.values())).sent == 48000)
|
||||
await input_turn(runtime, "u2", 10)
|
||||
await until(lambda: commands(transport, "response.cancel"))
|
||||
await done(runtime, status="cancelled")
|
||||
clock.advance(1)
|
||||
await runtime.tick()
|
||||
await until(lambda: commands(transport, "conversation.item.truncate"))
|
||||
monkeypatch.setattr(RealtimeAdapter, "confirm_history_repair", lambda self, repair, event:
|
||||
HistoryRepairReceipt(replace(repair, generation=repair.generation + 1), "ack", "wrong"))
|
||||
await runtime.handle(dict(type="conversation.item.truncated", item_id="a1",
|
||||
content_index=0, audio_end_ms=0))
|
||||
assert not runtime.usable
|
||||
assert len(commands(transport, "response.create")) == 1
|
||||
assert next(iter(runtime.audio.values())).repair_receipt is None
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Pinned extension checks use initialized fake handlers; no models/providers."""
|
||||
import asyncio
|
||||
from copy import deepcopy
|
||||
from queue import Empty
|
||||
from threading import Event, Thread
|
||||
from types import SimpleNamespace
|
||||
import httpx
|
||||
import pytest
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from services.local_s2s.components import ComponentServer
|
||||
from services.local_s2s.extension import FailClosedQueue, active_components, install_session_proof, EngineTokenGuard
|
||||
from app.modules.voice.local_s2s import setup_session
|
||||
from app.infrastructure.local_s2s import LocalS2SAdapter
|
||||
from app.modules.voice.settings import RuntimeSettings
|
||||
from tests.unit.test_local_s2s_phase2 import local_config
|
||||
from tests.unit.test_realtime_phase1 import Transport
|
||||
|
||||
|
||||
def test_saturated_pipeline_stops_without_blocking_teardown():
|
||||
stop = Event()
|
||||
queue = FailClosedQueue(stop, maxsize=1)
|
||||
queue.put(b'one')
|
||||
with pytest.raises(RuntimeError, match='QUEUE_CAPACITY'):
|
||||
queue.put(b'two', block=True)
|
||||
assert stop.is_set() and queue.get_nowait() == b'one'
|
||||
with pytest.raises(Empty): queue.get_nowait()
|
||||
|
||||
|
||||
def handlers(config):
|
||||
stt_type = type('STT', (), {'__module__': 'speech_to_speech.STT.openai_compatible_handler'})
|
||||
tts_type = type('TTS', (), {'__module__': 'speech_to_speech.TTS.openai_compatible_handler'})
|
||||
stt, tts = stt_type(), tts_type()
|
||||
stt.model, stt.language, stt.response_format = config.local_s2s_stt_model, 'fa', 'json'
|
||||
stt.base_url, stt.api_key, stt.timeout = 'http://127.0.0.1:8766/v1', 'local-components', 30
|
||||
tts.model, tts.voice, tts.response_format, tts.sample_rate = config.local_s2s_tts_model, config.local_s2s_tts_voice, 'pcm', 24000
|
||||
tts.base_url, tts.api_key, tts.timeout = stt.base_url, stt.api_key, stt.timeout
|
||||
class Client:
|
||||
token_limit, max_retries = 256, 0
|
||||
base_url, api_key = stt.base_url, stt.api_key
|
||||
def with_options(self, **kwargs):
|
||||
assert kwargs == {'max_retries': 0}
|
||||
return self
|
||||
llm = SimpleNamespace(model_name=config.local_s2s_llm_model, gen_kwargs={'max_tokens': 256}, request_timeout_s=30, client=Client())
|
||||
return SimpleNamespace(handlers=[SimpleNamespace(enable_realtime_transcription=False), stt, llm, tts])
|
||||
|
||||
|
||||
@pytest.mark.parametrize('change', ['none', 'model', 'voice', 'rate', 'credential', 'progressive'])
|
||||
def test_authoritative_components_come_from_initialized_handlers(change):
|
||||
config = local_config()
|
||||
unit = handlers(config)
|
||||
if change == 'model': unit.handlers[1].model = 'wrong'
|
||||
if change == 'voice': unit.handlers[-1].voice = 'wrong'
|
||||
if change == 'rate': unit.handlers[-1].sample_rate = 16000
|
||||
if change == 'credential': unit.handlers[1].api_key = ''
|
||||
if change == 'progressive': unit.handlers[0].enable_realtime_transcription = True
|
||||
if change != 'none':
|
||||
with pytest.raises(ValueError): active_components(unit, config.components())
|
||||
else:
|
||||
assert active_components(unit, config.components()) == config.components()
|
||||
|
||||
|
||||
def test_native_session_proof_uses_applied_state_instead_of_request_echo():
|
||||
config = local_config()
|
||||
class Session(BaseModel):
|
||||
model_config = ConfigDict(extra='allow')
|
||||
class Result(BaseModel):
|
||||
session: Session
|
||||
actual = Session(**setup_session(config))
|
||||
service = object()
|
||||
class Handler:
|
||||
_service = service
|
||||
def _state(self, conn): return SimpleNamespace(runtime_config=SimpleNamespace(session=actual))
|
||||
def build_session_updated(self, conn): return Result(session=actual.model_copy())
|
||||
install_session_proof(Handler, {id(service): config.components()}, setup_session(config))
|
||||
adapter = LocalS2SAdapter(Transport(), config=config, settings=RuntimeSettings(_env_file=None))
|
||||
event = Handler().build_session_updated('native-session')
|
||||
assert adapter.acknowledged(event.session.model_dump())
|
||||
actual.model = 'other/model'
|
||||
assert not adapter.acknowledged(Handler().build_session_updated('native-session').session.model_dump())
|
||||
|
||||
|
||||
@pytest.mark.parametrize('kind', ['http', 'websocket'])
|
||||
def test_engine_token_mismatch_refuses_before_native_handler(kind):
|
||||
async def scenario():
|
||||
sent, entered = [], []
|
||||
async def app(scope, receive, send): entered.append(True)
|
||||
async def send(e): sent.append(e)
|
||||
async def receive(): return {}
|
||||
guard = EngineTokenGuard(app, 'private-test-token')
|
||||
await guard({'type': kind, 'headers': []}, receive, send)
|
||||
assert not entered
|
||||
assert sent[0].get('status', sent[0].get('code')) in (401, 1008)
|
||||
await guard({'type': kind, 'headers': [(b'authorization', b'Bearer private-test-token')]}, receive, send)
|
||||
assert entered == [True]
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure', [False, True])
|
||||
def test_loopback_gateway_credentials_pcm_and_detectable_stream_abort(failure):
|
||||
observed = []
|
||||
def upstream(request):
|
||||
observed.append(request)
|
||||
assert request.url == 'https://openrouter.ai/api/v1/audio/speech'
|
||||
assert request.headers['authorization'] == 'Bearer fake-router-key'
|
||||
size = 1440002 if failure else 9600
|
||||
return httpx.Response(200, headers={'content-type': 'audio/pcm'}, content=bytes(size))
|
||||
server = ComponentServer('fake-router-key', port=0, transport=httpx.MockTransport(upstream))
|
||||
thread = Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
url = f'http://127.0.0.1:{server.server_port}/v1/audio/speech'
|
||||
with httpx.Client(timeout=3, trust_env=False) as client:
|
||||
assert client.post(url, content=b'{}').status_code == 403
|
||||
if failure:
|
||||
with pytest.raises(httpx.RemoteProtocolError):
|
||||
client.post(url, content=b'{}', headers={'Authorization': 'Bearer local-components'})
|
||||
else:
|
||||
result = client.post(url, content=b'{}', headers={'Authorization': 'Bearer local-components'})
|
||||
assert result.status_code == 200 and result.content == bytes(9600)
|
||||
assert len(observed) == 1 and server.counts['/v1/audio/speech'] == 1
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join(timeout=3)
|
||||
@@ -0,0 +1,179 @@
|
||||
"""Local development adapter, attestation, PCM and bounded component contracts."""
|
||||
import asyncio
|
||||
from copy import deepcopy
|
||||
from io import BytesIO
|
||||
import json
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from uuid import uuid4
|
||||
import wave
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from app.modules.voice.configuration import VoiceSettings
|
||||
from app.modules.voice.settings import RuntimeSettings
|
||||
from app.modules.voice.local_s2s import effective_identity, require_isolated_candidate
|
||||
from app.infrastructure.local_s2s import LocalS2SAdapter, LocalS2SContextError
|
||||
from app.modules.voice.runtime import VoiceRuntime
|
||||
from app.local_s2s_smoke import stages, stub_response, tone, wav_bytes
|
||||
from tests.unit.test_realtime_phase1 import Transport, runner, until, commands, input_turn, response, delta, done
|
||||
|
||||
|
||||
def local_config(**changes):
|
||||
values = dict(provider='local_s2s', local_s2s_enabled=True, voice_transport_testing=True,
|
||||
local_s2s_stt_model='test/stt', local_s2s_llm_model='test/llm',
|
||||
local_s2s_tts_model='test/tts', local_s2s_tts_voice='fixture')
|
||||
values.update(changes)
|
||||
return VoiceSettings(_env_file=None, **values)
|
||||
|
||||
|
||||
def confirmed(adapter):
|
||||
session = adapter.setup()['session']
|
||||
session['s2s_effective'] = effective_identity(adapter.config.components(), deepcopy(session))
|
||||
return session
|
||||
|
||||
|
||||
@pytest.mark.parametrize('changed', [dict(local_s2s_enabled=False), dict(voice_transport_testing=False),
|
||||
dict(local_s2s_stt_model=''), dict(local_s2s_tts_model=''), dict(local_s2s_tts_voice='')])
|
||||
def test_opt_in_and_complete_fixed_profile_required(changed):
|
||||
with pytest.raises(ValueError):
|
||||
local_config(**changed).require_voice()
|
||||
|
||||
|
||||
def test_profile_has_no_credentials_and_changes_with_effective_components():
|
||||
a = local_config(local_s2s_token='private-fixture')
|
||||
a.require_voice()
|
||||
profile = a.profile()
|
||||
assert 'private-fixture' not in json.dumps(profile)
|
||||
assert profile == local_config(local_s2s_token='rotated-fixture').profile()
|
||||
assert profile != local_config(local_s2s_stt_model='other/stt').profile()
|
||||
assert profile['development_only'] and profile['interruption_policy'] == 'close_until_phase3'
|
||||
assert profile['input_sample_rate'] == profile['output_sample_rate'] == 24000
|
||||
|
||||
|
||||
@pytest.mark.parametrize('path', ['engine_revision', 'patch_revision', 'contract_revision',
|
||||
'components', 'effective_config_sha256'])
|
||||
def test_setup_echo_or_mismatched_engine_identity_never_ready(path):
|
||||
adapter = LocalS2SAdapter(Transport(), config=local_config(), settings=RuntimeSettings(_env_file=None))
|
||||
assert not adapter.acknowledged(adapter.setup()['session'])
|
||||
session = confirmed(adapter)
|
||||
assert adapter.acknowledged(session)
|
||||
session['s2s_effective'][path] = 'wrong'
|
||||
assert not adapter.acknowledged(session)
|
||||
assert not adapter.acknowledged(dict(confirmed(adapter), model='other/llm'))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('kind', ['response.cancel', 'conversation.item.truncate'])
|
||||
def test_no_fake_history_or_terminal_on_interruption(kind):
|
||||
async def scenario():
|
||||
wire = Transport()
|
||||
adapter = LocalS2SAdapter(wire, config=local_config(), settings=RuntimeSettings(_env_file=None))
|
||||
with pytest.raises(LocalS2SContextError):
|
||||
await adapter.send({'type': kind})
|
||||
assert not wire.sent
|
||||
with pytest.raises(LocalS2SContextError):
|
||||
adapter.confirm_history_repair(None, {})
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_actual_runtime_normal_local_audio_and_close(runner):
|
||||
async def scenario():
|
||||
wire, output = Transport(), []
|
||||
adapter = LocalS2SAdapter(wire, config=local_config(), settings=RuntimeSettings(_env_file=None))
|
||||
async def emit(event): output.append(event)
|
||||
async def authority(execution):
|
||||
return execution.capture(dict(id=execution.user_id, organization_id='fixture', role='user'), 1)
|
||||
runtime = VoiceRuntime(adapter, SimpleNamespace(engine=None), runner, uuid4(), emit, authority_check=authority)
|
||||
try:
|
||||
await runtime.start()
|
||||
await until(lambda: commands(wire, 'session.update'))
|
||||
assert not runtime.ready
|
||||
await runtime.handle(dict(type='session.updated', session=confirmed(adapter)))
|
||||
await until(lambda: runtime.ready)
|
||||
await input_turn(runtime)
|
||||
await response(runtime, wire)
|
||||
await runtime.handle(dict(type='conversation.item.input_audio_transcription.completed', item_id='u1', content_index=0, transcript='hello fixture'))
|
||||
await runtime.handle(delta(960))
|
||||
await runtime.handle(dict(type='response.output_audio_transcript.done', response_id='r1', item_id='a1', output_index=0, content_index=0, transcript='answer fixture'))
|
||||
await runtime.handle(dict(type='response.output_audio.done', response_id='r1', item_id='a1', output_index=0, content_index=0))
|
||||
await done(runtime)
|
||||
await until(lambda: any(isinstance(e, bytes) for e in output))
|
||||
audio = next(iter(runtime.audio.values()))
|
||||
await until(lambda: audio.sent == 960)
|
||||
await runtime.playback_progress(audio.ref, 20)
|
||||
assert runtime.usable and b''.join(e for e in output if isinstance(e, bytes)) == bytes(960)
|
||||
await until(lambda: len([e for e in output if isinstance(e, dict) and e.get('type') == 'transcript']) >= 2)
|
||||
assert {e['role'] for e in output if isinstance(e, dict) and e.get('type') == 'transcript'} == {'user', 'assistant'}
|
||||
assert not commands(wire, 'conversation.item.truncate')
|
||||
finally:
|
||||
await runtime.close()
|
||||
assert wire.closed
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_factory_selects_local_only(monkeypatch):
|
||||
import app.infrastructure.local_s2s as local
|
||||
from app.infrastructure.voice_provider import create_adapter
|
||||
wire = Transport()
|
||||
async def connect(config, limits): return wire
|
||||
monkeypatch.setattr(local, 'connect_local', connect)
|
||||
async def scenario():
|
||||
adapter = await create_adapter(local_config(), RuntimeSettings(_env_file=None))
|
||||
assert isinstance(adapter, LocalS2SAdapter)
|
||||
await adapter.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_isolation_precedes_startup_reconciliation(settings):
|
||||
config = local_config()
|
||||
with pytest.raises(ValueError, match='isolated'):
|
||||
require_isolated_candidate(config, settings)
|
||||
candidate = settings.model_copy(update={'database_url': __import__('pydantic').SecretStr('postgresql+psycopg://unused/app_local_s2s_test')})
|
||||
with pytest.raises(ValueError, match='storage'):
|
||||
require_isolated_candidate(config, candidate)
|
||||
candidate = candidate.model_copy(update={'original_directory': Path('data/local-s2s-test/originals'),
|
||||
'extraction_directory': Path('data/local-s2s-test/extractions')})
|
||||
require_isolated_candidate(config, candidate)
|
||||
# An edited environment cannot relabel the API's already-open operational DB.
|
||||
with pytest.raises(ValueError, match='isolated'):
|
||||
require_isolated_candidate(config, candidate, database_url='postgresql+psycopg://unused/operational')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('mode', ['multipart', 'json'])
|
||||
def test_stub_stages_forward_credentials_and_use_persian_pcm_contract(mode):
|
||||
seen = []
|
||||
def remote(request):
|
||||
seen.append(request)
|
||||
assert request.headers['authorization'] == 'Bearer fixture-secret'
|
||||
return stub_response(request)
|
||||
async def scenario():
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(remote)) as client:
|
||||
pcm = await stages(local_config(), tone(), client, 'fixture-secret', stt_format=mode)
|
||||
assert pcm == tone() and len(seen) == 3
|
||||
with wave.open(BytesIO(wav_bytes(pcm)), 'rb') as audio:
|
||||
assert (audio.getframerate(), audio.getnchannels(), audio.getsampwidth()) == (24000, 1, 2)
|
||||
if mode == 'json':
|
||||
assert json.loads(seen[0].content)['language'] == 'fa'
|
||||
else:
|
||||
assert b'name="file"' in seen[0].content and b'test/stt' in seen[0].content
|
||||
assert json.loads(seen[1].content)['max_tokens'] == 128
|
||||
assert json.loads(seen[2].content)['response_format'] == 'pcm'
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure', ['http', 'odd-audio', 'oversize', 'unfinished-llm', 'json-error-audio'])
|
||||
def test_stage_failures_are_bounded_and_never_become_success(failure):
|
||||
def remote(request):
|
||||
if failure == 'http': return httpx.Response(401, text='PRIVATE_KEY_PROVIDER_TEXT')
|
||||
if request.url.path.endswith('/chat/completions') and failure == 'unfinished-llm':
|
||||
return httpx.Response(200, json={'choices': [{'finish_reason': 'length'}]})
|
||||
if request.url.path.endswith('/audio/speech'):
|
||||
if failure == 'odd-audio': return httpx.Response(200, headers={'content-type': 'audio/pcm'}, content=b'x')
|
||||
if failure == 'oversize': return httpx.Response(200, headers={'content-type': 'audio/pcm'}, content=bytes(480002))
|
||||
if failure == 'json-error-audio': return httpx.Response(200, json={'error': 'private'})
|
||||
return stub_response(request)
|
||||
async def scenario():
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(remote)) as client:
|
||||
with pytest.raises(ValueError, match='LOCAL_STAGE_'):
|
||||
await stages(local_config(), tone(), client, 'fixture-secret')
|
||||
asyncio.run(scenario())
|
||||
@@ -0,0 +1,590 @@
|
||||
"""Regression evidence for five repairs: real pinned methods and owned loopback I/O."""
|
||||
import asyncio
|
||||
from contextlib import contextmanager
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import socket
|
||||
import socketserver
|
||||
from threading import Event, Lock, Thread, Timer, current_thread, BoundedSemaphore
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from services.local_s2s.request_policy import LimitedChatClient, install_client_policy
|
||||
from services.local_s2s.components import ComponentServer, CLEANUP_WINDOW_SECONDS
|
||||
from services.local_s2s.assets import REQUIRED_NLTK, REQUIRED_VAD, AssetError, validate_assets, configure_nltk, patch_pipeline_source
|
||||
from services.local_s2s.lifecycle import cleanup, run_owned
|
||||
from tests.support.local_s2s_pinned import functions, tree, constant, ROOT
|
||||
from tests.unit.test_local_s2s_phase2 import local_config
|
||||
|
||||
|
||||
class RecordingSDK:
|
||||
"""SDK boundary stand-in; pinned request/setup/process/warmup methods run unchanged."""
|
||||
def __init__(self, calls, *, max_retries=0, failure=None, **kwargs):
|
||||
self.calls, self.max_retries, self.failure = calls, max_retries, failure
|
||||
self.chat = SimpleNamespace(completions=SimpleNamespace(create=self.create))
|
||||
def with_options(self, **kwargs):
|
||||
return RecordingSDK(self.calls, max_retries=kwargs.get('max_retries', self.max_retries), failure=self.failure)
|
||||
def create(self, **kwargs):
|
||||
payload = {key: value for key, value in kwargs.items() if key != 'timeout'}
|
||||
def send(request):
|
||||
self.calls.append(json.loads(request.content))
|
||||
if self.failure:
|
||||
raise self.failure
|
||||
return httpx.Response(200, json={})
|
||||
for attempt in range(self.max_retries + 1):
|
||||
try:
|
||||
with httpx.Client(transport=httpx.MockTransport(send), trust_env=False) as transport:
|
||||
transport.post('https://fixture.invalid/v1/chat/completions', json=payload)
|
||||
return payload
|
||||
except httpx.HTTPError:
|
||||
if attempt == self.max_retries:
|
||||
raise
|
||||
|
||||
|
||||
def upstream_handler(client):
|
||||
ns = dict(time=time, logger=logging.getLogger('pinned-fixture'), WARMUP_MAX_RETRIES=constant('base.py.source', 'WARMUP_MAX_RETRIES'),
|
||||
_build_chat_optional_kwargs=lambda *_: {})
|
||||
functions('chat.py.source', [(None, '_request_chat_completions'),
|
||||
('ChatCompletionsApiModelHandler', '_request'), ('ChatCompletionsApiModelHandler', 'warmup'),
|
||||
('ChatCompletionsApiModelHandler', '_build_optional_kwargs')], ns)
|
||||
functions('base.py.source', [('BaseOpenAICompatibleHandler', 'process'), ('BaseOpenAICompatibleHandler', 'setup')], ns)
|
||||
ns.update(os=__import__('os'), httpx=httpx, BoundedSemaphore=BoundedSemaphore,
|
||||
Lock=Lock, PREFETCH_PROVIDER_WORKER_LIMIT=2)
|
||||
ns.update(is_out_of_band=lambda _: False, resolve_auto_language=lambda x: (x, None),
|
||||
language_name_for_prompt=lambda *a, **k: None, response_wants_audio=lambda _: True,
|
||||
_Turn=lambda **kw: SimpleNamespace(**kw))
|
||||
Handler = type('PinnedHandler', (), {name: ns[name] for name in ('_request', 'warmup', '_build_optional_kwargs', 'process', 'setup')})
|
||||
handler = Handler()
|
||||
handler.client, handler.model_name, handler.stream = client, 'test/llm', False
|
||||
handler._extra_body, handler.request_timeout, handler.cancel_scope = {}, 1, None
|
||||
handler.enable_lang_prompt = False
|
||||
handler._turn_is_latest = lambda *_: True
|
||||
handler._apply_config = lambda *a, **kw: None
|
||||
# Only serialization/history output is isolated; process calls the pinned _request.
|
||||
handler._generate = lambda chat, original, turn, kw: iter([handler._request(chat.messages, kw)])
|
||||
return handler
|
||||
|
||||
|
||||
@pytest.mark.parametrize('limit', [17, 83])
|
||||
def test_pinned_normal_stt_turn_and_warmup_emit_actual_nondefault_token_limit(limit):
|
||||
calls = []
|
||||
client = LimitedChatClient(RecordingSDK(calls), limit)
|
||||
handler = upstream_handler(client)
|
||||
chat = SimpleNamespace(messages=[{'role': 'user', 'content': 'transcribed fixture'}], buffer=[],
|
||||
copy=lambda **kw: chat, history_anchor_id=lambda: None, has_pending_tool_calls=lambda: False)
|
||||
request = SimpleNamespace(audio=None, response=None, turn_id='turn', turn_revision=1,
|
||||
speech_stopped_at_s=0, runtime_config=SimpleNamespace(chat=chat,
|
||||
session=SimpleNamespace(instructions='fixture', tools=None, tool_choice=None)),
|
||||
language_code='fa', selected_language='fa', response_key='r', prefetch_transaction=None)
|
||||
list(handler.process(request))
|
||||
handler.warmup()
|
||||
assert len(calls) == 2
|
||||
assert [c['max_tokens'] for c in calls] == [limit, limit]
|
||||
assert calls[0]['messages'][0]['content'] == 'transcribed fixture'
|
||||
assert calls[1]['messages'][-1]['content'] == 'Hello'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure', [httpx.ConnectError('fixture connection failure'),
|
||||
httpx.HTTPStatusError('fixture retryable 503', request=httpx.Request('POST', 'https://fixture.invalid'), response=httpx.Response(503))])
|
||||
def test_pinned_warmup_cannot_restore_retries(failure):
|
||||
calls = []
|
||||
handler = upstream_handler(LimitedChatClient(RecordingSDK(calls, failure=failure), 29))
|
||||
with pytest.raises(type(failure)):
|
||||
handler.warmup()
|
||||
assert len(calls) == 1 and calls[0]['max_tokens'] == 29
|
||||
|
||||
|
||||
def asset_bundle(tmp_path):
|
||||
roots = {'nltk': tmp_path / 'nltk', 'vad': tmp_path / 'vad'}
|
||||
files = {}
|
||||
for kind, paths in [('nltk', REQUIRED_NLTK), ('vad', REQUIRED_VAD)]:
|
||||
for name in paths:
|
||||
path = roots[kind] / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(b'controlled asset fixture')
|
||||
files[kind + '/' + name] = hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
manifest = tmp_path / 'assets.json'
|
||||
manifest.write_text(json.dumps(dict(schema=1, files=files)))
|
||||
return roots, manifest
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fault', ['missing', 'changed', 'extra', 'valid'])
|
||||
def test_required_assets_are_complete_and_fingerprinted_before_any_probe(tmp_path, fault):
|
||||
roots, manifest = asset_bundle(tmp_path)
|
||||
path = roots['nltk'] / REQUIRED_NLTK[0]
|
||||
if fault == 'missing': path.unlink()
|
||||
if fault == 'changed': path.write_bytes(b'changed')
|
||||
if fault == 'extra': (roots['vad'] / 'untracked').write_bytes(b'x')
|
||||
if fault == 'valid':
|
||||
assert validate_assets(roots['nltk'], roots['vad'], manifest) == hashlib.sha256(manifest.read_bytes()).hexdigest()
|
||||
else:
|
||||
with pytest.raises(AssetError): validate_assets(roots['nltk'], roots['vad'], manifest)
|
||||
|
||||
|
||||
def test_pinned_import_has_no_runtime_nltk_download_and_keeps_tokenization(tmp_path):
|
||||
calls = []
|
||||
nltk = SimpleNamespace(data=SimpleNamespace(path=[], find=lambda p: p),
|
||||
sent_tokenize=lambda text: calls.append('sent') or [text],
|
||||
pos_tag=lambda words, **kw: calls.append('pos') or [(words[0], 'NN')],
|
||||
download=lambda *a: pytest.fail('download invoked'))
|
||||
configure_nltk(nltk, tmp_path)
|
||||
source = (ROOT / 'pipeline.py.source').read_text()
|
||||
patched = patch_pipeline_source(source)
|
||||
assert 'nltk.download(' not in patched
|
||||
# Execute the exact import-time patched preflight, not a replacement tokenizer.
|
||||
start, end = patched.index('from services.local_s2s.assets'), patched.index('# caching allows')
|
||||
exec(patched[start:end], {'nltk': nltk})
|
||||
assert calls == ['sent', 'pos', 'sent', 'pos']
|
||||
with pytest.raises(AssetError): nltk.download('anything')
|
||||
|
||||
|
||||
def test_missing_assets_main_fails_safely_before_provider_imports(monkeypatch, tmp_path, capsys):
|
||||
from services.local_s2s import engine
|
||||
import sys
|
||||
monkeypatch.setattr(sys, 'argv', ['engine', '--allow-paid-startup'])
|
||||
monkeypatch.setenv('LOCAL_S2S_ALLOW_PAID_STARTUP', 'true')
|
||||
monkeypatch.setenv('LOCAL_S2S_NLTK_DATA', str(tmp_path / 'missing'))
|
||||
monkeypatch.setattr('app.modules.voice.configuration.VoiceSettings', lambda **kw: local_config())
|
||||
monkeypatch.setattr(engine, 'build_runtime', lambda *a: pytest.fail('provider construction reached'))
|
||||
assert engine.main() == 1
|
||||
assert 'LOCAL_ENGINE_ASSET_VALIDATION_FAILED' in capsys.readouterr().out
|
||||
|
||||
|
||||
@contextmanager
|
||||
def gateway(handler=None, *, timeout=.2, inactivity=.1, transport=None):
|
||||
server = ComponentServer('fixture-key', port=0, transport=transport or httpx.MockTransport(handler or (lambda r: httpx.Response(503))),
|
||||
timeout=timeout, inactivity=inactivity)
|
||||
thread = Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
assert server.ready.wait(2)
|
||||
try: yield server
|
||||
finally:
|
||||
server.shutdown(); server.server_close(); thread.join(2)
|
||||
assert not thread.is_alive()
|
||||
|
||||
|
||||
def wait_released(server, count=1):
|
||||
deadline = time.monotonic() + 2
|
||||
while server.counts['released'] < count and time.monotonic() < deadline: time.sleep(.005)
|
||||
assert server.counts['released'] >= count and not server.requests
|
||||
|
||||
|
||||
@pytest.mark.parametrize('partial', [b'', b'POST /v1/audio/speech HTTP/1.1\r\nContent-',
|
||||
b'POST /v1/audio/speech HTTP/1.1\r\nContent-Length: 100\r\n\r\nx'])
|
||||
def test_silent_partial_headers_and_stalled_body_release_slots(partial):
|
||||
with gateway() as server:
|
||||
with socket.create_connection(('127.0.0.1', server.server_port), timeout=2) as client:
|
||||
if partial: client.sendall(partial)
|
||||
assert client.recv(4096) == b''
|
||||
wait_released(server)
|
||||
assert server.counts['expired'] == 1 and sum(server.counts[p] for p in ('/v1/audio/speech','/v1/chat/completions')) == 0
|
||||
|
||||
|
||||
def test_slow_upstream_headers_cancel_transport_and_release_slot():
|
||||
cancelled = Event()
|
||||
async def remote(request):
|
||||
try: await asyncio.sleep(10)
|
||||
finally: cancelled.set()
|
||||
with gateway(remote) as server:
|
||||
with httpx.Client(timeout=2, trust_env=False) as client:
|
||||
with pytest.raises(httpx.RemoteProtocolError):
|
||||
client.post(f'http://127.0.0.1:{server.server_port}/v1/audio/speech', content=b'{}', headers={'Authorization':'Bearer local-components'})
|
||||
wait_released(server)
|
||||
assert cancelled.is_set() and server.counts['/v1/audio/speech'] == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize('path,media', [('/v1/audio/speech','audio/pcm'),('/v1/chat/completions','text/event-stream')])
|
||||
def test_sub8192_trickle_is_forwarded_but_total_deadline_leaves_incomplete_stream(path, media):
|
||||
closed = Event()
|
||||
class Stream(httpx.AsyncByteStream):
|
||||
async def __aiter__(self):
|
||||
while True:
|
||||
yield b'x'
|
||||
await asyncio.sleep(.02)
|
||||
async def aclose(self): closed.set()
|
||||
def remote(request): return httpx.Response(200, headers={'content-type':media}, stream=Stream())
|
||||
with gateway(remote, timeout=.2, inactivity=.1) as server:
|
||||
began = time.monotonic()
|
||||
with httpx.Client(timeout=2, trust_env=False) as client:
|
||||
with client.stream('POST',f'http://127.0.0.1:{server.server_port}'+path,content=b'{}',headers={'Authorization':'Bearer local-components'}) as result:
|
||||
iterator=result.iter_raw()
|
||||
assert next(iterator) == b'x'
|
||||
assert time.monotonic()-began < .18
|
||||
with pytest.raises(httpx.RemoteProtocolError): list(iterator)
|
||||
wait_released(server)
|
||||
assert closed.is_set() and server.counts['expired'] == 1
|
||||
|
||||
|
||||
def test_blocked_downstream_drain_is_bounded_and_transports_close():
|
||||
async def scenario():
|
||||
with gateway(lambda r:httpx.Response(200,headers={'content-type':'audio/pcm'},content=b'xx')) as server:
|
||||
reader = asyncio.StreamReader()
|
||||
reader.feed_data(b'POST /v1/audio/speech HTTP/1.1\r\nContent-Length: 2\r\nAuthorization: Bearer local-components\r\n\r\n{}')
|
||||
class Writer:
|
||||
closed=False
|
||||
def write(self,data): pass
|
||||
drains=0
|
||||
async def drain(self):
|
||||
self.drains+=1
|
||||
if self.drains>1: await asyncio.Event().wait()
|
||||
def close(self): self.closed=True
|
||||
async def wait_closed(self): pass
|
||||
writer=Writer()
|
||||
start=time.monotonic()
|
||||
await server._serve(reader,writer,asyncio.get_running_loop().time()+.1)
|
||||
assert writer.closed and time.monotonic()-start<.5 and writer.drains==2
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_pinned_stop_exception_does_not_skip_gateway_cleanup():
|
||||
ns=dict(monotonic=time.monotonic,current_thread=current_thread,_JOIN_TIMEOUT_S=.01,logger=logging.getLogger('pinned'),ConfiguredRuntimeError=RuntimeError,_cleanup=lambda _:None)
|
||||
functions('lifecycle.py.source',[('ConfiguredRuntime','stop')],ns)
|
||||
class Survivor:
|
||||
def join(self,timeout): pass
|
||||
def is_alive(self): return True
|
||||
runtime=SimpleNamespace(_lock=Lock(),state='running',_signal_stop=lambda:None,_threads=[Survivor()],_monitor=None)
|
||||
runtime.stop=lambda:ns['stop'](runtime)
|
||||
logs=[]
|
||||
with gateway() as guard:
|
||||
thread=SimpleNamespace(join=lambda timeout:None,is_alive=lambda:False)
|
||||
assert cleanup(runtime,guard,thread,Event(),timeout=.2,emit=lambda value,**kw:logs.append(json.loads(value)))
|
||||
assert logs[-1]['cleanup']['runtime_stop']==1
|
||||
assert logs[-1]['cleanup']['gateway_shutdown']==0
|
||||
assert guard.done.is_set()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('sig',[signal.SIGINT,signal.SIGTERM])
|
||||
def test_termination_during_inflight_restores_handlers_and_emits_final_counters(monkeypatch,sig):
|
||||
import services.local_s2s.lifecycle as lifecycle
|
||||
captured,logs=[],[]
|
||||
previous={s:signal.getsignal(s) for s in (signal.SIGINT,signal.SIGTERM)}
|
||||
entered=Event()
|
||||
async def remote(request):
|
||||
entered.set()
|
||||
await asyncio.sleep(10)
|
||||
def start(key,timeout):
|
||||
guard=ComponentServer(key,port=0,transport=httpx.MockTransport(remote),timeout=1)
|
||||
thread=Thread(target=guard.serve_forever,daemon=True);thread.start();assert guard.ready.wait(2)
|
||||
captured.extend([guard,thread]);return guard,thread
|
||||
monkeypatch.setattr(lifecycle,'start_components',start)
|
||||
def build(stop):
|
||||
class Runtime:
|
||||
def start(self):
|
||||
def request():
|
||||
try:
|
||||
with httpx.Client(timeout=2,trust_env=False) as client:
|
||||
client.post(f'http://127.0.0.1:{captured[0].server_port}/v1/audio/speech',content=b'{}',headers={'Authorization':'Bearer local-components'})
|
||||
except httpx.HTTPError: pass
|
||||
Thread(target=request,daemon=True).start()
|
||||
def wait(self): stop.wait()
|
||||
def stop(self): raise RuntimeError('controlled stop failure')
|
||||
def terminate():
|
||||
assert entered.wait(2)
|
||||
signal.getsignal(sig)(sig,None) # installed handler dispatch; portable on Windows
|
||||
Thread(target=terminate,daemon=True).start()
|
||||
return Runtime()
|
||||
assert lifecycle.run_owned(build,'fixture-key',1,emit=lambda value,**kw:logs.append(json.loads(value)))==1
|
||||
assert not captured[1].is_alive() and not captured[0].requests
|
||||
assert logs[-1]['stage']=='close' and logs[-1]['request_counts']['released']==1
|
||||
assert all(signal.getsignal(s)==handler for s,handler in previous.items())
|
||||
|
||||
|
||||
@pytest.mark.parametrize('limit', [19, 71])
|
||||
def test_real_pinned_setup_warmup_is_already_capped_before_constructor_returns(limit):
|
||||
calls=[]
|
||||
handler=upstream_handler(None)
|
||||
ns=handler.setup.__func__.__globals__
|
||||
module=SimpleNamespace(OpenAI=lambda **kw: RecordingSDK(calls, **kw),
|
||||
BaseOpenAICompatibleHandler=type('Base', (), {'setup': handler.setup.__func__}))
|
||||
install_client_policy(module, local_config(local_s2s_max_output_tokens=limit,local_s2s_request_timeout_seconds=9))
|
||||
handler.setup=module.BaseOpenAICompatibleHandler.setup.__get__(handler)
|
||||
ns['OpenAI']=module.OpenAI
|
||||
handler._build_extra_body=lambda *a: {}
|
||||
handler.setup(model_name='test/llm', api_key='fixture', base_url='http://127.0.0.1/v1', compact_history=False)
|
||||
assert len(calls)==1 and calls[0]['max_tokens']==limit
|
||||
assert handler.client.token_limit==limit and handler.gen_kwargs=={}
|
||||
assert handler.request_timeout_s==9 and handler.request_timeout.read==9
|
||||
|
||||
|
||||
def test_hung_construction_and_hung_stop_are_bounded_and_gateway_always_closes(monkeypatch):
|
||||
import services.local_s2s.lifecycle as lifecycle
|
||||
captured,logs=[],[]
|
||||
def start(key,timeout):
|
||||
server=ComponentServer(key,port=0,timeout=.2)
|
||||
thread=Thread(target=server.serve_forever,daemon=True);thread.start();assert server.ready.wait(1)
|
||||
captured.extend([server,thread]);return server,thread
|
||||
monkeypatch.setattr(lifecycle,'start_components',start)
|
||||
latch=Event()
|
||||
began=time.monotonic()
|
||||
assert lifecycle.run_owned(lambda stop:latch.wait(10),'fixture',.2,startup_timeout=.05,cleanup_timeout=.2,
|
||||
emit=lambda value,**kw:logs.append(json.loads(value)))==1
|
||||
assert time.monotonic()-began<1 and not captured[1].is_alive()
|
||||
assert logs[-1]['stage']=='close'
|
||||
latch.set()
|
||||
with gateway() as server:
|
||||
runtime=SimpleNamespace(stop=lambda:Event().wait(10))
|
||||
logs=[]
|
||||
assert cleanup(runtime,server,SimpleNamespace(join=lambda timeout:None,is_alive=lambda:False),Event(),timeout=.05,
|
||||
emit=lambda value,**kw:logs.append(json.loads(value)))
|
||||
assert logs[-1]['cleanup']['runtime_stop']==2 and server.done.is_set()
|
||||
|
||||
|
||||
def test_downstream_disconnect_closes_upstream_and_releases_slot():
|
||||
closed=Event()
|
||||
class Stream(httpx.AsyncByteStream):
|
||||
async def __aiter__(self):
|
||||
while True:
|
||||
yield b'a'*256
|
||||
await asyncio.sleep(.01)
|
||||
async def aclose(self): closed.set()
|
||||
with gateway(lambda r:httpx.Response(200,headers={'content-type':'audio/pcm'},stream=Stream()),timeout=.4,inactivity=.2) as server:
|
||||
with httpx.Client(timeout=1,trust_env=False) as client:
|
||||
with client.stream('POST',f'http://127.0.0.1:{server.server_port}/v1/audio/speech',content=b'{}',headers={'Authorization':'Bearer local-components'}) as result:
|
||||
assert next(result.iter_raw())
|
||||
wait_released(server)
|
||||
assert closed.is_set()
|
||||
|
||||
|
||||
def test_concurrency_slots_include_silent_connections_and_recover_after_expiry():
|
||||
with gateway(timeout=.3,inactivity=.15) as server:
|
||||
peers=[socket.create_connection(('127.0.0.1',server.server_port),timeout=1) for _ in range(4)]
|
||||
try:
|
||||
deadline=time.monotonic()+1
|
||||
while server.counts['rejected']<1 and time.monotonic()<deadline: time.sleep(.005)
|
||||
assert server.counts['rejected']==1 and server.counts['accepted']==3
|
||||
wait_released(server,3)
|
||||
finally:
|
||||
for peer in peers: peer.close()
|
||||
|
||||
|
||||
def test_asset_provisioning_is_local_only_and_emits_reviewable_fingerprint(tmp_path,monkeypatch,capsys):
|
||||
import services.local_s2s.assets as assets
|
||||
import sys
|
||||
roots,_=asset_bundle(tmp_path)
|
||||
output=tmp_path/'new-assets.json'
|
||||
monkeypatch.setattr(sys,'argv',['assets','--nltk-root',str(roots['nltk']),'--vad-root',str(roots['vad']),'--output',str(output)])
|
||||
assert assets.main()==0
|
||||
record=json.loads(capsys.readouterr().out)
|
||||
assert record['manifest_sha256']==validate_assets(roots['nltk'],roots['vad'],output)
|
||||
assert record['files']==len(REQUIRED_NLTK)+len(REQUIRED_VAD)
|
||||
|
||||
|
||||
def test_trickled_request_body_still_expires_on_total_deadline():
|
||||
with gateway(timeout=.2,inactivity=.1) as server:
|
||||
with socket.create_connection(('127.0.0.1',server.server_port),timeout=1) as client:
|
||||
client.sendall(b'POST /v1/audio/speech HTTP/1.1\r\nContent-Length: 100\r\n\r\n')
|
||||
began=time.monotonic()
|
||||
for _ in range(20):
|
||||
try: client.sendall(b'x')
|
||||
except OSError: break
|
||||
time.sleep(.02)
|
||||
try:
|
||||
closed=client.recv(1024)==b''
|
||||
except (ConnectionResetError, ConnectionAbortedError):
|
||||
closed=True # Windows resets a timed-out socket with unread body bytes.
|
||||
assert closed
|
||||
assert time.monotonic()-began<.7
|
||||
wait_released(server)
|
||||
assert server.counts['expired']==1 and server.counts['/v1/audio/speech']==0
|
||||
|
||||
|
||||
@pytest.mark.parametrize('invalid', [[], {'schema': 1, 'files': []}, {'schema': 1, 'files': None}])
|
||||
def test_malformed_asset_manifest_has_safe_category(tmp_path, invalid):
|
||||
roots, manifest = asset_bundle(tmp_path)
|
||||
manifest.write_text(json.dumps(invalid))
|
||||
with pytest.raises(AssetError, match='^LOCAL_ENGINE_ASSET_VALIDATION_FAILED$'):
|
||||
validate_assets(roots['nltk'], roots['vad'], manifest)
|
||||
|
||||
|
||||
def test_unusable_tokenizer_with_downloads_blocked_fails_before_provider_calls(tmp_path, monkeypatch, capsys):
|
||||
from services.local_s2s import engine
|
||||
import sys
|
||||
roots, manifest = asset_bundle(tmp_path)
|
||||
nltk = SimpleNamespace(data=SimpleNamespace(path=[], find=lambda p: p),
|
||||
download=lambda *a: pytest.fail('runtime download reached'),
|
||||
pos_tag=lambda *a, **kw: [])
|
||||
# A tokenizer trying to obtain a missing asset must hit the installed blocker.
|
||||
nltk.sent_tokenize = lambda text: nltk.download('punkt_tab')
|
||||
monkeypatch.setitem(sys.modules, 'nltk', nltk)
|
||||
monkeypatch.setattr(sys, 'argv', ['engine', '--allow-paid-startup'])
|
||||
for name, value in {'LOCAL_S2S_ALLOW_PAID_STARTUP': 'true',
|
||||
'LOCAL_S2S_NLTK_DATA': str(roots['nltk']), 'LOCAL_S2S_SILERO_SOURCE': str(roots['vad']),
|
||||
'LOCAL_S2S_ASSET_MANIFEST': str(manifest),
|
||||
'LOCAL_S2S_ASSET_MANIFEST_SHA256': hashlib.sha256(manifest.read_bytes()).hexdigest()}.items():
|
||||
monkeypatch.setenv(name, value)
|
||||
monkeypatch.setattr('app.modules.voice.configuration.VoiceSettings', lambda **kw: local_config())
|
||||
calls = []
|
||||
monkeypatch.setattr(engine, 'build_runtime', lambda *a: calls.append('provider'))
|
||||
assert engine.main() == 1 and calls == []
|
||||
assert 'LOCAL_ENGINE_ASSET_VALIDATION_FAILED' in capsys.readouterr().out
|
||||
|
||||
|
||||
@contextmanager
|
||||
def loopback_upstream(*, headers=False, hang_close=False):
|
||||
"""Real local TCP upstream: cancellation must close its actual HTTP socket."""
|
||||
entered, closed, transport_closed = Event(), Event(), Event()
|
||||
class Handler(socketserver.BaseRequestHandler):
|
||||
def handle(self):
|
||||
self.request.settimeout(6)
|
||||
try:
|
||||
data = b''
|
||||
while b'\r\n\r\n' not in data:
|
||||
data += self.request.recv(4096)
|
||||
head, body = data.split(b'\r\n\r\n', 1)
|
||||
size = int(next(line.split(b':', 1)[1] for line in head.split(b'\r\n') if line.lower().startswith(b'content-length:')))
|
||||
while len(body) < size:
|
||||
body += self.request.recv(size - len(body))
|
||||
if headers:
|
||||
self.request.sendall(b'HTTP/1.1 200 OK\r\nContent-Type: audio/pcm\r\nTransfer-Encoding: chunked\r\n\r\n')
|
||||
entered.set()
|
||||
# No data is produced. Only owned cancellation closes this socket.
|
||||
assert self.request.recv(1) == b''
|
||||
except ConnectionResetError:
|
||||
pass
|
||||
finally:
|
||||
closed.set()
|
||||
class Server(socketserver.ThreadingTCPServer):
|
||||
daemon_threads = True
|
||||
remote = Server(('127.0.0.1', 0), Handler)
|
||||
thread = Thread(target=remote.serve_forever, kwargs={'poll_interval': .01}, daemon=True)
|
||||
thread.start()
|
||||
class Transport(httpx.AsyncHTTPTransport):
|
||||
async def handle_async_request(self, request):
|
||||
request.url = httpx.URL(f'http://127.0.0.1:{remote.server_address[1]}' + request.url.path)
|
||||
return await super().handle_async_request(request)
|
||||
async def aclose(self):
|
||||
await super().aclose()
|
||||
transport_closed.set()
|
||||
if hang_close:
|
||||
await asyncio.Event().wait()
|
||||
try:
|
||||
yield Transport(retries=0), entered, closed, transport_closed
|
||||
finally:
|
||||
remote.shutdown(); remote.server_close(); thread.join(1)
|
||||
|
||||
|
||||
def speech_request(extra=b''):
|
||||
return (b'POST /v1/audio/speech HTTP/1.1\r\nContent-Length: 2\r\n'
|
||||
b'Authorization: Bearer local-components\r\n' + extra + b'\r\n{}')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('headers', [False, True], ids=['before-upstream-headers', 'stalled-after-headers'])
|
||||
def test_disconnect_cancels_silent_real_upstream_and_releases_slot(headers):
|
||||
with loopback_upstream(headers=headers) as (transport, entered, closed, transport_closed):
|
||||
with gateway(transport=transport, timeout=5, inactivity=4) as server:
|
||||
peer = socket.create_connection(('127.0.0.1', server.server_port), timeout=2)
|
||||
try:
|
||||
peer.sendall(speech_request())
|
||||
assert entered.wait(1)
|
||||
if headers:
|
||||
received = b''
|
||||
while b'\r\n\r\n' not in received:
|
||||
received += peer.recv(4096)
|
||||
assert received.startswith(b'HTTP/1.1 200')
|
||||
assert not received.endswith(b'0\r\n\r\n')
|
||||
began = time.monotonic()
|
||||
finally:
|
||||
peer.close()
|
||||
assert closed.wait(CLEANUP_WINDOW_SECONDS + .4)
|
||||
assert transport_closed.wait(.4)
|
||||
wait_released(server)
|
||||
assert time.monotonic() - began < CLEANUP_WINDOW_SECONDS + .6 < server.timeout
|
||||
assert server.counts['disconnected'] == 1 and server.counts['expired'] == 0
|
||||
assert server.counts['accepted'] == server.counts['released'] == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize('half_close', [False, True], ids=['normal', 'declared-receive-only-half-close'])
|
||||
def test_success_and_declared_half_close_receive_complete_response(half_close):
|
||||
entered = Event()
|
||||
async def remote(request):
|
||||
entered.set()
|
||||
await asyncio.sleep(.08) # receive-side EOF precedes upstream headers
|
||||
return httpx.Response(200, headers={'content-type': 'audio/pcm'}, content=b'xx')
|
||||
with gateway(remote, timeout=2, inactivity=1) as server:
|
||||
with socket.create_connection(('127.0.0.1', server.server_port), timeout=1) as peer:
|
||||
peer.sendall(speech_request(b'X-Local-S2S-Half-Close: receive-response\r\n' if half_close else b''))
|
||||
if half_close:
|
||||
peer.shutdown(socket.SHUT_WR)
|
||||
received = b''
|
||||
while part := peer.recv(4096):
|
||||
received += part
|
||||
assert entered.is_set()
|
||||
assert received.startswith(b'HTTP/1.1 200')
|
||||
assert received.endswith(b'2\r\nxx\r\n0\r\n\r\n')
|
||||
wait_released(server)
|
||||
assert server.counts['disconnected'] == server.counts['expired'] == 0
|
||||
|
||||
|
||||
def test_undeclared_half_close_is_explicit_cancellation_even_if_peer_can_receive():
|
||||
with loopback_upstream() as (transport, entered, closed, transport_closed):
|
||||
with gateway(transport=transport, timeout=5, inactivity=4) as server:
|
||||
with socket.create_connection(('127.0.0.1', server.server_port), timeout=2) as peer:
|
||||
peer.sendall(speech_request())
|
||||
assert entered.wait(1)
|
||||
peer.shutdown(socket.SHUT_WR)
|
||||
assert peer.recv(4096) == b'' # policy cancellation, not inferred inability to receive
|
||||
assert closed.wait(1) and transport_closed.wait(1)
|
||||
wait_released(server)
|
||||
assert server.counts['disconnected'] == 1 and server.counts['expired'] == 0
|
||||
|
||||
|
||||
def test_disconnect_cleanup_has_shared_bound_even_if_transport_close_stalls():
|
||||
with loopback_upstream(hang_close=True) as (transport, entered, closed, transport_closed):
|
||||
with gateway(transport=transport, timeout=5, inactivity=4) as server:
|
||||
peer = socket.create_connection(('127.0.0.1', server.server_port), timeout=2)
|
||||
peer.sendall(speech_request())
|
||||
assert entered.wait(1)
|
||||
began = time.monotonic()
|
||||
peer.close()
|
||||
assert closed.wait(1) and transport_closed.wait(1)
|
||||
wait_released(server)
|
||||
assert time.monotonic() - began < CLEANUP_WINDOW_SECONDS + .6 < server.timeout
|
||||
assert server.counts['close_errors'] >= 1
|
||||
|
||||
|
||||
LOCAL_IDENTIFIERS = ('local_s2s_stt_model', 'local_s2s_llm_model', 'local_s2s_tts_model', 'local_s2s_tts_voice')
|
||||
|
||||
|
||||
@pytest.mark.parametrize('field', LOCAL_IDENTIFIERS)
|
||||
@pytest.mark.parametrize('value', ['bad id', 'bad\tvalue', 'bad\nvalue', 'bad\x00value', 'bad\x7fvalue', 'bad\u00e9value'])
|
||||
def test_voice_settings_inherits_local_identifier_validation(field, value):
|
||||
from pydantic import ValidationError
|
||||
with pytest.raises(ValidationError, match='Invalid local component identifier'):
|
||||
local_config(**{field: value}) # constructs the real VoiceSettings, not the base class
|
||||
|
||||
|
||||
@pytest.mark.parametrize('field', LOCAL_IDENTIFIERS)
|
||||
def test_voice_settings_preserves_valid_local_identifiers(field):
|
||||
value = 'vendor/Valid-Model_1.2'
|
||||
assert getattr(local_config(**{field: value}), field) == value
|
||||
|
||||
|
||||
@pytest.mark.parametrize('field', LOCAL_IDENTIFIERS)
|
||||
def test_invalid_local_identifiers_fail_before_assets_gateway_or_provider(monkeypatch, field, capsys):
|
||||
from services.local_s2s import engine, assets, lifecycle
|
||||
import sys
|
||||
monkeypatch.setattr(sys, 'argv', ['engine', '--allow-paid-startup'])
|
||||
monkeypatch.setenv('LOCAL_S2S_ALLOW_PAID_STARTUP', 'true')
|
||||
monkeypatch.setenv(field.upper(), 'bad id')
|
||||
calls = []
|
||||
monkeypatch.setattr(assets, 'validate_assets', lambda *a: calls.append('assets'))
|
||||
monkeypatch.setattr(lifecycle, 'run_owned', lambda *a: calls.append('provider'))
|
||||
assert engine.main() == 1 and calls == []
|
||||
assert 'LOCAL_ENGINE_ASSET_VALIDATION_FAILED' in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_warmup_retry_constant_is_read_from_hash_checked_upstream_source():
|
||||
assert constant('base.py.source', 'WARMUP_MAX_RETRIES') == 6
|
||||
|
||||
|
||||
@pytest.mark.parametrize('field', ['gemini_model', 'gemini_voice', 'openai_realtime_model', 'openai_realtime_voice'])
|
||||
def test_existing_provider_identifier_validators_remain_active(field):
|
||||
from pydantic import ValidationError
|
||||
with pytest.raises(ValidationError, match='Invalid voice profile identifier'):
|
||||
local_config(**{field: 'bad id'})
|
||||
assert getattr(local_config(**{field: 'Valid-1.2'}), field) == 'Valid-1.2'
|
||||
Reference in New Issue
Block a user