Skip to content

Open full-duplex voice models that hear your tone and speak with one. One GPU with vLLM-Omni, or fully offline on a Mac with MLX. Zero-shot voice cloning, OpenAI Realtime / GPT-Live compatible, free hosted API trial. Apache-2.0.

1.6.2: say always finishes (#22); say works before the caller speaks

Adventists AI39046d4ba9c4
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..c18dd8d
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+__pycache__/
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 844bed1..3592905 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,14 @@ One version number for the whole Sophon-Realtime v1 family: the code in this rep
ModelScope (git tags with the same name) and the `sophon-realtime` package on PyPI. Each entry says which builds changed.
Second digit: new features or new weights; third digit: fixes only.
+## 1.6.2 (2026-11-23): say always finishes, and works before the caller speaks
+
+- **A `say` could stop before the end of the sentence** ([#22](https://github.com/adventists-ai/sophon-realtime/issues/22)). Its token limit was the sentence's normal tokenization plus 16. Constrained decoding may spell the same words with more, shorter tokens, so a long read-back on the 4B stopped at its limit mid-sentence. The limit is now the sentence's length in UTF-8 bytes plus 8. Every token spells at least one byte, so the sentence always fits.
+- When a `say` stops early (cut by the caller, or any other reason), the history and the log keep the words actually spoken, not the requested sentence. The log also says why it stopped.
+- **A `say` sent before the caller had spoken did nothing.** An example is a recording notice right at the start of a call. The engine only learned a session's tool-bridge key with its first reply or turn question, and the bridge opened only then. The bridge now opens when the engine starts. A `say` for a session that has not registered yet is queued, and unregistered sessions are asked to register (one throwaway turn question).
+- Verified on Flash 4B (the reporter's setup) through the Live gateway: 8 long read-backs (names, numbers, addresses, a Chinese one) × 3 rounds, all spoken to the end. The first `say` of each session was sent before any speech.
+- The plugins carry 1.6.2; the Live gateway did not change.
+
## 1.6.1 (2026-11-22): say waits for the current reply
- **`say` no longer cuts a reply that is still being spoken.** It now waits until the current reply has been generated and played (and the caller is silent). On E2E, whose replies take longer to generate, a `say` sent right after a tool answer used to cut that answer.
diff --git a/e2e/plugin/pyproject.toml b/e2e/plugin/pyproject.toml
index 269ac0e..bcd99d8 100644
--- a/e2e/plugin/pyproject.toml
+++ b/e2e/plugin/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "sophon-realtime-e2e"
-version = "1.6.1"
+version = "1.6.2"
description = "Sophon-Realtime-32B-E2E as one vLLM-Omni model: full-duplex listen + write (with sound tags) -> E2E talker (continuous voice vectors) -> decoder"
requires-python = ">=3.10"
license = "Apache-2.0"
diff --git a/e2e/plugin/sophon_realtime/__init__.py b/e2e/plugin/sophon_realtime/__init__.py
index b0412ee..9f22f17 100644
--- a/e2e/plugin/sophon_realtime/__init__.py
+++ b/e2e/plugin/sophon_realtime/__init__.py
@@ -3,7 +3,7 @@
E2E build (installed by e2e/install.sh as `sophon-realtime-e2e`): vllm serve <Sophon-Realtime-32B-E2E dir> --omni --deploy-config <yaml>
"""
-__version__ = "1.6.1"
+__version__ = "1.6.2"
ARCH = "SophonRealtimeForConditionalGeneration"
TALKER_ARCH = "SophonE2ETalker"
DECODER_ARCH = "SophonE2EDecoder"
diff --git a/e2e/plugin/sophon_realtime/__pycache__/bridge.cpython-310.pyc b/e2e/plugin/sophon_realtime/__pycache__/bridge.cpython-310.pyc
deleted file mode 100644
index 1db69a3..0000000
Binary files a/e2e/plugin/sophon_realtime/__pycache__/bridge.cpython-310.pyc and /dev/null differ
diff --git a/e2e/plugin/sophon_realtime/__pycache__/bridge220.cpython-310.pyc b/e2e/plugin/sophon_realtime/__pycache__/bridge220.cpython-310.pyc
deleted file mode 100644
index 48fc602..0000000
Binary files a/e2e/plugin/sophon_realtime/__pycache__/bridge220.cpython-310.pyc and /dev/null differ
diff --git a/e2e/plugin/sophon_realtime/__pycache__/duplex.cpython-310.pyc b/e2e/plugin/sophon_realtime/__pycache__/duplex.cpython-310.pyc
deleted file mode 100644
index eef7668..0000000
Binary files a/e2e/plugin/sophon_realtime/__pycache__/duplex.cpython-310.pyc and /dev/null differ
diff --git a/e2e/plugin/sophon_realtime/duplex.py b/e2e/plugin/sophon_realtime/duplex.py
index 7464e7c..e6026b5 100644
--- a/e2e/plugin/sophon_realtime/duplex.py
+++ b/e2e/plugin/sophon_realtime/duplex.py
@@ -293,6 +293,7 @@ class SophonBuffer(PcmAppendBuffer):
retry: dict | None = None # a reply append the framework did not accept: send it again as soon as appends are allowed
tool_followup: bool = False # a tool result is in history: speak the answer as soon as the user is silent
say_q: list = field(default_factory=list) # texts to speak verbatim (bridge /say), each as its own reply once the user is silent
+ need_bind: bool = False # a say arrived for a key no session has registered yet: announce ours
tool_mode: str = "mock" # "mock": run tool_mocks here; "client": hand calls to the gateway over the bridge
bridge_key: str | None = None
call_entry: dict = field(default_factory=dict) # client mode: call_id -> history entry the call belongs to
@@ -430,6 +431,11 @@ class SophonBuffer(PcmAppendBuffer):
r.rollback()
if self.inflight_t and now - self.inflight_t > 3.0:
self.inflight_t = 0.0
+ if self.need_bind and self.bridge_key is None and self.speech_ms == 0 and allow_emit and not self.reservations and not self.inflight_t:
+ self.need_bind = False
+ p = {"audio": base64.b64encode(np.zeros(SR // 10, np.float32).tobytes()).decode(), "format": "pcm_f32le", "sample_rate_hz": SR,
+ "is_speech": True, "sophon_kind": "bind", "sophon_buf": id(self), "lang": self.lang}
+ return self._res(operation_id, p)
if self.say_q and self.speech_ms == 0 and allow_emit and not self.reservations and not self.inflight_t and self._quiet_out():
text = self.say_q.pop(0); self.prev_user = None; self.t_reply = time.monotonic()
p = {"audio": base64.b64encode(np.zeros(SR // 10, np.float32).tobytes()).decode(), "format": "pcm_f32le", "sample_rate_hz": SR,
@@ -698,6 +704,11 @@ class SophonRealtimeDuplexPlugin(DuplexModelPlugin):
self._spec_lock = threading.Lock()
self._keys: dict[str, SophonBuffer] = {}
self.bridge = _bridge.Bridge(self._bridge_result, self._bridge_say)
+ self._orphan_say: dict = {} # bridge key -> [first time, [texts]] for says that arrived before the session bound
+ try:
+ self.bridge.start() # listen from the start: a say may come before any reply
+ except OSError as e:
+ logger.warning("sophon bridge: could not open at start (%s); will retry with the first session", e)
global _WARM_STARTED
if not _WARM_STARTED and os.environ.get("SOPHON_WARMUP", "1") != "0":
_WARM_STARTED = True; threading.Thread(target=_warm_turn_check, daemon=True).start()
@@ -806,6 +817,8 @@ class SophonRealtimeDuplexPlugin(DuplexModelPlugin):
key = runtime_config.get("bridge_key")
if key and buf.bridge_key != key:
buf.bridge_key = key; self._keys[key] = buf; self.bridge.start()
+ orphan = self._orphan_say.pop(key, None)
+ if orphan: buf.say_q.extend(orphan[1]); logger.info("sophon say: session bound, %d queued say(s)", len(orphan[1]))
with buf.lock:
if runtime_config.get("turn_fallback_s") is not None: buf.fb_s = float(runtime_config["turn_fallback_s"])
if runtime_config.get("min_release_s") is not None: buf.minrel_s = float(runtime_config["min_release_s"])
@@ -832,6 +845,10 @@ class SophonRealtimeDuplexPlugin(DuplexModelPlugin):
sf.write(os.path.join(dbg, f"{request_id.rsplit('.', 1)[-1]}_{kind}.wav"), audio, SR)
except Exception:
logger.exception("sophon debug dump failed")
+ if kind == "bind": # only registers the bridge key (above); answered by a throwaway turn question
+ text, perm = turn_question(lang, "")
+ self._reqs[request_id] = {"kind": "check", "buf": None, "perm": perm, "thr": 1.0, "top": {}}
+ return DuplexAppendPlan(prompt={"prompt": self._render([{"role": "user", "content": text}]), "multi_modal_data": {"audio": [(audio, SR)]}, "additional_information": addl})
if kind == "check":
text, perm = turn_question(lang, buf.last_said if buf else "")
prompt = self._render([{"role": "user", "content": text}])
@@ -852,7 +869,9 @@ class SophonRealtimeDuplexPlugin(DuplexModelPlugin):
p0 = sampling_params[0] if isinstance(sampling_params, (tuple, list)) else sampling_params # stage-0 params of this request
if p0 is not None:
p0.structured_outputs = StructuredOutputsParams(choice=[text])
- p0.max_tokens = len(self.tok.encode(text, add_special_tokens=False)) + 16
+ # constrained decoding may spell the sentence with more (shorter) tokens than its normal tokenization; every token
+ # spells at least one byte, so bytes + a few always fits
+ p0.max_tokens = len(text.encode("utf-8")) + 8
info = {"kind": "reply", "buf": buf, "user": None, "a_audio": [], "a_text": "", "t_plan": time.monotonic(),
"spec": False, "released": True, "dropped": False, "held": [], "say": text}
self._reqs[request_id] = info
@@ -1026,7 +1045,13 @@ class SophonRealtimeDuplexPlugin(DuplexModelPlugin):
buf.last_said = info["a_text"]
self._run_tools(buf, info["entry"], calls)
return
- if info.get("say") is not None and completed: info["a_text"] = info["say"] # the text as given, not the detokenized stream
+ if info.get("say") is not None:
+ full, spoken = info["say"], info["a_text"]
+ if completed and "".join(spoken.split()) == "".join(full.split()):
+ info["a_text"] = full # the text as given, not the detokenized stream
+ else: # keep what was actually spoken
+ logger.warning("sophon say: %s after %d of %d chars: %r", "stopped early" if completed else "cut by the user",
+ len(spoken), len(full), spoken[-80:])
entry = {"user": info["user"], "a_text": info["a_text"] + ("" if completed else "……(被用户打断)"),
"a_audio": a if completed and a is not None and a.size > SR // 10 else None}
cut = buf.cut
@@ -1086,8 +1111,16 @@ class SophonRealtimeDuplexPlugin(DuplexModelPlugin):
def _bridge_say(self, key, text):
"""A say from the gateway: speak this text verbatim as the next reply (after the user is silent) and keep it in history."""
buf = self._keys.get(key)
- if buf is None or not text.strip():
+ if not text.strip():
return False
+ if buf is None: # no reply yet in that session: have unbound sessions announce their key
+ now = time.monotonic()
+ for k in [k for k, v in self._orphan_say.items() if now - v[0] > 30]: self._orphan_say.pop(k, None)
+ self._orphan_say.setdefault(key, [now, []])[1].append(text.strip())
+ for b in list(self._bufs.values()):
+ if b.bridge_key is None: b.need_bind = True
+ logger.info("sophon say: key not bound yet, queued and asked sessions to bind")
+ return True
with buf.lock: buf.say_q.append(text.strip())
logger.info("sophon say: queued %r", text[:120])
return True
diff --git a/flash/plugin/pyproject.toml b/flash/plugin/pyproject.toml
index feca86b..10ea4f2 100644
--- a/flash/plugin/pyproject.toml
+++ b/flash/plugin/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "sophon-realtime-flash"
-version = "1.6.1"
+version = "1.6.2"
description = "Sophon-Realtime-32B-Flash as one vLLM-Omni model: full-duplex listen + write (with sound tags) -> 12.5 Hz streaming speech"
requires-python = ">=3.10"
license = "Apache-2.0"
diff --git a/flash/plugin/sophon_realtime/__init__.py b/flash/plugin/sophon_realtime/__init__.py
index 41854ff..4aa63c4 100644
--- a/flash/plugin/sophon_realtime/__init__.py
+++ b/flash/plugin/sophon_realtime/__init__.py
@@ -2,7 +2,7 @@
Flash build (installed by flash/install.sh as `sophon-realtime-flash`): vllm serve <Sophon-Realtime dir> --omni --deploy-config <sophon_realtime.yaml>
"""
-__version__ = "1.6.1"
+__version__ = "1.6.2"
ARCH = "SophonRealtimeForConditionalGeneration"
TALKER_ARCH = "SophonTTSTalker"
_done = False
diff --git a/flash/plugin/sophon_realtime/duplex.py b/flash/plugin/sophon_realtime/duplex.py
index 635b5ee..e7be91f 100644
--- a/flash/plugin/sophon_realtime/duplex.py
+++ b/flash/plugin/sophon_realtime/duplex.py
@@ -287,6 +287,7 @@ class SophonBuffer(PcmAppendBuffer):
retry: dict | None = None # a reply append the framework did not accept: send it again as soon as appends are allowed
tool_followup: bool = False # a tool result is in history: speak the answer as soon as the user is silent
say_q: list = field(default_factory=list) # texts to speak verbatim (bridge /say), each as its own reply once the user is silent
+ need_bind: bool = False # a say arrived for a key no session has registered yet: announce ours
tool_mode: str = "mock" # "mock": run tool_mocks here; "client": hand calls to the gateway over the bridge
bridge_key: str | None = None
call_entry: dict = field(default_factory=dict) # client mode: call_id -> history entry the call belongs to
@@ -424,6 +425,11 @@ class SophonBuffer(PcmAppendBuffer):
r.rollback()
if self.inflight_t and now - self.inflight_t > 3.0:
self.inflight_t = 0.0
+ if self.need_bind and self.bridge_key is None and self.speech_ms == 0 and allow_emit and not self.reservations and not self.inflight_t:
+ self.need_bind = False
+ p = {"audio": base64.b64encode(np.zeros(SR // 10, np.float32).tobytes()).decode(), "format": "pcm_f32le", "sample_rate_hz": SR,
+ "is_speech": True, "sophon_kind": "bind", "sophon_buf": id(self), "lang": self.lang}
+ return self._res(operation_id, p)
if self.say_q and self.speech_ms == 0 and allow_emit and not self.reservations and not self.inflight_t and self._quiet_out():
text = self.say_q.pop(0); self.prev_user = None; self.t_reply = time.monotonic()
p = {"audio": base64.b64encode(np.zeros(SR // 10, np.float32).tobytes()).decode(), "format": "pcm_f32le", "sample_rate_hz": SR,
@@ -686,6 +692,11 @@ class SophonRealtimeDuplexPlugin(DuplexModelPlugin):
self._spec_lock = threading.Lock()
self._keys: dict[str, SophonBuffer] = {}
self.bridge = _bridge.Bridge(self._bridge_result, self._bridge_say)
+ self._orphan_say: dict = {} # bridge key -> [first time, [texts]] for says that arrived before the session bound
+ try:
+ self.bridge.start() # listen from the start: a say may come before any reply
+ except OSError as e:
+ logger.warning("sophon bridge: could not open at start (%s); will retry with the first session", e)
global _WARM_STARTED
if not _WARM_STARTED and os.environ.get("SOPHON_WARMUP", "1") != "0":
_WARM_STARTED = True; threading.Thread(target=_warm_turn_check, daemon=True).start()
@@ -794,6 +805,8 @@ class SophonRealtimeDuplexPlugin(DuplexModelPlugin):
key = runtime_config.get("bridge_key")
if key and buf.bridge_key != key:
buf.bridge_key = key; self._keys[key] = buf; self.bridge.start()
+ orphan = self._orphan_say.pop(key, None)
+ if orphan: buf.say_q.extend(orphan[1]); logger.info("sophon say: session bound, %d queued say(s)", len(orphan[1]))
with buf.lock:
if runtime_config.get("turn_fallback_s") is not None: buf.fb_s = float(runtime_config["turn_fallback_s"])
if runtime_config.get("min_release_s") is not None: buf.minrel_s = float(runtime_config["min_release_s"])
@@ -820,6 +833,10 @@ class SophonRealtimeDuplexPlugin(DuplexModelPlugin):
sf.write(os.path.join(dbg, f"{request_id.rsplit('.', 1)[-1]}_{kind}.wav"), audio, SR)
except Exception:
logger.exception("sophon debug dump failed")
+ if kind == "bind": # only registers the bridge key (above); answered by a throwaway turn question
+ text, perm = turn_question(lang, "")
+ self._reqs[request_id] = {"kind": "check", "buf": None, "perm": perm, "thr": 1.0, "top": {}}
+ return DuplexAppendPlan(prompt={"prompt": self._render([{"role": "user", "content": text}]), "multi_modal_data": {"audio": [(audio, SR)]}, "additional_information": addl})
if kind == "check":
text, perm = turn_question(lang, buf.last_said if buf else "")
prompt = self._render([{"role": "user", "content": text}])
@@ -840,7 +857,9 @@ class SophonRealtimeDuplexPlugin(DuplexModelPlugin):
p0 = sampling_params[0] if isinstance(sampling_params, (tuple, list)) else sampling_params # stage-0 params of this request
if p0 is not None:
p0.structured_outputs = StructuredOutputsParams(choice=[text])
- p0.max_tokens = len(self.tok.encode(text, add_special_tokens=False)) + 16
+ # constrained decoding may spell the sentence with more (shorter) tokens than its normal tokenization; every token
+ # spells at least one byte, so bytes + a few always fits
+ p0.max_tokens = len(text.encode("utf-8")) + 8
info = {"kind": "reply", "buf": buf, "user": None, "a_audio": [], "a_text": "", "t_plan": time.monotonic(),
"spec": False, "released": True, "dropped": False, "held": [], "say": text}
self._reqs[request_id] = info
@@ -1011,7 +1030,13 @@ class SophonRealtimeDuplexPlugin(DuplexModelPlugin):
buf.last_said = info["a_text"]
self._run_tools(buf, info["entry"], calls)
return
- if info.get("say") is not None and completed: info["a_text"] = info["say"] # the text as given, not the detokenized stream
+ if info.get("say") is not None:
+ full, spoken = info["say"], info["a_text"]
+ if completed and "".join(spoken.split()) == "".join(full.split()):
+ info["a_text"] = full # the text as given, not the detokenized stream
+ else: # keep what was actually spoken
+ logger.warning("sophon say: %s after %d of %d chars: %r", "stopped early" if completed else "cut by the user",
+ len(spoken), len(full), spoken[-80:])
entry = {"user": info["user"], "a_text": info["a_text"] + ("" if completed else "……(被用户打断)"),
"a_audio": a if completed and a is not None and a.size > SR // 10 else None}
cut = buf.cut
@@ -1071,8 +1096,16 @@ class SophonRealtimeDuplexPlugin(DuplexModelPlugin):
def _bridge_say(self, key, text):
"""A say from the gateway: speak this text verbatim as the next reply (after the user is silent) and keep it in history."""
buf = self._keys.get(key)
- if buf is None or not text.strip():
+ if not text.strip():
return False
+ if buf is None: # no reply yet in that session: have unbound sessions announce their key
+ now = time.monotonic()
+ for k in [k for k, v in self._orphan_say.items() if now - v[0] > 30]: self._orphan_say.pop(k, None)
+ self._orphan_say.setdefault(key, [now, []])[1].append(text.strip())
+ for b in list(self._bufs.values()):
+ if b.bridge_key is None: b.need_bind = True
+ logger.info("sophon say: key not bound yet, queued and asked sessions to bind")
+ return True
with buf.lock: buf.say_q.append(text.strip())
logger.info("sophon say: queued %r", text[:120])
return True
diff --git a/live/sophon_live/__pycache__/adapters.cpython-310.pyc b/live/sophon_live/__pycache__/adapters.cpython-310.pyc
deleted file mode 100644
index c1c92b3..0000000
Binary files a/live/sophon_live/__pycache__/adapters.cpython-310.pyc and /dev/null differ
diff --git a/live/sophon_live/__pycache__/realtime.cpython-310.pyc b/live/sophon_live/__pycache__/realtime.cpython-310.pyc
deleted file mode 100644
index 57bafd7..0000000
Binary files a/live/sophon_live/__pycache__/realtime.cpython-310.pyc and /dev/null differ
diff --git a/tag/plugin/pyproject.toml b/tag/plugin/pyproject.toml
index 2a0ab49..c7da961 100644
--- a/tag/plugin/pyproject.toml
+++ b/tag/plugin/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "sophon-realtime-tag"
-version = "1.6.1"
+version = "1.6.2"
description = "Sophon-Realtime-32B-Tag as one vLLM-Omni model: full-duplex listen + write (with sound tags) -> tag-tts streaming speech"
requires-python = ">=3.10"
license = "Apache-2.0"
diff --git a/tag/plugin/sophon_realtime/__init__.py b/tag/plugin/sophon_realtime/__init__.py
index aafc8e4..21e1bca 100644
--- a/tag/plugin/sophon_realtime/__init__.py
+++ b/tag/plugin/sophon_realtime/__init__.py
@@ -3,7 +3,7 @@ bistream style while it is written) -> CosyVoice3 flow + HiFT, served as one vLL
vllm serve <Sophon-Realtime-32B-Tag dir> --omni --deploy-config <sophon_realtime_tag_1gpu.yaml>
"""
-__version__ = "1.6.1"
+__version__ = "1.6.2"
ARCH = "SophonRealtimeForConditionalGeneration"
TALKER_ARCH = "SophonTagTalker"
_done = False
diff --git a/tag/plugin/sophon_realtime/__pycache__/bridge.cpython-310.pyc b/tag/plugin/sophon_realtime/__pycache__/bridge.cpython-310.pyc
deleted file mode 100644
index 1dcb81d..0000000
Binary files a/tag/plugin/sophon_realtime/__pycache__/bridge.cpython-310.pyc and /dev/null differ
diff --git a/tag/plugin/sophon_realtime/__pycache__/duplex.cpython-310.pyc b/tag/plugin/sophon_realtime/__pycache__/duplex.cpython-310.pyc
deleted file mode 100644
index fbc54fa..0000000
Binary files a/tag/plugin/sophon_realtime/__pycache__/duplex.cpython-310.pyc and /dev/null differ
diff --git a/tag/plugin/sophon_realtime/duplex.py b/tag/plugin/sophon_realtime/duplex.py
index 7464e7c..e6026b5 100644
--- a/tag/plugin/sophon_realtime/duplex.py
+++ b/tag/plugin/sophon_realtime/duplex.py
@@ -293,6 +293,7 @@ class SophonBuffer(PcmAppendBuffer):
retry: dict | None = None # a reply append the framework did not accept: send it again as soon as appends are allowed
tool_followup: bool = False # a tool result is in history: speak the answer as soon as the user is silent
say_q: list = field(default_factory=list) # texts to speak verbatim (bridge /say), each as its own reply once the user is silent
+ need_bind: bool = False # a say arrived for a key no session has registered yet: announce ours
tool_mode: str = "mock" # "mock": run tool_mocks here; "client": hand calls to the gateway over the bridge
bridge_key: str | None = None
call_entry: dict = field(default_factory=dict) # client mode: call_id -> history entry the call belongs to
@@ -430,6 +431,11 @@ class SophonBuffer(PcmAppendBuffer):
r.rollback()
if self.inflight_t and now - self.inflight_t > 3.0:
self.inflight_t = 0.0
+ if self.need_bind and self.bridge_key is None and self.speech_ms == 0 and allow_emit and not self.reservations and not self.inflight_t:
+ self.need_bind = False
+ p = {"audio": base64.b64encode(np.zeros(SR // 10, np.float32).tobytes()).decode(), "format": "pcm_f32le", "sample_rate_hz": SR,
+ "is_speech": True, "sophon_kind": "bind", "sophon_buf": id(self), "lang": self.lang}
+ return self._res(operation_id, p)
if self.say_q and self.speech_ms == 0 and allow_emit and not self.reservations and not self.inflight_t and self._quiet_out():
text = self.say_q.pop(0); self.prev_user = None; self.t_reply = time.monotonic()
p = {"audio": base64.b64encode(np.zeros(SR // 10, np.float32).tobytes()).decode(), "format": "pcm_f32le", "sample_rate_hz": SR,
@@ -698,6 +704,11 @@ class SophonRealtimeDuplexPlugin(DuplexModelPlugin):
self._spec_lock = threading.Lock()
self._keys: dict[str, SophonBuffer] = {}
self.bridge = _bridge.Bridge(self._bridge_result, self._bridge_say)
+ self._orphan_say: dict = {} # bridge key -> [first time, [texts]] for says that arrived before the session bound
+ try:
+ self.bridge.start() # listen from the start: a say may come before any reply
+ except OSError as e:
+ logger.warning("sophon bridge: could not open at start (%s); will retry with the first session", e)
global _WARM_STARTED
if not _WARM_STARTED and os.environ.get("SOPHON_WARMUP", "1") != "0":
_WARM_STARTED = True; threading.Thread(target=_warm_turn_check, daemon=True).start()
@@ -806,6 +817,8 @@ class SophonRealtimeDuplexPlugin(DuplexModelPlugin):
key = runtime_config.get("bridge_key")
if key and buf.bridge_key != key:
buf.bridge_key = key; self._keys[key] = buf; self.bridge.start()
+ orphan = self._orphan_say.pop(key, None)
+ if orphan: buf.say_q.extend(orphan[1]); logger.info("sophon say: session bound, %d queued say(s)", len(orphan[1]))
with buf.lock:
if runtime_config.get("turn_fallback_s") is not None: buf.fb_s = float(runtime_config["turn_fallback_s"])
if runtime_config.get("min_release_s") is not None: buf.minrel_s = float(runtime_config["min_release_s"])
@@ -832,6 +845,10 @@ class SophonRealtimeDuplexPlugin(DuplexModelPlugin):
sf.write(os.path.join(dbg, f"{request_id.rsplit('.', 1)[-1]}_{kind}.wav"), audio, SR)
except Exception:
logger.exception("sophon debug dump failed")
+ if kind == "bind": # only registers the bridge key (above); answered by a throwaway turn question
+ text, perm = turn_question(lang, "")
+ self._reqs[request_id] = {"kind": "check", "buf": None, "perm": perm, "thr": 1.0, "top": {}}
+ return DuplexAppendPlan(prompt={"prompt": self._render([{"role": "user", "content": text}]), "multi_modal_data": {"audio": [(audio, SR)]}, "additional_information": addl})
if kind == "check":
text, perm = turn_question(lang, buf.last_said if buf else "")
prompt = self._render([{"role": "user", "content": text}])
@@ -852,7 +869,9 @@ class SophonRealtimeDuplexPlugin(DuplexModelPlugin):
p0 = sampling_params[0] if isinstance(sampling_params, (tuple, list)) else sampling_params # stage-0 params of this request
if p0 is not None:
p0.structured_outputs = StructuredOutputsParams(choice=[text])
- p0.max_tokens = len(self.tok.encode(text, add_special_tokens=False)) + 16
+ # constrained decoding may spell the sentence with more (shorter) tokens than its normal tokenization; every token
+ # spells at least one byte, so bytes + a few always fits
+ p0.max_tokens = len(text.encode("utf-8")) + 8
info = {"kind": "reply", "buf": buf, "user": None, "a_audio": [], "a_text": "", "t_plan": time.monotonic(),
"spec": False, "released": True, "dropped": False, "held": [], "say": text}
self._reqs[request_id] = info
@@ -1026,7 +1045,13 @@ class SophonRealtimeDuplexPlugin(DuplexModelPlugin):
buf.last_said = info["a_text"]
self._run_tools(buf, info["entry"], calls)
return
- if info.get("say") is not None and completed: info["a_text"] = info["say"] # the text as given, not the detokenized stream
+ if info.get("say") is not None:
+ full, spoken = info["say"], info["a_text"]
+ if completed and "".join(spoken.split()) == "".join(full.split()):
+ info["a_text"] = full # the text as given, not the detokenized stream
+ else: # keep what was actually spoken
+ logger.warning("sophon say: %s after %d of %d chars: %r", "stopped early" if completed else "cut by the user",
+ len(spoken), len(full), spoken[-80:])
entry = {"user": info["user"], "a_text": info["a_text"] + ("" if completed else "……(被用户打断)"),
"a_audio": a if completed and a is not None and a.size > SR // 10 else None}
cut = buf.cut
@@ -1086,8 +1111,16 @@ class SophonRealtimeDuplexPlugin(DuplexModelPlugin):
def _bridge_say(self, key, text):
"""A say from the gateway: speak this text verbatim as the next reply (after the user is silent) and keep it in history."""
buf = self._keys.get(key)
- if buf is None or not text.strip():
+ if not text.strip():
return False
+ if buf is None: # no reply yet in that session: have unbound sessions announce their key
+ now = time.monotonic()
+ for k in [k for k, v in self._orphan_say.items() if now - v[0] > 30]: self._orphan_say.pop(k, None)
+ self._orphan_say.setdefault(key, [now, []])[1].append(text.strip())
+ for b in list(self._bufs.values()):
+ if b.bridge_key is None: b.need_bind = True
+ logger.info("sophon say: key not bound yet, queued and asked sessions to bind")
+ return True
with buf.lock: buf.say_q.append(text.strip())
logger.info("sophon say: queued %r", text[:120])
return True