HEL-877: wire the audited .12 voice base into the one CyberGril chat chain as backend-only code (no deploy, no real voice call) - new independent src/cybergril/voice module: session+router add POST /api/voice/session / DELETE end / GET honest status on the unified instance (server-side room + dedicated cybergril-voice-agent dispatch + short-TTL join token via zero-new-dependency livekit_wire HS256/Twirp matching the installed SDK's wire format verified claim-for-claim on the .12 agent venv stdin-only; keys never reach the browser; unconfigured/no-profile/TTS-down refuse honestly and capabilities.voice stays false), chat_api_client speaks the exact real.ts RealChatAdapter protocol (per-turn health epoch, bounded 409 resync, robust incremental SSE parsing across multibyte/CRLF/multi-data chunk splits, fixed turn_id idempotency, immediate HTTP-stream close on barge-in without waiting for the next ASR final), llm_chat_api is a livekit llm.LLM adapter whose only backend is POST /api/chat so persona/mood/dyad/memory/life-sharing/budget gates and the one same-turn chat_lock govern text and voice identically (phi spoken verbatim via ChatChunk, never archived, no receipt), receipt.py confirms a sharing receipt only after real SDK playback completion with every negative (interrupted/failed/mid-playout/phi/incomplete/stale-epoch) fail-closed and exactly once per turn, stt_funasr/tts_cosyvoice reuse the proven .12 adapters verbatim with provenance, worker.py assembles the dedicated worker (independent voice_state_cybergril.json so D1 stays undecided, no second persona, cg.subtitle data-channel contract for the visual lead, CG-011 proactive seam left as an explicit no-op hook, built-in health port 8082); app.py keeps a minimal registration with voice_service injection for isolated tests; deployment drafts only (config/voice.example.yaml, worker.env.example, restart_cybergril.sh.example with exact-pattern process matching, serve_dual_8360_8361.py keeping HTTP 8360 and the HTTPS voice entry on ONE process sharing state/locks, runbook-hel877-voice.md contract+startup+rollback incl. the >=6GB GPU precondition and the do-not-copy historical fuser warning) - verification: 281 pytest pass on 3.11 venv + requirements.lock after merging the chief engineer's mid-flight HEL-874 rework e978e87 in full (parallel work preserved), verify_hel877_voice_chain.py 8/8 offline full-chain incl. socket-level barge-in fail-close and text/voice mutual same-gate cancellation, real-SDK check on the .12 livekit-agents 1.8.8 venv 8/8 ALL PASS via SSH stdin with zero writes zero network, dual-port single-process smoke on loopback 18360/18361 with a throwaway self-signed cert then stopped, ruff clean on all new code, dual-target requirement checks pass vs origin/hel-870-assembly (current tip e978e87) and origin/main with handoff-HEL-877.json; zero real LLM/embed/TTS/ASR requests, no mic/camera, no downloads/installs, no service start/stop, no 4080 access, no third-account or profile writes, web/ untouched, not merged, not deployed

Co-authored-by: multica-agent <github@multica.ai>

## HEL-877 交付摘要(R5 后台施工,未部署未合并)

- 新独立模块 src/cybergril/voice/:专属 livekit worker(agent_name=cybergril-voice-agent,复用 .12 FunASR/CosyVoice/silero 底座,不 fork 不另搭平台,无第二人格/记忆,不直连 LLM);llm_chat_api 适配器与文字前端 real.ts 同协议走 POST /api/chat(epoch 409 有界重同步、SSE 分片、turn_id 幂等、打断即断流);/api/voice/session 建房+专属派发+短时限 token 全服务端(密钥不进浏览器;缺配置/无档案/TTS 停机诚实拒绝;capabilities.voice 不伪造);receipt 仅在 SDK 真实播放完成后确认(打断/失败/φ 轮/旧 epoch 全 fail-closed)。
- 部署草案:/opt/voice-agent-cybergril 目录、worker 健康端口 8082、HTTP 8360 + HTTPS 8361 同进程双入口(deploy/voice/serve_dual_8360_8361.py,共用同一状态/锁)、启动顺序含 TTS GPU≥6GB 前置与回滚;本卡未执行任何启停。契约(开关/字幕/失败/打断/挂断 + CG-011 主动开口接缝)见 docs/runbook-hel877-voice.md §3。
- 自测(零真实请求):281 pytest 全过(含语音 25 例:socket 级打断断流、SSE 边界、重放零调用、文字/语音同门互打断、回执全负例、token 房间隔离);scripts/verify_hel877_voice_chain.py 8/8;.12 agent venv(livekit-agents 1.8.8)真 SDK 检查 8/8(stdin-only 零写入零网络);双端口同进程本地冒烟通过;ruff 干净;需求检查双目标通过(含 handoff-HEL-877.json)。
- 施工中总工 HEL-874(e978e87)推上同分支,本卡已完整并入,不覆盖并行成果。未验证如实列明:端到端语音(TTS 停机/GPU 3.9GB<5.6GB)、真 LiveKit server 的 dispatch/delete、移动端实机——待接线/审核卡真机验收,未经真实验收不称 R5 完成。
This commit is contained in:
施工员2号
2026-10-26 22:42:19 +08:00
parent a324fd57b7
commit aba2aebeb0
21 changed files with 2902 additions and 0 deletions
+18
View File
@@ -48,6 +48,7 @@ from ..memory.semantic import build_semantic
from ..memory.store import Store
from ..think.scenes import Scene
from ..think.wiring import build_router_from_config
from ..voice import VoiceSessionService, build_voice_router, load_voice_config
HOURS = [
"子时",
@@ -180,6 +181,7 @@ def create_app(
character: CharacterConfig | None = None,
semantic_mode: str | None = None,
semantic_config: dict | None = None,
voice_service=None,
) -> FastAPI:
"""Dependencies can be injected for isolated fault/cancellation tests, never via browser flags."""
db_path = db_path or os.environ.get(
@@ -264,10 +266,26 @@ def create_app(
await app.state.semantic.backend.aclose()
for provider in set(router.provider_for(t) for t in router.available_tiers()):
await provider.aclose()
if getattr(app.state, "voice_service", None):
await app.state.voice_service.aclose()
store.close()
app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None)
# R5 voice session endpoint (HEL-877): independent module sharing this
# process's state/locks; unconfigured instances refuse honestly.
# voice_service injection is for isolated tests; production reads config.
if voice_service is None:
try:
voice_config = load_voice_config()
except Exception:
voice_config = None
voice_service = (
VoiceSessionService(voice_config) if voice_config is not None else None
)
app.state.voice_service = voice_service
app.include_router(build_voice_router(voice_service))
@app.exception_handler(RequestValidationError)
async def invalid(_request, exc):
fields = {}
+26
View File
@@ -0,0 +1,26 @@
"""CyberGril voice module (HEL-877, approved R5 backend wiring).
Two worlds live here on purpose:
* API-process side (no livekit imports, runs inside the unified instance):
``session``/``router`` (POST /api/voice/session + end/status) and
``chat_api_client``/``receipt`` (protocol helpers the worker also uses).
* Worker side (agent venv only, livekit-agents 1.8.8): ``llm_chat_api``,
``stt_funasr``, ``tts_cosyvoice``, ``worker`` — the dedicated
``cybergril-voice-agent`` that reuses the .12 FunASR/CosyVoice/VAD base and
gets every reply from the same POST /api/chat chain the text UI uses.
"""
from __future__ import annotations
def __getattr__(name: str): # lazy: API side must import without livekit installed
if name in {"VoiceConfig", "VoiceSessionService", "load_voice_config", "VoiceNotConfigured"}:
from . import session
return getattr(session, name)
if name == "build_voice_router":
from . import router
return router.build_voice_router
raise AttributeError(name)
+186
View File
@@ -0,0 +1,186 @@
"""Unified-API chat client for the voice worker (HEL-877).
Speaks the exact RealChatAdapter protocol the text frontend already uses
(web/src/adapters/real.ts): GET /api/health for the epoch, POST /api/chat with
{text, turn_id, epoch}, SSE chat.delta / chat.final / chat.error frames, one
bounded 409 resync, receive-confirmation receipts, and immediate cancellation
of the HTTP stream when the caller is interrupted.
This module is deliberately free of livekit imports so the whole protocol can
be exercised offline against the real API with fake transports.
"""
from __future__ import annotations
import codecs
import json
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import Any
from uuid import uuid4
import httpx
class ChatApiConnectionError(RuntimeError):
"""The SSE stream broke without a final or error frame."""
@dataclass
class ChatApiTurn:
"""Result of one completed voice turn (or its honest failure)."""
turn_id: str
epoch: int
text: str = ""
receipt: dict[str, Any] | None = None
error_phi: str | None = None
completed: bool = False
@dataclass
class ChatApiClient:
"""One instance per worker; thread-less, single event loop."""
base_url: str
transport: httpx.AsyncBaseTransport | None = None
epoch_resyncs: int = 1
request_timeout: httpx.Timeout = field(
default_factory=lambda: httpx.Timeout(connect=5.0, read=120.0, write=10.0, pool=5.0)
)
def __post_init__(self) -> None:
self._client = httpx.AsyncClient(
base_url=self.base_url.rstrip("/"), transport=self.transport,
timeout=self.request_timeout,
)
async def aclose(self) -> None:
await self._client.aclose()
async def current_epoch(self) -> int:
response = await self._client.get("/api/health")
response.raise_for_status()
epoch = response.json().get("epoch")
if not isinstance(epoch, int) or epoch < 1:
raise ChatApiConnectionError("health response missing epoch")
return epoch
async def send_turn(
self,
text: str,
*,
turn_id: str | None = None,
epoch: int | None = None,
on_delta: Callable[[str], None] | None = None,
) -> ChatApiTurn:
"""Run one turn to completion. Cancellation (barge-in) propagates from
the caller's task; the in-flight HTTP response is always closed in the
finally block so the server sees the disconnect immediately."""
turn_id = turn_id or str(uuid4())
epoch = await self.current_epoch() if epoch is None else epoch
attempts = self.epoch_resyncs + 1
for attempt in range(attempts):
response = None
try:
# stream=True: a plain post() would buffer the whole SSE body.
request = self._client.build_request(
"POST", "/api/chat", json={"text": text, "turn_id": turn_id, "epoch": epoch}
)
response = await self._client.send(request, stream=True)
if response.status_code == 409 and attempt + 1 < attempts:
await response.aread()
body = response.json()
new_epoch = body.get("epoch")
if isinstance(new_epoch, int) and new_epoch >= 1:
epoch = new_epoch
continue
response.raise_for_status()
return await self._consume(
response, turn_id=turn_id, epoch=epoch, on_delta=on_delta
)
finally:
if response is not None:
await response.aclose()
raise ChatApiConnectionError("epoch resync exhausted")
async def _consume(
self,
response: httpx.Response,
*,
turn_id: str,
epoch: int,
on_delta: Callable[[str], None] | None,
) -> ChatApiTurn:
turn = ChatApiTurn(turn_id=turn_id, epoch=epoch)
got_terminal = False
async for frame in _sse_frames(response):
kind = frame.get("t")
if frame.get("turn_id") not in (None, turn_id):
continue
if kind == "chat.delta":
delta = frame.get("delta")
if delta:
turn.text += delta
if on_delta is not None:
on_delta(delta)
elif kind == "chat.final":
turn.text = frame.get("utterance", {}).get("text", turn.text)
turn.receipt = frame.get("receipt")
turn.completed = True
got_terminal = True
elif kind == "chat.error":
turn.error_phi = frame.get("phi") or ""
got_terminal = True
if not got_terminal:
raise ChatApiConnectionError("chat stream ended without final or error")
return turn
async def acknowledge(self, receipt: dict[str, Any]) -> bool:
"""POST /api/chat/received; False when the server no longer accepts it
(expired / already gone / wrong epoch) — never retried by the caller."""
try:
response = await self._client.post(
"/api/chat/received",
json={k: receipt[k] for k in
("message_id", "turn_id", "epoch", "token", "text_hash")},
)
except Exception:
return False
return response.status_code == 200
async def _sse_frames(response: httpx.Response):
"""Incremental SSE parser: CRLF or LF frame separators, multi-line data,
UTF-8 split across transport chunks — same robustness as readEvents()."""
decoder = codecs.getincrementaldecoder("utf-8")()
buffer = ""
async for chunk in response.aiter_bytes():
buffer += decoder.decode(chunk)
while True:
boundary = _frame_boundary(buffer)
if boundary is None:
break
frame, buffer = buffer[: boundary[0]], buffer[boundary[1]:]
data = "\n".join(
line[5:].lstrip(" ") for line in frame.splitlines() if line.startswith("data:")
)
if not data:
continue
try:
yield json.loads(data)
except ValueError:
continue
def _frame_boundary(buffer: str) -> tuple[int, int] | None:
"""(start, end) of the earliest blank-line separator, or None when the
buffer holds no complete frame yet."""
candidates = []
lf = buffer.find("\n\n")
if lf >= 0:
candidates.append((lf, lf + 2))
crlf = buffer.find("\r\n\r\n")
if crlf >= 0:
candidates.append((crlf, crlf + 4))
return min(candidates, key=lambda pair: pair[0]) if candidates else None
+195
View File
@@ -0,0 +1,195 @@
"""LiveKit wire helpers for the voice session endpoint (HEL-877).
Reuses the already-running LiveKit SFU on .12 without adding the ``livekit``
package to the API process: access tokens are the same HS256 JWTs, and the
dispatch / room-delete calls use the same Twirp endpoints with the same
protobuf bodies that the installed SDK (livekit 1.1.20, read-only verified on
/opt/voice-agent/agent/venv) sends for /opt/voice-agent/web/server.py's
working /api/token flow. No keys ever leave the server: only the minted,
short-lived room token is returned to the browser.
"""
from __future__ import annotations
import base64
import hashlib
import hmac
import json
import time
from dataclasses import dataclass
from typing import Any
import httpx
TWIRP_PREFIX = "/twirp"
DISPATCH_SERVICE = "livekit.AgentDispatchService"
ROOM_SERVICE = "livekit.RoomService"
def _b64url(raw: bytes) -> str:
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
def _jwt_hs256(secret: str, claims: dict[str, Any]) -> str:
"""HS256 JWT with the exact header the installed SDK's PyJWT produces."""
header = _b64url(json.dumps({"alg": "HS256", "typ": "JWT"}, separators=(",", ":")).encode())
payload = _b64url(json.dumps(claims, separators=(",", ":"), ensure_ascii=False).encode())
signing_input = f"{header}.{payload}".encode("ascii")
signature = _b64url(hmac.new(secret.encode(), signing_input, hashlib.sha256).digest())
return f"{header}.{payload}.{signature}"
def _camel(name: str) -> str:
head, *rest = name.split("_")
return head + "".join(part.capitalize() for part in rest)
def mint_token(
api_key: str,
api_secret: str,
*,
identity: str,
name: str = "",
room: str = "",
room_join: bool = False,
can_publish: bool = True,
can_subscribe: bool = True,
ttl_seconds: float = 300.0,
now: float | None = None,
) -> str:
"""Participant access token; claims mirror livekit.api.AccessToken.to_jwt().
Video grants are emitted camelCase with empty values dropped, exactly like
Claims.asdict() in the installed SDK.
"""
now = time.time() if now is None else now
video = {
_camel(k): v
for k, v in {
"room_join": room_join,
"room": room,
"can_publish": can_publish,
"can_subscribe": can_subscribe,
"can_publish_data": True,
}.items()
if v is not None and v != ""
}
claims: dict[str, Any] = {"video": video, "sub": identity, "iss": api_key,
"nbf": int(now), "exp": int(now + ttl_seconds)}
if name:
claims["name"] = name
return _jwt_hs256(api_secret, claims)
def mint_server_token(api_key: str, api_secret: str, ttl_seconds: float = 60.0,
now: float | None = None) -> str:
"""Server-API bearer token; matches Service._auth_header() with no grants."""
now = time.time() if now is None else now
return _jwt_hs256(
api_secret,
{"iss": api_key, "sub": "", "nbf": int(now), "exp": int(now + ttl_seconds)},
)
def _proto_string(field_number: int, value: str) -> bytes:
payload = value.encode()
return bytes([(field_number << 3) | 2]) + _varint(len(payload)) + payload
def _varint(value: int) -> bytes:
out = bytearray()
while value > 0x7F:
out.append((value & 0x7F) | 0x80)
value >>= 7
out.append(value)
return bytes(out)
@dataclass
class DispatchResult:
room: str
dispatch_id: str
body: dict
async def create_dispatch(
http: httpx.AsyncClient,
*,
internal_url: str,
api_key: str,
api_secret: str,
agent_name: str,
room: str,
metadata: str = "",
timeout: float = 5.0,
) -> DispatchResult:
"""Twirp AgentDispatchService/CreateDispatch with an explicit agent_name.
Body is livekit.CreateAgentDispatchRequest: field 1 agent_name, field 2 room,
field 3 metadata (field numbers verified against the installed protocol pkg).
"""
body = _proto_string(1, agent_name) + _proto_string(2, room)
if metadata:
body += _proto_string(3, metadata)
response = await http.post(
f"{internal_url.rstrip('/')}{TWIRP_PREFIX}/{DISPATCH_SERVICE}/CreateDispatch",
content=body,
headers={
"authorization": f"Bearer {mint_server_token(api_key, api_secret)}",
"content-type": "application/protobuf",
},
timeout=timeout,
)
response.raise_for_status()
parsed = json.loads(response.content or b"{}")
return DispatchResult(
room=room,
dispatch_id=str(parsed.get("id") or parsed.get("dispatchId") or ""),
body=parsed,
)
async def delete_room(
http: httpx.AsyncClient,
*,
internal_url: str,
api_key: str,
api_secret: str,
room: str,
timeout: float = 5.0,
) -> bool:
"""Twirp RoomService/DeleteRoom (livekit.DeleteRoomRequest field 1: room).
Deleting the room disconnects every participant, ends the dispatched agent
job and releases the browser microphone server-side.
"""
response = await http.post(
f"{internal_url.rstrip('/')}{TWIRP_PREFIX}/{ROOM_SERVICE}/DeleteRoom",
content=_proto_string(1, room),
headers={
"authorization": f"Bearer {mint_server_token(api_key, api_secret)}",
"content-type": "application/protobuf",
},
timeout=timeout,
)
# LiveKit answers DeleteRoom with an empty protobuf body; treat 2xx as done.
return response.status_code // 100 == 2
def decode_token(token: str) -> tuple[dict[str, Any], bytes]:
"""Header/claims decode without verification (test helper, never trusting input)."""
header_b64, payload_b64, _ = token.split(".")
pad = lambda s: s + "=" * (-len(s) % 4) # noqa: E731
claims = json.loads(base64.urlsafe_b64decode(pad(payload_b64)))
signing_input = f"{header_b64}.{payload_b64}".encode("ascii")
return claims, signing_input
def verify_signature(token: str, secret: str) -> bool:
"""Constant-time HS256 check for tests proving the minted token is genuine."""
parts = token.split(".")
if len(parts) != 3:
return False
signing_input = f"{parts[0]}.{parts[1]}".encode("ascii")
expected = _b64url(hmac.new(secret.encode(), signing_input, hashlib.sha256).digest())
return hmac.compare_digest(expected, parts[2])
+153
View File
@@ -0,0 +1,153 @@
"""livekit-agents LLM adapter backed by the unified CyberGril chat API (HEL-877).
The worker holds no persona, no memory and no direct LLM connection: every
reply is POST /api/chat on the unified instance, so persona / mood / dyad /
memory / life-sharing / call limits and the same-turn gate apply to voice
exactly as to text. This is the same protocol web/src/adapters/real.ts speaks
(epoch sync, serialized turns, barge-in cancel, idempotent replay, receipts).
Only this module (and worker/stt/tts below) import livekit: the API process
never does. Verified against livekit-agents 1.8.8 source on
/opt/voice-agent/agent/venv (LLM.chat/LLMStream._run/ChatChunk/ChoiceDelta).
"""
from __future__ import annotations
import time
from collections.abc import Callable
from typing import Any
from uuid import uuid4
from livekit.agents import APIConnectionError, APIStatusError
from livekit.agents.llm import (
LLM,
ChatChunk,
ChatContext,
ChoiceDelta,
LLMStream,
Tool,
)
from livekit.agents.types import (
DEFAULT_API_CONNECT_OPTIONS,
NOT_GIVEN,
APIConnectOptions,
NotGivenOr,
)
from .chat_api_client import ChatApiClient, ChatApiConnectionError
def latest_user_text(chat_ctx: ChatContext) -> str:
"""The one message the server needs: the user's current utterance.
The server composes persona/memory/history itself from its own archive;
the worker must never ship livekit's local chat_ctx back to it.
"""
for item in reversed(chat_ctx.items):
role = getattr(item, "role", None)
text = getattr(item, "text_content", None) or ""
if role == "user" and text.strip():
return text.strip()
return ""
class ChatApiLLMStream(LLMStream):
"""Bridges one /api/chat SSE turn into livekit ChatChunks."""
def __init__(
self,
*,
llm: CyberGrillLLM,
chat_ctx: ChatContext,
tools: list[Tool],
conn_options: APIConnectOptions,
) -> None:
super().__init__(llm, chat_ctx=chat_ctx, tools=tools, conn_options=conn_options)
# Never auto-retry after output: a retried turn would re-speak audio.
# The turn_id stays fixed, so a retry before any chunk is idempotent
# server-side (replay path).
self._retry_on_chunk_sent = False
self.turn_id = str(uuid4())
self.created_at = time.time()
self.text = ""
self.receipt: dict[str, Any] | None = None
self.error_phi: str | None = None
self.completed = False
def _emit(self, content: str) -> None:
self._event_ch.send_nowait(
ChatChunk(id=self.turn_id, delta=ChoiceDelta(role="assistant", content=content))
)
async def _run(self) -> None:
text = latest_user_text(self._chat_ctx)
if not text:
raise APIStatusError(
"empty user utterance", status_code=400, body=None, retryable=False
)
try:
turn = await self._llm.client.send_turn(
text,
turn_id=self.turn_id,
on_delta=self._emit,
)
except ChatApiConnectionError as exc:
raise APIConnectionError(str(exc)) from exc
except Exception as exc:
raise APIStatusError(
f"chat api failure: {exc}", status_code=502, body=None
) from exc
self.text = turn.text
self.receipt = turn.receipt
self.error_phi = turn.error_phi
self.completed = turn.completed
if turn.error_phi:
# The φ line is spoken verbatim (HEL-876 §3.5); it is not her
# archived reply and carries no receipt.
self._emit(turn.error_phi)
class CyberGrillLLM(LLM):
"""llm.LLM whose single backend is the unified instance's /api/chat."""
def __init__(
self,
api_base: str,
*,
client: ChatApiClient | None = None,
on_stream_started: Callable[[ChatApiLLMStream], None] | None = None,
) -> None:
super().__init__()
self.client = client or ChatApiClient(api_base)
self._on_stream_started = on_stream_started
@property
def provider(self) -> str:
return "cybergril"
@property
def model(self) -> str:
return "cybergril-chat-api"
async def aclose(self) -> None:
await self.client.aclose()
def chat(
self,
*,
chat_ctx: ChatContext,
tools: list[Tool] | None = None,
conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS,
parallel_tool_calls: NotGivenOr[bool] = NOT_GIVEN,
tool_choice: NotGivenOr[Any] = NOT_GIVEN,
extra_kwargs: NotGivenOr[dict[str, Any]] = NOT_GIVEN,
) -> ChatApiLLMStream:
stream = ChatApiLLMStream(
llm=self,
chat_ctx=chat_ctx,
tools=tools or [],
conn_options=conn_options,
)
if self._on_stream_started is not None:
self._on_stream_started(stream)
return stream
+92
View File
@@ -0,0 +1,92 @@
"""Playback-completion-gated receive confirmation for voice turns (HEL-877).
A sharing receipt may only be confirmed after the SDK reports the assistant
speech truly finished playing out. None of these count as delivered, so none of
them may ack: interrupted (barge-in), failed playback/generation, turns that
ended in chat.error (the φ line is spoken verbatim but is not her archived
reply), missing receipt, or a receipt from an epoch the server has since left
(the server fail-closes those anyway — this is the client-side half).
Speech-handle-to-stream binding lives in TurnLedger: AgentSession emits
speech_created before the LLM stream starts and runs one user-turn generation
at a time, so the first stream created at/after a handle belongs to it.
"""
from __future__ import annotations
from collections import deque
from typing import Any, Protocol
from .chat_api_client import ChatApiClient
def should_ack(
*,
played_to_end: bool,
interrupted: bool,
failed: bool,
receipt: dict[str, Any] | None,
current_epoch: int | None = None,
) -> bool:
"""Pure decision: only a fully played-out, unerrored, receipted turn acks."""
if not played_to_end or interrupted or failed:
return False
if not receipt:
return False
for key in ("message_id", "turn_id", "epoch", "token", "text_hash"):
if not receipt.get(key):
return False
return current_epoch is None or receipt.get("epoch") == current_epoch
class _HasHandle(Protocol):
@property
def created_at(self) -> float: # SpeechCreatedEvent.created_at
...
def add_done_callback(self, callback) -> None: ...
class TurnLedger:
"""Binds livekit SpeechHandles to the ChatApiLLMStream of their generation."""
def __init__(self) -> None:
self._handles: deque[tuple[float, Any]] = deque() # (created_at, handle)
self._streams: deque[tuple[float, Any]] = deque() # (created_at, stream)
def note_handle(self, handle: _HasHandle, created_at: float) -> None:
self._handles.append((created_at, handle))
def note_stream(self, stream: Any, created_at: float) -> None:
self._streams.append((created_at, stream))
def stream_for(self, handle: _HasHandle) -> Any | None:
"""First not-yet-consumed stream created at/after the handle."""
while self._handles and self._handles[0][1] is not handle:
self._handles.popleft() # older handles ended without a generation
if not self._handles:
return None
# (handle present below)
created = self._handles.popleft()[0]
while self._streams:
at, stream = self._streams.popleft()
if at >= created:
return stream
return None
class ReceiptSender:
"""Posts accepted receipts to /api/chat/received exactly once per turn."""
def __init__(self, client: ChatApiClient) -> None:
self._client = client
self._acked: set[str] = set()
self.results: dict[str, bool] = {}
async def confirm(self, turn_id: str, receipt: dict[str, Any]) -> bool:
if turn_id in self._acked:
return self.results.get(turn_id, False)
accepted = await self._client.acknowledge(receipt)
self._acked.add(turn_id)
self.results[turn_id] = accepted
return accepted
+78
View File
@@ -0,0 +1,78 @@
"""Minimal voice-session protocol mounted on the unified API (HEL-877).
POST /api/voice/session open a room, dispatch the dedicated worker,
return a short-lived join token (keys stay
server-side); honest refusal when voice is
not configured, no companion exists yet or
TTS is down.
DELETE /api/voice/session/{id} end: delete the LiveKit room, which
disconnects browser and worker, ends the
agent job and releases the microphone.
GET /api/voice/status honest switch state for the frontend
(configured / tts reachable / agent name).
capabilities.voice in /api/health stays false: R5 is not real-accepted yet and
this endpoint never claims end-to-end voice availability.
"""
from __future__ import annotations
from fastapi import APIRouter, HTTPException, Request
from .session import VoiceSessionService
REFUSAL_NOT_CONFIGURED = "语音还没有在这台服务上配置,不能假装能通话。"
REFUSAL_NO_COMPANION = "还没有创建真实伴侣,语音也不会开始。"
REFUSAL_TTS_DOWN = "她的声音服务这会儿不在,稍后再试试。"
REFUSAL_LIVEKIT_DOWN = "通话服务暂时连不上,稍后再试试。"
def build_voice_router(service: VoiceSessionService | None) -> APIRouter:
router = APIRouter(prefix="/api/voice", tags=["voice"])
@router.get("/status")
async def status() -> dict:
if service is None:
return {"configured": False, "tts_ok": False, "agent_name": None, "voice": False}
tts_ok = await service.tts_available()
return {
"configured": True,
"tts_ok": tts_ok,
"agent_name": service.config.agent_name,
"voice": False, # honest until real-device R5 acceptance
**service.config.sanitized(),
}
@router.post("/session", status_code=201)
async def open_session(request: Request) -> dict:
if service is None:
raise HTTPException(503, REFUSAL_NOT_CONFIGURED)
state = request.app.state
if not state.store.query_one("SELECT id FROM companion"):
raise HTTPException(409, REFUSAL_NO_COMPANION)
if not await service.tts_available():
raise HTTPException(503, REFUSAL_TTS_DOWN)
try:
session = await service.open_session(epoch=state.epoch)
except Exception:
raise HTTPException(503, REFUSAL_LIVEKIT_DOWN) from None
return {
"url": service.config.livekit_url,
"token": service.token_for(session),
"room": session.room,
"session_id": session.session_id,
"agent_name": service.config.agent_name,
"epoch": session.epoch,
"expires_at": int(session.expires_at * 1000),
}
@router.delete("/session/{session_id}")
async def end_session(session_id: str) -> dict:
if service is None:
raise HTTPException(503, REFUSAL_NOT_CONFIGURED)
session = await service.end_session(session_id)
if session is None:
raise HTTPException(404, "这次通话已经不在了。")
return {"ended": True, "room": session.room}
return router
+209
View File
@@ -0,0 +1,209 @@
"""Voice session lifecycle for the unified API (HEL-877, approved R5 backend).
The endpoint reuses the .12 voice base (LiveKit SFU + FunASR + CosyVoice TTS +
silero VAD) exactly as HEL-876 audited it: this module only creates a room
dispatch for the dedicated ``cybergril-voice-agent`` worker and mints a
short-lived join token server-side, so no LiveKit key ever reaches the browser.
Everything here is process-local and stateless apart from the small session
registry: chat state, persona, memory and locks stay in the single API process
that mounts this router (HTTP and the HTTPS voice entry share it).
"""
from __future__ import annotations
import asyncio
import os
import secrets
import string
import time
from dataclasses import dataclass, field
from pathlib import Path
import httpx
import yaml
from . import livekit_wire
DEFAULT_AGENT_NAME = "cybergril-voice-agent"
DEFAULT_TOKEN_TTL = 300.0
DEFAULT_SESSION_TTL = 2 * 3600.0
TTS_HEALTH_CACHE_SECONDS = 30.0
@dataclass
class VoiceConfig:
livekit_url: str
livekit_internal: str
api_key: str
api_secret: str
agent_name: str = DEFAULT_AGENT_NAME
tts_health_url: str = "http://127.0.0.1:9880/health"
token_ttl_seconds: float = DEFAULT_TOKEN_TTL
session_ttl_seconds: float = DEFAULT_SESSION_TTL
dispatch_timeout_seconds: float = 5.0
def sanitized(self) -> dict:
return {
"livekit_url": self.livekit_url,
"agent_name": self.agent_name,
"tts_health_url": self.tts_health_url,
"token_ttl_seconds": self.token_ttl_seconds,
"session_ttl_seconds": self.session_ttl_seconds,
}
class VoiceNotConfigured(Exception):
"""Raised when no config file exists; the endpoint refuses honestly."""
def load_voice_config(
path: Path | str | None = None,
) -> VoiceConfig | None:
"""Load config/voice.yaml; env overrides keep deployment keys out of the repo.
Returns None (not an exception) when nothing is configured: "voice not set
up on this instance" is an honest state, not an error.
"""
path = Path(path or os.environ.get("CYBERGRIL_VOICE_CONFIG", "config/voice.yaml"))
if not path.is_file():
return None
data = yaml.safe_load(path.read_text()) or {}
overrides = {
"livekit_url": os.environ.get("CYBERGRIL_VOICE_LIVEKIT_URL"),
"livekit_internal": os.environ.get("CYBERGRIL_VOICE_LIVEKIT_INTERNAL"),
"api_key": os.environ.get("CYBERGRIL_VOICE_API_KEY"),
"api_secret": os.environ.get("CYBERGRIL_VOICE_API_SECRET"),
"tts_health_url": os.environ.get("CYBERGRIL_VOICE_TTS_HEALTH_URL"),
}
values = {**data, **{k: v for k, v in overrides.items() if v}}
required = ("livekit_url", "livekit_internal", "api_key", "api_secret")
missing = [k for k in required if not values.get(k)]
if missing:
raise VoiceNotConfigured(f"voice config missing fields: {', '.join(missing)}")
return VoiceConfig(
livekit_url=str(values["livekit_url"]),
livekit_internal=str(values["livekit_internal"]),
api_key=str(values["api_key"]),
api_secret=str(values["api_secret"]),
agent_name=str(values.get("agent_name") or DEFAULT_AGENT_NAME),
tts_health_url=str(values.get("tts_health_url") or "http://127.0.0.1:9880/health"),
token_ttl_seconds=float(values.get("token_ttl_seconds") or DEFAULT_TOKEN_TTL),
session_ttl_seconds=float(values.get("session_ttl_seconds") or DEFAULT_SESSION_TTL),
)
@dataclass
class VoiceSession:
session_id: str
room: str
identity: str
created_at: float
expires_at: float
epoch: int
dispatch_id: str = ""
@dataclass
class _Health:
checked: float = 0.0
ok: bool = False
@dataclass
class VoiceSessionService:
config: VoiceConfig
http: httpx.AsyncClient = field(default_factory=httpx.AsyncClient)
clock: object = time.time
tts_health_cache_seconds: float = TTS_HEALTH_CACHE_SECONDS
def __post_init__(self) -> None:
self._sessions: dict[str, VoiceSession] = {}
self._tts_health = _Health(checked=-1e9, ok=False)
self._tts_lock = asyncio.Lock()
# -- honest readiness ---------------------------------------------------
async def tts_available(self) -> bool:
"""Probe the CosyVoice TTS health endpoint, cached like /api/health's LLM probe."""
now = self.clock()
if now - self._tts_health.checked < self.tts_health_cache_seconds:
return self._tts_health.ok
async with self._tts_lock:
if self.clock() - self._tts_health.checked < self.tts_health_cache_seconds:
return self._tts_health.ok
try:
response = await self.http.get(self.config.tts_health_url, timeout=3.0)
ok = response.status_code // 100 == 2
except Exception:
ok = False
self._tts_health = _Health(checked=self.clock(), ok=ok)
return ok
# -- lifecycle ----------------------------------------------------------
def _prune(self) -> None:
now = self.clock()
for session_id in [k for k, v in self._sessions.items() if v.expires_at < now]:
del self._sessions[session_id]
async def open_session(self, *, epoch: int) -> VoiceSession:
self._prune()
alphabet = string.ascii_lowercase + string.digits
room = "cg-voice-" + "".join(secrets.choice(alphabet) for _ in range(10))
identity = "user-" + "".join(secrets.choice(string.ascii_lowercase) for _ in range(8))
dispatch = await livekit_wire.create_dispatch(
self.http,
internal_url=self.config.livekit_internal,
api_key=self.config.api_key,
api_secret=self.config.api_secret,
agent_name=self.config.agent_name,
room=room,
timeout=self.config.dispatch_timeout_seconds,
)
now = self.clock()
session = VoiceSession(
session_id=secrets.token_urlsafe(18),
room=room,
identity=identity,
created_at=now,
expires_at=now + self.config.session_ttl_seconds,
epoch=epoch,
dispatch_id=dispatch.dispatch_id,
)
self._sessions[session.session_id] = session
return session
def token_for(self, session: VoiceSession) -> str:
return livekit_wire.mint_token(
self.config.api_key,
self.config.api_secret,
identity=session.identity,
name="用户",
room=session.room,
room_join=True,
can_publish=True,
can_subscribe=True,
ttl_seconds=self.config.token_ttl_seconds,
now=self.clock(),
)
async def end_session(self, session_id: str) -> VoiceSession | None:
self._prune()
session = self._sessions.pop(session_id, None)
if session is None:
return None
await livekit_wire.delete_room(
self.http,
internal_url=self.config.livekit_internal,
api_key=self.config.api_key,
api_secret=self.config.api_secret,
room=session.room,
timeout=self.config.dispatch_timeout_seconds,
)
return session
def get(self, session_id: str) -> VoiceSession | None:
self._prune()
return self._sessions.get(session_id)
async def aclose(self) -> None:
await self.http.aclose()
+231
View File
@@ -0,0 +1,231 @@
"""FunASR 流式 STT 的 livekit-agents 适配器(CyberGril 语音 worker 用).
复用自 .12 /opt/voice-agent/agent/stt_funasr.py(10-16/10-24 两次真实通话验证
过的同一实现,未 fork、未改协议),仅加包路径与出处标注:worker 独立目录
/opt/voice-agent-cybergril 自带一份,通用 worker 的原文件不动。
对接 FunASR 官方 2pass websocket 服务(runtime SDK, 端口 10095):
- livekit 音频帧重采样到 16k PCM 后推送
- 2pass-online 响应 -> INTERIM_TRANSCRIPT(实时草稿)
- 收到 flush(VAD 判定用户说完) -> 发 {"is_speaking": false}, 等 2pass-offline 纠错终稿
-> FINAL_TRANSCRIPT, 之后为本轮重建 websocket(FunASR 一次会话一句话)
一个 RecognizeStream 对应一个房间会话, websocket 按轮次惰性重建.
"""
from __future__ import annotations
import asyncio
import contextlib
import json
from typing import Any
import websockets
from livekit import rtc
from livekit.agents import stt
from livekit.agents.stt import (
RecognizeStream,
SpeechData,
SpeechEvent,
SpeechEventType,
)
from livekit.agents.types import DEFAULT_API_CONNECT_OPTIONS, APIConnectOptions
FUNASR_WS = "ws://127.0.0.1:10095"
class FunASRSTT(stt.STT):
def __init__(self, endpoint: str = FUNASR_WS) -> None:
super().__init__(
capabilities=stt.STTCapabilities(streaming=True, interim_results=True)
)
self._endpoint = endpoint
# 回声抑制(worker 运行时注入): agent 说话期间, 短文本或与刚说内容
# 高度相似的识别结果视为音箱回声, 不作为新轮次提交
self.agent_speaking = False
self.agent_recent_text = ""
def _is_echo(self, text: str) -> bool:
if not self.agent_speaking or not text:
return False
if len(text) <= 8:
return True # 说话期间识别出 <=8 字 → 大概率是回声碎片
from difflib import SequenceMatcher
recent = self.agent_recent_text
if recent:
ratio = SequenceMatcher(None, text, recent).ratio()
if ratio >= 0.55:
return True
return False
@property
def provider(self) -> str:
return "funasr"
@property
def model(self) -> str:
return "paraformer-zh-streaming-2pass"
async def _recognize_impl(
self, buffer, *, language=None, conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS
) -> SpeechEvent:
raise NotImplementedError("FunASR adapter only supports streaming")
def stream(
self, *, language=None, conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS
) -> RecognizeStream:
return _LoggedRecognizeStream(stt=self, conn_options=conn_options, endpoint=self._endpoint)
class _Utterance:
"""一轮用户发言: 一个独立 websocket, flush 后结束"""
def __init__(self, endpoint: str):
self.endpoint = endpoint
self.ws: websockets.WebSocketClientProtocol | None = None
self.closed = False
self.last_text = ""
class FunASRRecognizeStream(RecognizeStream):
def __init__(self, *, stt: FunASRSTT, conn_options: APIConnectOptions, endpoint: str) -> None:
super().__init__(stt=stt, conn_options=conn_options)
self._endpoint = endpoint
def _ev(self, ev_type: SpeechEventType, text: str) -> SpeechEvent:
return SpeechEvent(
type=ev_type,
alternatives=[SpeechData(language="zh", text=text)],
)
async def _run(self) -> None:
utt: _Utterance | None = None
recv_task: asyncio.Task | None = None
finals: asyncio.Queue[str] = asyncio.Queue()
resampler: rtc.AudioResampler | None = None # 有状态, 全程复用
n_frames = 0
async def open_utt() -> _Utterance:
ws = await websockets.connect(self._endpoint, max_size=2**24)
cfg = {
"mode": "2pass",
"wav_name": "livekit",
"is_speaking": True,
"wav_format": "pcm",
"chunk_size": [5, 10, 5],
"audio_fs": 16000,
"itn": True,
}
await ws.send(json.dumps(cfg))
u = _Utterance(self._endpoint)
u.ws = ws
return u
async def recv_loop(u: _Utterance) -> None:
assert u.ws is not None
pending: list[str] = [] # 去抖合并中的 final 片段
emit_task: asyncio.Task | None = None
def strip_punct(t: str) -> str:
return t.lstrip(",。!?、,.!?;;:: ")
async def emit_merged_final() -> None:
# 600ms 内无后续片段才视为一句说完, 合并成单个 FINAL
await asyncio.sleep(0.6)
merged = strip_punct("".join(pending))
pending.clear()
if not merged:
return
stt_ref: FunASRSTT = self._stt # type: ignore[assignment]
if stt_ref._is_echo(merged):
print(f"[stt] echo suppressed: {merged[:40]}", flush=True)
return
print(f"[stt] FINAL(merged): {merged[:60]}", flush=True)
self._event_ch.send_nowait(self._ev(SpeechEventType.FINAL_TRANSCRIPT, merged))
await finals.put(merged)
try:
async for msg in u.ws:
data: dict[str, Any] = json.loads(msg)
text = (data.get("text") or "").strip()
if not text:
continue
if str(data.get("mode", "")).endswith("offline"):
# 离线纠错终稿: 去抖合并后作为单个 FINAL 推给框架
u.last_text = text
pending.append(text)
if emit_task is not None:
emit_task.cancel()
emit_task = asyncio.create_task(emit_merged_final())
else:
u.last_text = text
print(f"[stt] interim: {text[:60]}", flush=True)
self._event_ch.send_nowait(
self._ev(SpeechEventType.INTERIM_TRANSCRIPT, text)
)
except Exception:
pass
try:
async for ev in self._input_ch:
if ev is None: # 流关闭
break
if isinstance(ev, RecognizeStream._FlushSentinel):
if utt is not None and utt.ws is not None:
print(
f"[stt] flush after {n_frames} frames, "
f"last_text={utt.last_text!r}",
flush=True,
)
with contextlib.suppress(Exception):
await utt.ws.send(json.dumps({"is_speaking": False}))
# 等离线终稿, 最多 2.5s, 超时用最后的 online 文本兜底
try:
final = await asyncio.wait_for(finals.get(), timeout=2.5)
except TimeoutError:
final = utt.last_text
if final:
self._event_ch.send_nowait(
self._ev(SpeechEventType.FINAL_TRANSCRIPT, final)
)
if recv_task is not None:
recv_task.cancel()
with contextlib.suppress(asyncio.CancelledError):
await recv_task
with contextlib.suppress(Exception):
await utt.ws.close()
utt = None
continue
if not isinstance(ev, rtc.AudioFrame):
continue
frame: rtc.AudioFrame = ev
if utt is None: # 新一轮发言, 惰性建连
utt = await open_utt()
recv_task = asyncio.create_task(recv_loop(utt))
print(f"[stt] utterance open, frame sr={frame.sample_rate}", flush=True)
n_frames += 1
if frame.sample_rate != 16000:
if resampler is None:
resampler = rtc.AudioResampler(frame.sample_rate, 16000)
for f in resampler.push(frame):
await utt.ws.send(bytes(f.data))
else:
await utt.ws.send(bytes(frame.data))
finally:
if recv_task is not None:
recv_task.cancel()
if utt is not None and utt.ws is not None:
with contextlib.suppress(Exception):
await utt.ws.close()
class _LoggedRecognizeStream(FunASRRecognizeStream):
"""调试: 打印框架实际读取的每个事件"""
async def __anext__(self) -> SpeechEvent:
ev = await super().__anext__()
txt = ev.alternatives[0].text[:40] if ev.alternatives else ""
print(f"[stt->session] {ev.type.value}: {txt}", flush=True)
return ev
+117
View File
@@ -0,0 +1,117 @@
"""CosyVoice3 HTTP 流式 TTS 的 livekit-agents 适配器(CyberGril 语音 worker 用).
复用自 .12 /opt/voice-agent/agent/tts_cosyvoice.py(同一已验证实现,未 fork、
未改协议)。CyberGril worker 读取自己的音色状态文件(默认
/opt/voice-agent-cybergril/voice_state_cybergril.json),不读通用助手的
voice_state.json;最终音色(D1)仍待白栖知拍板,这里不替用户定。
对接 /opt/voice-agent/cosyvoice/server.py:
POST /tts {"text":..., "voice":...} -> audio/L16 (24k mono int16) 字节流
"""
from __future__ import annotations
import time
import uuid
import httpx
from livekit import rtc
from livekit.agents import tts
from livekit.agents.tts import (
AudioEmitter,
ChunkedStream,
TTSCapabilities,
)
from livekit.agents.types import DEFAULT_API_CONNECT_OPTIONS, APIConnectOptions
COSYVOICE_URL = "http://127.0.0.1:9880"
class CosyVoiceTTS(tts.TTS):
def __init__(self, endpoint: str = COSYVOICE_URL, default_voice: str = "default") -> None:
super().__init__(
capabilities=TTSCapabilities(streaming=False),
sample_rate=24000,
num_channels=1,
)
self._endpoint = endpoint.rstrip("/")
self._default_voice = default_voice
self._http = httpx.AsyncClient(timeout=httpx.Timeout(30, read=120))
@property
def provider(self) -> str:
return "cosyvoice3"
@property
def model(self) -> str:
return "Fun-CosyVoice3-0.5B-2512"
async def aclose(self) -> None:
await self._http.aclose()
def synthesize(
self,
text: str,
*,
conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS,
) -> ChunkedStream:
return CosyVoiceChunkedStream(
tts=self, input_text=text, conn_options=conn_options, voice=self._default_voice
)
class CosyVoiceChunkedStream(ChunkedStream):
def __init__(
self,
*,
tts: CosyVoiceTTS,
input_text: str,
conn_options: APIConnectOptions,
voice: str,
) -> None:
super().__init__(tts=tts, input_text=input_text, conn_options=conn_options)
self._voice = voice
async def _run(self, output_emitter: AudioEmitter) -> None:
req_id = uuid.uuid4().hex
t0 = time.perf_counter()
output_emitter.initialize(
request_id=req_id,
sample_rate=24000,
num_channels=1,
mime_type="audio/pcm",
)
first = True
buf = bytearray()
def emit_frames() -> None:
# 按 480 样本(20ms)切帧, push_frame 跳过容器解码
step = 480 * 2 # int16 字节
while len(buf) >= step:
frame = rtc.AudioFrame(bytes(buf[:step]), 24000, 1, 480)
output_emitter.push_frame(frame)
del buf[:step]
async with self._tts._http.stream(
"POST",
f"{self._tts._endpoint}/tts",
json={"text": self._input_text, "voice": self._voice},
) as resp:
resp.raise_for_status()
async for chunk in resp.aiter_bytes():
if not chunk:
continue
if first:
print(
f"[tts] first audio after {time.perf_counter() - t0:.3f}s "
f"({self._input_text[:20]}...)",
flush=True,
)
first = False
buf.extend(chunk)
emit_frames()
if buf:
n = len(buf) // 2
frame = rtc.AudioFrame(bytes(buf), 24000, 1, n)
output_emitter.push_frame(frame)
output_emitter.flush()
+189
View File
@@ -0,0 +1,189 @@
"""CyberGril 专属语音 worker(HEL-877,agent_name=cybergril-voice-agent).
组装与 /opt/voice-agent/agent/agent.py 同源(10-16/10-24 两次真实通话验证的
级联链路):
麦克风 -> silero VAD(端点检测/打断) -> FunASR(流式 STT)
-> 统一 CyberGril 实例 POST /api/chat(她的人格/情绪/关系/记忆/生活分享/
调用限制全部在服务端同一业务链里;worker 不持有第二份人格或记忆,
不直连任何 LLM,不读通用助手 persona_state/voice_state)
-> CosyVoice3(流式 TTS) -> 播放
打断: VAD 判定用户开口即打断(AgentSession 默认 allow_interruptions):
生成任务被取消,ChatApiLLMStream 的 HTTP 流在 finally 立刻关闭,
服务端随即把旧轮 user 行标 cancelled——不等下一次 ASR final。
文字与语音同走 /api/chat,互相争用由服务端同一轮次门处理。
回执: 只有 SDK 真实播放完成(speech handle done、未被打断、无异常、轮次
完整带 receipt)才 POST /api/chat/received;被打断、断线、播放失败、
chat.error(φ 文案原句念出)一律不确认。
字幕: cg.subtitle 数据消息发到房间(契约见 docs/voice-contract-hel877.md)。
音色: 独立 voice_state_cybergril.json;D1 未拍板前回落 default,不替用户定。
运行位置: /opt/voice-agent-cybergril/(独立目录,复用 .12 现有 agent venv 与
LiveKit/FunASR/CosyVoice;专属健康端口 CYBERGRIL_WORKER_HEALTH_PORT——
livekit-agents worker 内建 HTTP 健康检查,GET / 返回 OK/503)。
本文件只在 agent venv(livekit-agents 1.8.8)中导入;产品 API 进程不导入它。
"""
from __future__ import annotations
import asyncio
import json
import os
from pathlib import Path
from livekit.agents import Agent, AgentSession, JobContext, JobProcess, WorkerOptions, cli
from livekit.plugins.silero import VAD
from .llm_chat_api import CyberGrillLLM
from .receipt import ReceiptSender, TurnLedger, should_ack
from .stt_funasr import FunASRSTT
from .tts_cosyvoice import CosyVoiceTTS
AGENT_NAME = os.environ.get("CYBERGRIL_AGENT_NAME", "cybergril-voice-agent")
API_BASE = os.environ.get("CYBERGRIL_API_BASE", "http://127.0.0.1:8360")
VOICE_STATE = Path(
os.environ.get(
"CYBERGRIL_VOICE_STATE", "/opt/voice-agent-cybergril/voice_state_cybergril.json"
)
)
WORKER_HEALTH_PORT = int(os.environ.get("CYBERGRIL_WORKER_HEALTH_PORT", "8082"))
SUBTOPIC = "cg.subtitle"
# 占位指令:真正的人格由统一服务在 /api/chat 服务端组装。适配器忽略
# chat_ctx/instructions(latest_user_text 只取当前用户话轮),这里不放任何
# 人格内容,避免出现第二份她。
INSTRUCTIONS_PLACEHOLDER = "语音通道适配层:回复内容由统一服务生成。"
def read_default_voice() -> str:
"""CyberGril 自己的音色状态;缺文件回落 default(D1 未拍板不替用户定)。"""
try:
return json.loads(VOICE_STATE.read_text(encoding="utf-8")).get("voice", "default")
except Exception:
return "default"
def prewarm(proc: JobProcess) -> None:
proc.userdata["vad"] = VAD.load()
async def _maybe_open_proactive(session: AgentSession, room) -> None:
"""CG-011 主动开口接缝(本卡不实现,留明确边界,不丢需求)。
语音里的主动开口必须:仅在已开启的语音会话内、走同一条业务链(只念
服务端已落库、标记 proactive=1 的 companion 行,不新起模型调用)、可被
用户打断、不新造第二条回执通道。具体呈现与节奏由总管/视觉总监在接线
卡定;在此之前保持空操作。
"""
return None
async def entrypoint(ctx: JobContext) -> None:
stt = FunASRSTT()
# agent 说话期间短文本/相似文本视为回声丢弃(同通用 worker 的实测做法)
stt.agent_speaking = False
stt.agent_recent_text = ""
ledger = TurnLedger()
def note_stream(stream) -> None:
ledger.note_stream(stream, stream.created_at)
llm = CyberGrillLLM(API_BASE, on_stream_started=note_stream)
receipts = ReceiptSender(llm.client)
session = AgentSession(
stt=stt,
llm=llm,
tts=CosyVoiceTTS(default_voice=read_default_voice()),
vad=ctx.proc.userdata["vad"],
turn_handling={
# 停顿稍久才判说完, 合并慢语速碎片(同通用 worker 实测参数)
"endpointing": {"min_delay": 0.8, "max_delay": 6.0},
},
)
def subtitle(payload: dict) -> None:
data = json.dumps(payload, ensure_ascii=False).encode()
asyncio.get_running_loop().create_task(
ctx.room.local_participant.publish_data(data, topic=SUBTOPIC, reliable=False)
)
@session.on("user_input_transcribed")
def _on_transcript(ev) -> None:
if ev.transcript.strip():
subtitle({
"kind": "user_final" if ev.is_final else "interim",
"role": "user",
"text": ev.transcript,
})
async def _after_playout(handle) -> None:
# SDK 真实播放完成(wait_for_playout 返回)之后才考虑回执。
await handle.wait_for_playout()
stream = ledger.stream_for(handle)
if stream is None:
return
failed = handle.exception() is not None
if stream.error_phi:
subtitle({"kind": "error", "role": "assistant", "text": stream.error_phi})
return
if stream.text and not handle.interrupted:
subtitle({"kind": "assistant_final", "role": "assistant", "text": stream.text})
epoch = None
try:
epoch = await llm.client.current_epoch()
except Exception:
epoch = stream.receipt.get("epoch") if stream.receipt else None
if should_ack(
played_to_end=True,
interrupted=handle.interrupted,
failed=failed,
receipt=stream.receipt,
current_epoch=epoch,
):
await receipts.confirm(stream.turn_id, stream.receipt)
@session.on("speech_created")
def _on_speech_created(ev) -> None:
if not ev.user_initiated:
return
ledger.note_handle(ev.speech_handle, ev.created_at)
ev.speech_handle.add_done_callback(
lambda handle=ev.speech_handle: asyncio.get_running_loop().create_task(
_after_playout(handle)
)
)
@session.on("conversation_item_added")
def _on_item(ev) -> None:
if ev.item.role == "assistant":
texts = [
getattr(p, "text", "") or (p if isinstance(p, str) else "")
for p in (ev.item.content or [])
]
text = "".join(t for t in texts if t).strip()
if text:
stt.agent_recent_text = text
@session.on("agent_state_changed")
def _on_state(ev) -> None:
stt.agent_speaking = getattr(ev, "new_state", "") == "speaking"
await ctx.connect()
await session.start(room=ctx.room, agent=Agent(instructions=INSTRUCTIONS_PLACEHOLDER))
await _maybe_open_proactive(session, ctx.room)
print(
f"[cybergril-worker] session started (api={API_BASE}, "
f"voice={read_default_voice()}, agent_name={AGENT_NAME})",
flush=True,
)
if __name__ == "__main__":
cli.run_app(
WorkerOptions(
entrypoint_fnc=entrypoint,
prewarm_fnc=prewarm,
agent_name=AGENT_NAME,
port=WORKER_HEALTH_PORT,
)
)