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:
@@ -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,
|
||||
)
|
||||
)
|
||||
Reference in New Issue
Block a user