[Full Duplex] Feat: Support Full-Duplex realtime runtime & add MiniCPM-o 4.5 demo (#3907)

Signed-off-by: Sy03 <1370724210@qq.com>
Signed-off-by: lishunyang12 <lishunyang03@gmail.com>
Signed-off-by: Yueqian Lin <linyueqian@outlook.com>
Co-authored-by: lishunyang12 <lishunyang03@gmail.com>
Co-authored-by: Yueqian Lin <linyueqian@outlook.com>
Co-authored-by: StormMelody <22371184@zju.edu.cn>
Co-authored-by: Gao Han <hgaoaf@connect.ust.hk>
Co-authored-by: Hongsheng Liu <liuhongsheng4@huawei.com>
This commit is contained in:
authored and GitHub committed 2026-07-23 16:45:18 +08:00
1 parent b55120c93b
commit 05b794f29b
142 files changed
+48389 -1013

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -0,0 +1,388 @@
"""Run two MiniCPM-o Realtime duplex demo processes concurrently.
This E2E driver covers the same process boundary users exercise manually:
two independent ``realtime_duplex_demo.py`` invocations, two distinct input
WAVs, and two distinct output directories.
"""
from __future__ import annotations
import argparse
import asyncio
import base64
import hashlib
import io
import json
import sys
import uuid
import wave
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[3]
DEMO_PATH = REPO_ROOT / "examples/online_serving/minicpmo/realtime_duplex_demo.py"
AUDIO_DELTA_EVENTS = {"response.audio.delta", "response.output_audio.delta"}
def _canonical_path(path: str) -> Path:
return Path(path).expanduser().resolve(strict=False)
def _sha256_file(path: Path) -> str:
hasher = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
hasher.update(chunk)
return hasher.hexdigest()
def _validate_pair_args(args: argparse.Namespace) -> dict[str, object]:
input_a = _canonical_path(args.input_wav_a)
input_b = _canonical_path(args.input_wav_b)
output_a = _canonical_path(args.output_dir_a)
output_b = _canonical_path(args.output_dir_b)
if output_a == output_b:
raise ValueError("output directories must be different")
if not input_a.is_file():
raise ValueError(f"input WAV does not exist: {input_a}")
if not input_b.is_file():
raise ValueError(f"input WAV does not exist: {input_b}")
sha_a = _sha256_file(input_a)
sha_b = _sha256_file(input_b)
if sha_a == sha_b:
raise ValueError("input WAV files must have different content")
return {
"input_wav_a": str(input_a),
"input_wav_b": str(input_b),
"input_sha256_a": sha_a,
"input_sha256_b": sha_b,
"output_dir_a": str(output_a),
"output_dir_b": str(output_b),
}
def _event_response_id(event: dict[str, object]) -> str | None:
response_id = event.get("response_id")
if isinstance(response_id, str):
return response_id
response = event.get("response")
if isinstance(response, dict) and isinstance(response.get("id"), str):
return response["id"]
return None
def _read_json(path: Path) -> dict[str, object]:
if not path.is_file():
return {}
data = json.loads(path.read_text(encoding="utf-8"))
return data if isinstance(data, dict) else {}
def _read_events(path: Path) -> list[dict[str, object]]:
if not path.is_file():
return []
events: list[dict[str, object]] = []
for line in path.read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
event = json.loads(line)
if isinstance(event, dict):
events.append(event)
return events
def _response_ids_from_artifacts(result: dict[str, object], events: list[dict[str, object]]) -> list[str]:
response_ids = result.get("response_ids")
if isinstance(response_ids, list):
ids = [item for item in response_ids if isinstance(item, str)]
if ids:
return ids
seen: list[str] = []
for event in events:
response_id = _event_response_id(event)
if response_id is not None and response_id not in seen:
seen.append(response_id)
return seen
def _audio_delta_duration_ms(event: dict[str, object]) -> float | None:
encoded = event.get("delta") or event.get("audio")
if not isinstance(encoded, str) or not encoded:
return None
try:
raw = base64.b64decode(encoded)
except ValueError:
return None
fmt = str(event.get("format") or event.get("audio_format") or "pcm16").lower()
sample_rate = event.get("sample_rate_hz") or event.get("sample_rate") or 24_000
if not isinstance(sample_rate, int | float) or sample_rate <= 0:
return None
if "wav" in fmt:
try:
with wave.open(io.BytesIO(raw), "rb") as wav:
return round((wav.getnframes() * 1000.0) / wav.getframerate(), 3)
except (EOFError, wave.Error):
return None
bytes_per_sample = 4 if "f32" in fmt else 2
return round((len(raw) * 1000.0) / (bytes_per_sample * float(sample_rate)), 3)
def _audio_delta_received_at_s(event: dict[str, object]) -> float | None:
raw = event.get("_client_received_at_s")
if isinstance(raw, int | float):
return float(raw)
return None
def _session_audio_contract_ok(
*,
audio_delta_count: int,
delta_response_ids: list[str],
response_ids: list[str],
first_audio_delta_before_done: bool,
) -> bool:
if audio_delta_count <= 0 or not response_ids:
return False
if len(delta_response_ids) != audio_delta_count:
return False
delta_id_set = set(delta_response_ids)
if len(delta_id_set) != 1:
return False
return first_audio_delta_before_done and next(iter(delta_id_set)) in set(response_ids)
def _summarize_session(
*,
label: str,
input_wav: str,
output_dir: str,
returncode: int,
stdout: str,
stderr: str,
) -> dict[str, object]:
output_path = Path(output_dir)
result = _read_json(output_path / "result.json")
events = _read_events(output_path / "events.jsonl")
audio_delta_indices = [index for index, event in enumerate(events) if event.get("type") in AUDIO_DELTA_EVENTS]
done_indices = [index for index, event in enumerate(events) if event.get("type") == "response.done"]
response_ids = _response_ids_from_artifacts(result, events)
delta_response_ids = [
response_id
for response_id in (_event_response_id(events[index]) for index in audio_delta_indices)
if response_id is not None
]
first_audio_delta_before_done = bool(audio_delta_indices and done_indices) and min(audio_delta_indices) < min(
done_indices
)
audio_delta_events = [events[index] for index in audio_delta_indices]
first_received_at_s = next(
(
received_at
for received_at in (_audio_delta_received_at_s(event) for event in audio_delta_events)
if received_at is not None
),
None,
)
audio_delta_timings = []
for event in audio_delta_events:
received_at_s = _audio_delta_received_at_s(event)
audio_delta_timings.append(
{
"response_id": _event_response_id(event),
"received_at_s": received_at_s,
"arrival_offset_ms": (
round((received_at_s - first_received_at_s) * 1000.0, 3)
if received_at_s is not None and first_received_at_s is not None
else None
),
"audio_duration_ms": _audio_delta_duration_ms(event),
}
)
all_audio_deltas_same_response = (
len(delta_response_ids) == len(audio_delta_indices) and len(set(delta_response_ids)) == 1
)
response_id_nonempty = bool(response_ids)
response_audio_contract_ok = _session_audio_contract_ok(
audio_delta_count=len(audio_delta_indices),
delta_response_ids=delta_response_ids,
response_ids=response_ids,
first_audio_delta_before_done=first_audio_delta_before_done,
)
return {
"label": label,
"input_wav": input_wav,
"output_dir": output_dir,
"returncode": returncode,
"ok": returncode == 0 and result.get("ok") is True and response_audio_contract_ok,
"result_ok": result.get("ok"),
"response_ids": response_ids,
"response_id_nonempty": response_id_nonempty,
"audio_bytes": result.get("audio_bytes", 0),
"audio_delta_count": len(audio_delta_indices),
"audio_delta_response_ids": delta_response_ids,
"audio_delta_timings": audio_delta_timings,
"all_audio_deltas_same_response": all_audio_deltas_same_response,
"first_audio_delta_before_done": first_audio_delta_before_done,
"response_audio_contract_ok": response_audio_contract_ok,
"event_count": len(events),
"stdout_tail": stdout[-4000:],
"stderr_tail": stderr[-4000:],
}
def _identity_isolation_ok(sessions: list[dict[str, object]]) -> bool:
seen: set[str] = set()
for session in sessions:
ids = {response_id for response_id in session.get("response_ids", []) if isinstance(response_id, str)}
if not ids:
return False
if ids & seen:
return False
seen.update(ids)
return True
async def _run_demo_process(
*,
label: str,
args: argparse.Namespace,
input_wav: str,
output_dir: str,
) -> dict[str, object]:
command = [
sys.executable,
str(DEMO_PATH),
"--url",
args.url,
"--model",
args.model,
"--input-wav",
input_wav,
"--output-dir",
output_dir,
"--chunk-ms",
str(args.chunk_ms),
"--timeout-s",
str(args.timeout_s),
"--session-id",
f"duplex-pair-{label}-{uuid.uuid4().hex}",
]
if args.no_realtime_pacing:
command.append("--no-realtime-pacing")
if args.require_audio:
command.append("--require-audio")
command.extend(["--ref-audio", str(args.ref_audio)])
process = await asyncio.create_subprocess_exec(
*command,
cwd=str(REPO_ROOT),
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
try:
stdout_bytes, stderr_bytes = await asyncio.wait_for(
process.communicate(),
timeout=args.timeout_s + 15.0,
)
except TimeoutError:
process.kill()
stdout_bytes, stderr_bytes = await process.communicate()
return _summarize_session(
label=label,
input_wav=input_wav,
output_dir=output_dir,
returncode=-1,
stdout=stdout_bytes.decode(errors="replace"),
stderr=(stderr_bytes.decode(errors="replace") + "\nclient timeout"),
)
return _summarize_session(
label=label,
input_wav=input_wav,
output_dir=output_dir,
returncode=process.returncode if process.returncode is not None else -1,
stdout=stdout_bytes.decode(errors="replace"),
stderr=stderr_bytes.decode(errors="replace"),
)
async def run_pair(args: argparse.Namespace) -> dict[str, object]:
validated = _validate_pair_args(args)
Path(validated["output_dir_a"]).mkdir(parents=True, exist_ok=True)
Path(validated["output_dir_b"]).mkdir(parents=True, exist_ok=True)
sessions = await asyncio.gather(
_run_demo_process(
label="a",
args=args,
input_wav=str(validated["input_wav_a"]),
output_dir=str(validated["output_dir_a"]),
),
_run_demo_process(
label="b",
args=args,
input_wav=str(validated["input_wav_b"]),
output_dir=str(validated["output_dir_b"]),
),
)
identity_isolation_ok = _identity_isolation_ok(sessions)
min_audio_delta_ok = all(
int(session.get("audio_delta_count", 0)) >= args.min_audio_deltas_per_session for session in sessions
)
response_audio_contract_ok = all(session.get("response_audio_contract_ok") is True for session in sessions)
result = {
"ok": (
all(session.get("ok") is True for session in sessions)
and identity_isolation_ok
and min_audio_delta_ok
and response_audio_contract_ok
),
"input_wavs_distinct": True,
"output_dirs_distinct": True,
"identity_isolation_ok": identity_isolation_ok,
"min_audio_deltas_per_session": args.min_audio_deltas_per_session,
"min_audio_delta_ok": min_audio_delta_ok,
"response_audio_contract_ok": response_audio_contract_ok,
"inputs": {
"a": validated["input_wav_a"],
"b": validated["input_wav_b"],
"sha256_a": validated["input_sha256_a"],
"sha256_b": validated["input_sha256_b"],
},
"sessions": sessions,
}
summary_output = (
Path(args.summary_output) if args.summary_output else Path(validated["output_dir_a"]).parent / "summary.json"
)
summary_output.parent.mkdir(parents=True, exist_ok=True)
summary_output.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
return result
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("--url", default="ws://127.0.0.1:8099/v1/realtime?duplex=1")
parser.add_argument("--model", default="openbmb/MiniCPM-o-4_5")
parser.add_argument("--input-wav-a", required=True)
parser.add_argument("--input-wav-b", required=True)
parser.add_argument("--ref-audio", required=True)
parser.add_argument("--output-dir-a", required=True)
parser.add_argument("--output-dir-b", required=True)
parser.add_argument("--summary-output")
parser.add_argument("--chunk-ms", type=int, default=200)
parser.add_argument("--timeout-s", type=float, default=120.0)
parser.add_argument("--no-realtime-pacing", action="store_true")
parser.add_argument("--require-audio", action="store_true")
parser.add_argument("--min-audio-deltas-per-session", type=int, default=2)
args = parser.parse_args()
if args.min_audio_deltas_per_session < 0:
parser.error("--min-audio-deltas-per-session must be non-negative")
return args
def main() -> None:
result = asyncio.run(run_pair(parse_args()))
print(json.dumps(result, ensure_ascii=False, indent=2))
raise SystemExit(0 if result["ok"] else 1)
if __name__ == "__main__":
main()
@@ -0,0 +1,556 @@
"""Concurrent MiniCPM-o Realtime duplex and resumable-session E2E driver."""
from __future__ import annotations
import argparse
import asyncio
import hashlib
import json
import sys
import uuid
from pathlib import Path
from types import SimpleNamespace
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
import websockets
from websockets.exceptions import ConnectionClosed
SCRIPT_DIR = Path(__file__).resolve().parent
if str(SCRIPT_DIR) not in sys.path:
sys.path.insert(0, str(SCRIPT_DIR))
from minicpmo_realtime_duplex_scenarios import _url_with_model, run_demo # noqa: E402
def _with_resume_mode(url: str) -> str:
parts = urlsplit(url)
query = dict(parse_qsl(parts.query, keep_blank_values=True))
query["resume"] = "1"
return urlunsplit((parts.scheme, parts.netloc, parts.path, urlencode(query), parts.fragment))
def _response_ids(result: dict[str, object]) -> set[str]:
values = result.get("completed_response_ids")
return {value for value in values if isinstance(value, str)} if isinstance(values, list) else set()
def _event_session_id(event: dict[str, object]) -> str | None:
session_id = event.get("session_id")
if isinstance(session_id, str):
return session_id
inner = event.get("event")
if isinstance(inner, dict):
nested_session_id = inner.get("session_id")
if isinstance(nested_session_id, str):
return nested_session_id
return None
def _error_code(event: dict[str, object]) -> str | None:
error = event.get("error")
if isinstance(error, dict) and isinstance(error.get("code"), str):
return error["code"]
code = event.get("code")
return code if isinstance(code, str) else None
def _validate_identity_isolation(results: list[dict[str, object]]) -> bool:
seen: set[str] = set()
for result in results:
current = _response_ids(result)
if current & seen:
return False
seen.update(current)
return True
def _validate_semantic_isolation(
results: list[dict[str, object]],
*,
input_wavs: list[str],
expected_tokens: list[str],
) -> bool:
if not input_wavs:
return True
if len(results) != len(input_wavs):
return False
input_hashes = [hashlib.sha256(Path(path).read_bytes()).digest() for path in input_wavs]
if len(set(input_hashes)) != len(input_hashes):
return False
if not expected_tokens:
return True
if len(expected_tokens) != len(results):
return False
for result, expected_token in zip(results, expected_tokens, strict=True):
details = result.get("transcript_integrity")
transcripts = (
[str(item.get("transcript", "")) for item in details if isinstance(item, dict)]
if isinstance(details, list)
else []
)
if expected_token not in "".join(transcripts):
return False
return True
async def _receive_until(ws, event_type: str, *, timeout_s: float) -> tuple[dict[str, object], list[dict[str, object]]]:
async def receive() -> tuple[dict[str, object], list[dict[str, object]]]:
events: list[dict[str, object]] = []
while True:
raw = await ws.recv()
if not isinstance(raw, str):
continue
event = json.loads(raw)
if not isinstance(event, dict):
continue
events.append(event)
if event.get("type") == event_type:
return event, events
return await asyncio.wait_for(receive(), timeout=timeout_s)
async def _open_admission_session(
args: argparse.Namespace,
session_id: str,
) -> tuple[object, dict[str, object]]:
url = _url_with_model(args.url, args.model, session_id=session_id)
ws = await websockets.connect(url, max_size=64 * 1024 * 1024)
await ws.send(
json.dumps(
{
"type": "session.update",
"session": {
"session_id": session_id,
"model": args.model,
"modalities": ["audio", "text"],
"extra_body": {"minicpmo45_native_duplex": True},
},
}
)
)
created, _ = await _receive_until(ws, "session.created", timeout_s=args.timeout_s)
return ws, created
async def _close_admission_session(ws, *, timeout_s: float) -> None:
await ws.send(json.dumps({"type": "session.close"}))
await _receive_until(ws, "session.closed", timeout_s=timeout_s)
await ws.close()
async def _admission_probe(args: argparse.Namespace, *, limit: int) -> dict[str, object]:
if limit < 1:
raise ValueError("admission limit must be positive")
prefix = f"admission-{uuid.uuid4().hex}"
accepted: list[tuple[object, dict[str, object]]] = []
replacement: tuple[object, dict[str, object]] | None = None
overflow_code = None
try:
for index in range(limit):
accepted.append(await _open_admission_session(args, f"{prefix}-accepted-{index}"))
overflow_id = f"{prefix}-overflow"
overflow_url = _url_with_model(args.url, args.model, session_id=overflow_id)
async with websockets.connect(overflow_url, max_size=64 * 1024 * 1024) as overflow:
await overflow.send(
json.dumps(
{
"type": "session.update",
"session": {
"session_id": overflow_id,
"model": args.model,
"modalities": ["audio", "text"],
"extra_body": {"minicpmo45_native_duplex": True},
},
}
)
)
error, _ = await _receive_until(overflow, "error", timeout_s=args.timeout_s)
overflow_code = _error_code(error)
first_ws, _ = accepted.pop(0)
await _close_admission_session(first_ws, timeout_s=args.timeout_s)
replacement = await _open_admission_session(args, f"{prefix}-replacement")
first_capabilities = accepted[0][1].get("session") if accepted else replacement[1].get("session")
capabilities = first_capabilities.get("capabilities") if isinstance(first_capabilities, dict) else None
advertised_multi = capabilities.get("supports_multi_session") if isinstance(capabilities, dict) else None
admission_mode = capabilities.get("session_admission_mode") if isinstance(capabilities, dict) else None
return {
"ok": (
overflow_code == "resource_exhausted"
and replacement[1].get("type") == "session.created"
and admission_mode == "engine_managed"
),
"configured_limit": limit,
"accepted_before_rejection": limit,
"overflow_error_code": overflow_code,
"replacement_accepted": True,
"advertised_multi_session": advertised_multi,
"session_admission_mode": admission_mode,
}
finally:
cleanup = list(accepted)
if replacement is not None:
cleanup.append(replacement)
for ws, _ in cleanup:
try:
await _close_admission_session(ws, timeout_s=args.timeout_s)
except Exception:
await ws.close()
async def _resume_probe(
args: argparse.Namespace,
*,
session_id: str,
expect_expired: bool = False,
) -> dict[str, object]:
url = _url_with_model(args.url, args.model, session_id=session_id)
async with websockets.connect(url, max_size=64 * 1024 * 1024) as first:
await first.send(
json.dumps(
{
"type": "session.update",
"session": {
"model": args.model,
"modalities": ["audio", "text"],
"extra_body": {"minicpmo45_native_duplex": True},
},
}
)
)
created, first_events = await _receive_until(first, "session.created", timeout_s=args.timeout_s)
token = created.get("resume_token")
incarnation = created.get("incarnation")
generation = created.get("attachment_generation")
if not isinstance(token, str) or not isinstance(incarnation, int):
raise RuntimeError("session.created omitted resumable credentials")
last_seq = max(
(
event.get("server_event_seq", 0)
for event in first_events
if isinstance(event.get("server_event_seq"), int)
),
default=0,
)
delay_s = args.expire_after_s if expect_expired else args.resume_after_ms / 1000
if delay_s > 0:
await asyncio.sleep(delay_s)
resume_url = _with_resume_mode(url)
async with websockets.connect(resume_url, max_size=64 * 1024 * 1024) as second:
await second.send(
json.dumps(
{
"type": "session.resume",
"session_id": session_id,
"incarnation": incarnation,
"resume_token": token,
"last_received_server_event_seq": last_seq,
}
)
)
if expect_expired:
error, error_events = await _receive_until(second, "error", timeout_s=args.timeout_s)
error_payload = error.get("error")
code = error_payload.get("code") if isinstance(error_payload, dict) else error.get("code")
return {
"ok": code == "session_resume_expired",
"session_id": session_id,
"expired": True,
"error_code": code,
"event_count": len(error_events),
}
resumed, replay = await _receive_until(second, "session.resumed", timeout_s=args.timeout_s)
rotated = resumed.get("resume_token")
if not isinstance(rotated, str) or rotated == token:
raise RuntimeError("session.resume did not rotate the resume token")
await second.send(json.dumps({"type": "session.heartbeat"}))
heartbeat, heartbeat_events = await _receive_until(
second,
"session.heartbeat_ack",
timeout_s=args.timeout_s,
)
await second.send(json.dumps({"type": "session.close"}))
closed, close_events = await _receive_until(second, "session.closed", timeout_s=args.timeout_s)
replay_sequences = [event["server_event_seq"] for event in replay if isinstance(event.get("server_event_seq"), int)]
return {
"ok": (
resumed.get("session_id") == session_id
and isinstance(generation, int)
and resumed.get("attachment_generation") == generation + 1
and _event_session_id(heartbeat) == session_id
and _event_session_id(closed) == session_id
and replay_sequences == sorted(replay_sequences)
),
"session_id": session_id,
"resumed_session_id": resumed.get("session_id"),
"heartbeat_session_id": _event_session_id(heartbeat),
"closed_session_id": _event_session_id(closed),
"initial_attachment_generation": generation,
"resumed_attachment_generation": resumed.get("attachment_generation"),
"replayed_event_count": len(replay_sequences),
"replayed_event_sequences": replay_sequences,
"heartbeat_event_count": len(heartbeat_events),
"close_event_count": len(close_events),
"token_rotated": True,
}
async def _takeover_probe(
args: argparse.Namespace,
*,
session_id: str,
) -> dict[str, object]:
url = _url_with_model(args.url, args.model, session_id=session_id)
first = await websockets.connect(url, max_size=64 * 1024 * 1024)
second = None
try:
await first.send(
json.dumps(
{
"type": "session.update",
"session": {
"model": args.model,
"modalities": ["audio", "text"],
"extra_body": {"minicpmo45_native_duplex": True},
},
}
)
)
created, first_events = await _receive_until(first, "session.created", timeout_s=args.timeout_s)
token = created.get("resume_token")
incarnation = created.get("incarnation")
generation = created.get("attachment_generation")
if not isinstance(token, str) or not isinstance(incarnation, int) or not isinstance(generation, int):
raise RuntimeError("session.created omitted takeover credentials")
last_seq = max(
(
event.get("server_event_seq", 0)
for event in first_events
if isinstance(event.get("server_event_seq"), int)
),
default=0,
)
second = await websockets.connect(_with_resume_mode(url), max_size=64 * 1024 * 1024)
await second.send(
json.dumps(
{
"type": "session.resume",
"session_id": session_id,
"incarnation": incarnation,
"resume_token": token,
"last_received_server_event_seq": last_seq,
}
)
)
resumed, replay_events = await _receive_until(second, "session.resumed", timeout_s=args.timeout_s)
replaced, replaced_events = await _receive_until(first, "session.replaced", timeout_s=args.timeout_s)
await asyncio.wait_for(first.wait_closed(), timeout=args.timeout_s)
rejected_old_writes = 0
for _ in range(4):
try:
await first.send(json.dumps({"type": "session.heartbeat"}))
except ConnectionClosed:
rejected_old_writes += 1
await second.send(json.dumps({"type": "session.heartbeat"}))
heartbeat, heartbeat_events = await _receive_until(
second,
"session.heartbeat_ack",
timeout_s=args.timeout_s,
)
await second.send(json.dumps({"type": "session.close"}))
closed, close_events = await _receive_until(second, "session.closed", timeout_s=args.timeout_s)
rotated_token = resumed.get("resume_token")
return {
"ok": (
resumed.get("session_id") == session_id
and resumed.get("attachment_generation") == generation + 1
and isinstance(rotated_token, str)
and rotated_token != token
and _event_session_id(replaced) == session_id
and replaced.get("attachment_generation") == generation
and rejected_old_writes == 4
and _event_session_id(heartbeat) == session_id
and _event_session_id(closed) == session_id
),
"session_id": session_id,
"initial_attachment_generation": generation,
"resumed_attachment_generation": resumed.get("attachment_generation"),
"replaced_attachment_generation": replaced.get("attachment_generation"),
"token_rotated": isinstance(rotated_token, str) and rotated_token != token,
"old_attachment_closed": True,
"rejected_old_writes": rejected_old_writes,
"replay_event_count": len(replay_events),
"replaced_event_count": len(replaced_events),
"heartbeat_event_count": len(heartbeat_events),
"close_event_count": len(close_events),
}
finally:
if second is not None:
await second.close()
await first.close()
def _demo_args(args: argparse.Namespace, index: int) -> SimpleNamespace:
validation_mode = "response-required" if args.response_required else "model-policy"
input_wav = args.session_input_wav[index] if args.session_input_wav else args.input_wav
return SimpleNamespace(
url=args.url,
model=args.model,
session_id=f"multi-{index}-{uuid.uuid4().hex}",
input_wav=input_wav,
ref_audio=args.ref_audio,
turn_input_wav=list(args.turn_input_wav),
output_dir=str(Path(args.output_dir) / f"session_{index:02d}"),
output_audio_format="pcm16",
chunk_ms=args.chunk_ms,
realtime_input=args.realtime_input,
first_turn_ms=args.first_turn_ms,
turn_duration_ms=list(args.turn_duration_ms),
first_turn_transcript=f"session {index} input",
omit_transcript_hints=True,
validation_mode=validation_mode,
temperature=args.temperature,
scenario="sequential",
require_audio=args.response_required,
require_distinct_inputs=False,
expect_empty_turn=[],
short_ack_ms=350,
turns=args.turns,
timeout_s=args.timeout_s,
model_policy_settle_ms=args.model_policy_settle_ms,
)
async def run_multi_session(args: argparse.Namespace) -> dict[str, object]:
if args.sessions < 1:
raise ValueError("--sessions must be positive")
output_dir = Path(args.output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
resume_result = None
if args.disconnect_session_index is not None:
if not 0 <= args.disconnect_session_index < args.sessions:
raise ValueError("--disconnect-session-index is outside the session range")
resume_result = await _resume_probe(
args,
session_id=f"resume-{args.disconnect_session_index}-{uuid.uuid4().hex}",
)
takeover_result = None
if args.takeover_session_index is not None:
if not 0 <= args.takeover_session_index < args.sessions:
raise ValueError("--takeover-session-index is outside the session range")
takeover_result = await _takeover_probe(
args,
session_id=f"takeover-{args.takeover_session_index}-{uuid.uuid4().hex}",
)
expiry_result = None
if args.expire_session_index is not None:
if not 0 <= args.expire_session_index < args.sessions:
raise ValueError("--expire-session-index is outside the session range")
expiry_result = await _resume_probe(
args,
session_id=f"expire-{args.expire_session_index}-{uuid.uuid4().hex}",
expect_expired=True,
)
admission_result = (
await _admission_probe(args, limit=args.verify_admission_limit)
if args.verify_admission_limit is not None
else None
)
session_results = await asyncio.gather(
*(run_demo(_demo_args(args, index)) for index in range(args.sessions)),
return_exceptions=True,
)
failures = [repr(result) for result in session_results if isinstance(result, BaseException)]
completed = [result for result in session_results if isinstance(result, dict)]
identity_isolation_ok = _validate_identity_isolation(completed)
semantic_isolation_ok = _validate_semantic_isolation(
completed,
input_wavs=list(args.session_input_wav),
expected_tokens=list(args.session_expected_token),
)
result = {
"ok": (
not failures
and len(completed) == args.sessions
and all(item.get("ok") is True for item in completed)
and identity_isolation_ok
and semantic_isolation_ok
and (resume_result is None or resume_result.get("ok") is True)
and (takeover_result is None or takeover_result.get("ok") is True)
and (expiry_result is None or expiry_result.get("ok") is True)
and (admission_result is None or admission_result.get("ok") is True)
),
"session_count": args.sessions,
"identity_isolation_ok": identity_isolation_ok,
"semantic_isolation_ok": semantic_isolation_ok,
"resume": resume_result,
"takeover": takeover_result,
"expiry": expiry_result,
"admission": admission_result,
"failures": failures,
"sessions": completed,
}
(output_dir / "summary.json").write_text(
json.dumps(result, ensure_ascii=False, indent=2),
encoding="utf-8",
)
return result
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("--url", default="ws://127.0.0.1:8113/v1/realtime?duplex=1")
parser.add_argument("--base-url", help="Deprecated alias; /v1/realtime is appended when supplied.")
parser.add_argument("--model", default="openbmb/MiniCPM-o-4_5")
parser.add_argument("--sessions", type=int, default=2)
parser.add_argument("--input-wav", required=True)
parser.add_argument("--ref-audio", help="Optional WAV used as the MiniCPM-o voice prompt for every session.")
parser.add_argument("--session-input-wav", action="append", default=[])
parser.add_argument("--session-expected-token", action="append", default=[])
parser.add_argument("--turn-input-wav", action="append", default=[])
parser.add_argument("--output-dir", default="/tmp/minicpmo_pr3907_multi_session_e2e")
parser.add_argument("--realtime-input", action="store_true")
parser.add_argument("--chunk-ms", type=int, default=200)
parser.add_argument("--turns", type=int, default=1)
parser.add_argument("--first-turn-ms", type=int, default=1400)
parser.add_argument("--turn-duration-ms", type=int, action="append", default=[])
parser.add_argument("--response-required", action="store_true")
parser.add_argument("--temperature", type=float, default=None)
parser.add_argument("--disconnect-session-index", type=int)
parser.add_argument("--takeover-session-index", type=int)
parser.add_argument("--resume-after-ms", type=int, default=1000)
parser.add_argument("--expire-session-index", type=int)
parser.add_argument("--expire-after-s", type=float, default=6.0)
parser.add_argument("--verify-admission-limit", type=int)
parser.add_argument("--model-policy-settle-ms", type=int, default=600)
parser.add_argument("--timeout-s", type=float, default=120.0)
args = parser.parse_args()
if args.base_url:
args.url = args.base_url.rstrip("/") + "/v1/realtime?duplex=1"
if args.session_input_wav and len(args.session_input_wav) != args.sessions:
parser.error("provide exactly one --session-input-wav per session")
if args.session_expected_token and len(args.session_expected_token) != args.sessions:
parser.error("provide exactly one --session-expected-token per session")
if args.session_expected_token and not args.session_input_wav:
parser.error("--session-expected-token requires --session-input-wav")
return args
def main() -> None:
result = asyncio.run(run_multi_session(parse_args()))
print(json.dumps(result, ensure_ascii=False, indent=2))
raise SystemExit(0 if result["ok"] else 1)
if __name__ == "__main__":
main()
@@ -0,0 +1,467 @@
"""Validate MiniCPM-o Realtime duplex soft-interrupt delta streaming.
This E2E driver runs the public ``realtime_duplex_demo.py`` against a live
duplex backend. Arbitrary audio defaults to the model-policy lifecycle contract.
The stronger response-required mode binds the two-response contract to a known
input checksum and expected second response.
"""
from __future__ import annotations
import argparse
import asyncio
import base64
import hashlib
import io
import json
import sys
import uuid
import wave
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[3]
DEMO_PATH = REPO_ROOT / "examples/online_serving/minicpmo/realtime_duplex_demo.py"
AUDIO_DELTA_EVENTS = {"response.audio.delta", "response.output_audio.delta"}
TRANSCRIPT_DELTA_EVENTS = {
"response.audio_transcript.delta",
"response.output_text.delta",
}
def _canonical_path(path: str) -> Path:
return Path(path).expanduser().resolve(strict=False)
def _validate_input_sha256(path: Path, expected: str) -> str:
actual = hashlib.sha256(path.read_bytes()).hexdigest()
if actual != expected.lower():
raise ValueError(f"input WAV SHA256 mismatch: expected {expected.lower()}, got {actual}")
return actual
def _read_json(path: Path) -> dict[str, object]:
if not path.is_file():
return {}
data = json.loads(path.read_text(encoding="utf-8"))
return data if isinstance(data, dict) else {}
def _read_events(path: Path) -> list[dict[str, object]]:
if not path.is_file():
return []
events: list[dict[str, object]] = []
for line in path.read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
event = json.loads(line)
if isinstance(event, dict):
events.append(event)
return events
def _event_response_id(event: dict[str, object]) -> str | None:
response_id = event.get("response_id")
if isinstance(response_id, str):
return response_id
response = event.get("response")
if isinstance(response, dict) and isinstance(response.get("id"), str):
return response["id"]
return None
def _event_received_at_s(event: dict[str, object]) -> float | None:
received_at = event.get("_client_received_at_s")
if isinstance(received_at, int | float):
return float(received_at)
return None
def _first_event_index(events: list[dict[str, object]], event_type: str) -> int | None:
for index, event in enumerate(events):
if event.get("type") == event_type:
return index
return None
def _event_counts(events: list[dict[str, object]]) -> dict[str, int]:
counts: dict[str, int] = {}
for event in events:
event_type = str(event.get("type"))
counts[event_type] = counts.get(event_type, 0) + 1
return counts
def _response_created_ids(events: list[dict[str, object]]) -> list[str]:
response_ids: list[str] = []
for event in events:
if event.get("type") != "response.created":
continue
response_id = _event_response_id(event)
if response_id and response_id not in response_ids:
response_ids.append(response_id)
return response_ids
def _audio_delta_duration_ms(event: dict[str, object]) -> float | None:
encoded = event.get("delta") or event.get("audio")
if not isinstance(encoded, str) or not encoded:
return None
try:
raw = base64.b64decode(encoded)
except ValueError:
return None
fmt = str(event.get("format") or event.get("audio_format") or "pcm16").lower()
sample_rate = event.get("sample_rate_hz") or event.get("sample_rate") or 24_000
if not isinstance(sample_rate, int | float) or sample_rate <= 0:
return None
if "wav" in fmt:
try:
with wave.open(io.BytesIO(raw), "rb") as wav_file:
return round((wav_file.getnframes() * 1000.0) / wav_file.getframerate(), 3)
except (EOFError, wave.Error):
return None
bytes_per_sample = 4 if "f32" in fmt else 2
return round((len(raw) * 1000.0) / (bytes_per_sample * float(sample_rate)), 3)
def _normalize_text(text: str) -> str:
return "".join(text.split())
def _compact_sequence(events: list[dict[str, object]]) -> list[str]:
sequence: list[str] = []
for event in events:
event_type = event.get("type")
response_id = _event_response_id(event)
suffix = f" {response_id[-8:]}" if response_id else ""
if event_type == "response.listen":
sequence.append("listen")
elif event_type == "response.created":
sequence.append(f"response.created{suffix}")
elif event_type == "response.speak":
sequence.append(f"speak{suffix}")
elif event_type in AUDIO_DELTA_EVENTS:
sequence.append(f"audio.delta{suffix}")
elif event_type in TRANSCRIPT_DELTA_EVENTS:
delta = str(event.get("delta") or "")
sequence.append(f"text.delta{suffix}> {delta}")
elif event_type == "response.done":
sequence.append(f"response.done{suffix}")
elif event_type == "input_audio_buffer.committed":
sequence.append("input.committed")
return sequence
def _response_summary(
events: list[dict[str, object]],
response_id: str,
*,
t0: float | None,
) -> dict[str, object]:
created_indices = [
index
for index, event in enumerate(events)
if event.get("type") == "response.created" and _event_response_id(event) == response_id
]
done_indices = [
index
for index, event in enumerate(events)
if event.get("type") == "response.done" and _event_response_id(event) == response_id
]
audio_indices = [
index
for index, event in enumerate(events)
if event.get("type") in AUDIO_DELTA_EVENTS and _event_response_id(event) == response_id
]
transcript_indices = [
index
for index, event in enumerate(events)
if event.get("type") in TRANSCRIPT_DELTA_EVENTS and _event_response_id(event) == response_id
]
done_index = done_indices[0] if done_indices else None
audio_before_done_ok = done_index is not None and all(index < done_index for index in audio_indices)
stale_audio_count = sum(index > done_index for index in audio_indices) if done_index is not None else 0
def offset_ms(index: int) -> float | None:
if t0 is None:
return None
received_at = _event_received_at_s(events[index])
return round((received_at - t0) * 1000.0, 3) if received_at is not None else None
return {
"response_id": response_id,
"created_index": created_indices[0] if created_indices else None,
"done_indices": done_indices,
"created_offset_ms": offset_ms(created_indices[0]) if created_indices else None,
"done_offset_ms": offset_ms(done_indices[0]) if done_indices else None,
"audio_delta_count": len(audio_indices),
"transcript_delta_count": len(transcript_indices),
"audio_delta_offsets_ms": [offset_ms(index) for index in audio_indices],
"audio_duration_ms": [_audio_delta_duration_ms(events[index]) for index in audio_indices],
"transcript": "".join(str(events[index].get("delta") or "") for index in transcript_indices),
"one_done": len(done_indices) == 1,
"audio_before_done_ok": audio_before_done_ok,
"stale_audio_count": stale_audio_count,
}
def summarize_artifacts(
*,
output_dir: Path,
validation_mode: str,
min_responses: int,
min_audio_deltas_per_response: int,
expect_second_response_substring: str | None,
) -> dict[str, object]:
if validation_mode not in {"model-policy", "response-required"}:
raise ValueError(f"unsupported validation mode: {validation_mode}")
result = _read_json(output_dir / "result.json")
events = _read_events(output_dir / "events.jsonl")
response_ids = _response_created_ids(events)
times = [_event_received_at_s(event) for event in events]
clean_times = [received_at for received_at in times if received_at is not None]
t0 = min(clean_times) if clean_times else None
response_summaries = [_response_summary(events, response_id, t0=t0) for response_id in response_ids]
commit_index = _first_event_index(events, "input_audio_buffer.committed")
first_created_index = next(
(summary["created_index"] for summary in response_summaries if isinstance(summary.get("created_index"), int)),
None,
)
first_done_index = (
response_summaries[0]["done_indices"][0]
if response_summaries and response_summaries[0]["done_indices"]
else None
)
second_created_index = (
response_summaries[1]["created_index"]
if len(response_summaries) >= 2 and isinstance(response_summaries[1].get("created_index"), int)
else None
)
last_done_index = next(
(summary["done_indices"][0] for summary in reversed(response_summaries) if summary.get("done_indices")),
None,
)
listen_indices = [index for index, event in enumerate(events) if event.get("type") == "response.listen"]
effective_min_responses = min_responses if validation_mode == "response-required" else 1
enough_responses = len(response_summaries) >= effective_min_responses
response_lifecycle_ok = enough_responses and all(bool(summary.get("one_done")) for summary in response_summaries)
multi_delta_ok = enough_responses and all(
int(summary.get("audio_delta_count", 0)) >= min_audio_deltas_per_response for summary in response_summaries
)
response_audio_contract_ok = enough_responses and all(
summary.get("audio_before_done_ok") is True and int(summary.get("stale_audio_count", 0)) == 0
for summary in response_summaries
)
response_before_final_commit = (
first_created_index is not None and commit_index is not None and first_created_index < commit_index
)
second_response_before_final_commit = (
second_created_index is not None and commit_index is not None and second_created_index < commit_index
)
listen_before_first_response = first_created_index is not None and any(
index < first_created_index for index in listen_indices
)
listen_between_responses = (
first_done_index is not None
and second_created_index is not None
and any(first_done_index < index < second_created_index for index in listen_indices)
)
listen_after_last_done = last_done_index is not None and any(index > last_done_index for index in listen_indices)
listen_after_response_before_commit = (
last_done_index is not None
and commit_index is not None
and any(last_done_index < index < commit_index for index in listen_indices)
)
final_listen_after_commit = commit_index is not None and any(index > commit_index for index in listen_indices)
transcript = "".join(str(summary.get("transcript") or "") for summary in response_summaries)
second_response_transcript = (
str(response_summaries[1].get("transcript") or "") if len(response_summaries) >= 2 else ""
)
second_response_transcript_expectation_ok = not expect_second_response_substring or _normalize_text(
expect_second_response_substring
) in _normalize_text(second_response_transcript)
error_events = [
event
for event in events
if event.get("type") == "error"
or str(event.get("type") or "").endswith(".cancelled")
or str(event.get("type") or "").endswith(".truncated")
]
cancelled_count = sum(
1
for event in events
if event.get("type") == "response.done"
and isinstance(event.get("response"), dict)
and event["response"].get("status") == "cancelled"
)
result_ok = result.get("ok") is True
common_contract_ok = bool(
result_ok
and not error_events
and cancelled_count == 0
and enough_responses
and response_lifecycle_ok
and multi_delta_ok
and response_audio_contract_ok
and response_before_final_commit
and listen_after_response_before_commit
and final_listen_after_commit
)
mode_contract_ok = validation_mode == "model-policy" or (
second_response_before_final_commit
and listen_before_first_response
and listen_between_responses
and listen_after_last_done
and second_response_transcript_expectation_ok
)
ok = common_contract_ok and mode_contract_ok
return {
"ok": ok,
"result_ok": result_ok,
"validation_mode": validation_mode,
"event_counts": _event_counts(events),
"response_ids": response_ids,
"response_summaries": response_summaries,
"min_responses": min_responses,
"effective_min_responses": effective_min_responses,
"min_audio_deltas_per_response": min_audio_deltas_per_response,
"enough_responses": enough_responses,
"response_lifecycle_ok": response_lifecycle_ok,
"multi_delta_ok": multi_delta_ok,
"response_audio_contract_ok": response_audio_contract_ok,
"response_before_final_commit": response_before_final_commit,
"second_response_before_final_commit": second_response_before_final_commit,
"listen_before_first_response": listen_before_first_response,
"listen_between_responses": listen_between_responses,
"listen_after_last_done": listen_after_last_done,
"listen_after_response_before_commit": listen_after_response_before_commit,
"final_listen_after_commit": final_listen_after_commit,
"transcript": transcript,
"second_response_transcript": second_response_transcript,
"expect_second_response_substring": expect_second_response_substring,
"second_response_transcript_expectation_ok": second_response_transcript_expectation_ok,
"error_count": len(error_events),
"cancelled_count": cancelled_count,
"compact_sequence": _compact_sequence(events),
"output_dir": str(output_dir),
}
async def run_soft_interrupt(args: argparse.Namespace) -> dict[str, object]:
input_wav = _canonical_path(args.input_wav)
output_dir = _canonical_path(args.output_dir)
if not input_wav.is_file():
raise ValueError(f"input WAV does not exist: {input_wav}")
input_sha256 = hashlib.sha256(input_wav.read_bytes()).hexdigest()
if args.input_sha256:
input_sha256 = _validate_input_sha256(input_wav, args.input_sha256)
command = [
sys.executable,
str(DEMO_PATH),
"--url",
args.url,
"--model",
args.model,
"--input-wav",
str(input_wav),
"--output-dir",
str(output_dir),
"--chunk-ms",
str(args.chunk_ms),
"--timeout-s",
str(args.timeout_s),
"--session-id",
f"duplex-soft-interrupt-{uuid.uuid4().hex}",
]
command.extend(["--ref-audio", str(_canonical_path(args.ref_audio))])
if args.require_audio:
command.append("--require-audio")
if args.no_realtime_pacing:
command.append("--no-realtime-pacing")
process = await asyncio.create_subprocess_exec(
*command,
cwd=str(REPO_ROOT),
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
try:
stdout_bytes, stderr_bytes = await asyncio.wait_for(
process.communicate(),
timeout=args.timeout_s + 30.0,
)
except TimeoutError:
process.kill()
stdout_bytes, stderr_bytes = await process.communicate()
return {
"ok": False,
"returncode": -1,
"stdout_tail": stdout_bytes.decode(errors="replace")[-4000:],
"stderr_tail": (stderr_bytes.decode(errors="replace") + "\nclient timeout")[-4000:],
"output_dir": str(output_dir),
}
summary = summarize_artifacts(
output_dir=output_dir,
validation_mode=args.validation_mode,
min_responses=args.min_responses,
min_audio_deltas_per_response=args.min_audio_deltas_per_response,
expect_second_response_substring=args.expect_second_response_substring,
)
summary.update(
{
"returncode": process.returncode if process.returncode is not None else -1,
"input_wav": str(input_wav),
"input_sha256": input_sha256,
"stdout_tail": stdout_bytes.decode(errors="replace")[-4000:],
"stderr_tail": stderr_bytes.decode(errors="replace")[-4000:],
}
)
summary["ok"] = bool(summary["ok"] and summary["returncode"] == 0)
summary_output = Path(args.summary_output) if args.summary_output else output_dir / "summary.json"
summary_output.parent.mkdir(parents=True, exist_ok=True)
summary_output.write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
return summary
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("--url", default="ws://127.0.0.1:8099/v1/realtime?duplex=1")
parser.add_argument("--model", default="openbmb/MiniCPM-o-4_5")
parser.add_argument("--input-wav", required=True)
parser.add_argument("--ref-audio", required=True)
parser.add_argument("--output-dir", required=True)
parser.add_argument("--summary-output")
parser.add_argument("--chunk-ms", type=int, default=200)
parser.add_argument("--timeout-s", type=float, default=120.0)
parser.add_argument("--require-audio", action="store_true")
parser.add_argument("--no-realtime-pacing", action="store_true")
parser.add_argument(
"--validation-mode",
choices=("model-policy", "response-required"),
default="model-policy",
)
parser.add_argument("--min-responses", type=int, default=2)
parser.add_argument("--min-audio-deltas-per-response", type=int, default=2)
parser.add_argument("--input-sha256")
parser.add_argument("--expect-second-response-substring")
args = parser.parse_args()
if args.validation_mode == "response-required" and args.min_responses < 2:
parser.error("--min-responses must be at least 2")
if args.validation_mode == "response-required" and not args.input_sha256:
parser.error("--input-sha256 is required in response-required mode")
if args.validation_mode == "response-required" and not args.expect_second_response_substring:
parser.error("--expect-second-response-substring is required in response-required mode")
if args.min_audio_deltas_per_response < 1:
parser.error("--min-audio-deltas-per-response must be positive")
return args
def main() -> None:
result = asyncio.run(run_soft_interrupt(parse_args()))
print(json.dumps(result, ensure_ascii=False, indent=2))
raise SystemExit(0 if result["ok"] else 1)
if __name__ == "__main__":
main()