- asr_usage.py (stdlib-only): append-only JSONL ledger, per-call/window audio seconds counted from actually-sent frames (sample-rate aware, resend counted), connect attempt/failure/retry semantics (normal per-utterance reconnects are not retries), fail-closed default (real cap=0 unless a window is armed), pre-send blocking so no byte crosses the cap, ledger replay for restart recovery and cross-window isolation, resumable summarize CLI - stt_funasr.py: guard hooks on the real send path (check_connect before open_utt, precheck before send, count after send, recv-side death recorded, per-utterance flush aggregation); usage=None keeps prior behavior - worker.py: entrypoint builds guard from env per job, room name as call id, on_exhausted -> ctx.shutdown ends the call, window summary in start log - tests: 17 deterministic offline tests incl. fake livekit/websockets SDK driving the real _run seam, sample-rate variants, silence/cancel/failure/ reconnect/repeated-end, cap rejection before crossing, ledger persistence across restart, room deletion keeps history, other windows unaffected Co-authored-by: multica-agent <github@multica.ai>
343 lines
16 KiB
Python
343 lines
16 KiB
Python
"""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(φ 文案原句念出)一律不确认。归属是确切的:生成流通过
|
||
SDK 自己的 agents_speech_handle 上下文绑定到它所属的 SpeechHandle,
|
||
不按事件先后猜(HEL-879 收口)。
|
||
字幕: cg.subtitle 数据消息发到房间,契约 v2(带 v/seq/speech_id/起止事件,
|
||
见 docs/voice-subtitle-contract-v2.md)。
|
||
音色: 独立 voice_state_cybergril.json;D1 未拍板前回落 default,不替用户定。
|
||
|
||
HEL-906 连续通话 ASR 用量: entrypoint 按 job 构造 AsrUsageGuard 注入
|
||
FunASRSTT(房间名作为每通标识)。未布防(无 CYBERGRIL_ASR_WINDOW_ID)
|
||
即 fail-closed 拒绝一切 ASR 连接/音频(真实 cap=0);获批的一次性窗口
|
||
由窗口负责人启动时显式设置环境变量(见 voice/asr_usage.py 与
|
||
docs/rework/hel902/r5-followup-package.md §4)。触线时 guard 在发送前
|
||
拒绝并经 on_exhausted 回调 ctx.shutdown 结束本通 job;逐通/全窗计数落
|
||
asr-usage.jsonl,不随删房丢失。
|
||
|
||
运行位置: /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 进程不导入它。
|
||
事件接线集中在 bind_voice_session(离线真 SDK 检查直接驱动它注册的回调,
|
||
scripts/gen_hel877_sdk_check.py 不再手抄复刻)。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import contextlib
|
||
import inspect
|
||
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 .asr_usage import build_usage_from_env
|
||
from .llm_chat_api import CyberGrillLLM
|
||
from .receipt import ReceiptSender, TurnLedger, should_ack
|
||
from .seam import AssistantInterimPublisher, SubtitleBus, pending_proactive
|
||
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"))
|
||
# CG-011 语音主动开口(HEL-879 最小接缝):默认关闭,接线卡与视觉作者定好
|
||
# 入口呈现并经批准后才置 1。开启后只念服务端已落库 proactive=1 的行。
|
||
PROACTIVE_VOICE = os.environ.get("CYBERGRIL_PROACTIVE_VOICE", "") == "1"
|
||
PROACTIVE_PER_SESSION = 1
|
||
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()
|
||
|
||
|
||
def make_subtitle_publisher(room):
|
||
"""cg.subtitle 数据通道(contract v2 信封由 SubtitleBus 统一加)。"""
|
||
def subtitle(payload: dict) -> None:
|
||
data = json.dumps(payload, ensure_ascii=False).encode()
|
||
asyncio.get_running_loop().create_task(
|
||
room.local_participant.publish_data(data, topic=SUBTOPIC, reliable=False)
|
||
)
|
||
return subtitle
|
||
|
||
|
||
def make_voice_llm(api_base: str, *, ledger: TurnLedger,
|
||
interim: AssistantInterimPublisher, client=None) -> CyberGrillLLM:
|
||
"""CyberGrillLLM + 确切归属接线(worker 的唯一 LLM 组装方式).
|
||
|
||
on_stream_started 拿到 SDK 生成上下文里的确切 SpeechHandle(适配器读
|
||
agents_speech_handle ContextVar):字幕按该 speech_id 开轮,账本按该
|
||
handle 精确绑定;无归属(None/未登记)一律 fail-closed,不绑任何轮。
|
||
"""
|
||
def on_stream_started(stream, speech_handle) -> None:
|
||
if stream.speech_id:
|
||
interim.begin(stream.speech_id)
|
||
ledger.note_stream(stream, speech_handle)
|
||
|
||
def on_assistant_delta(stream, delta: str) -> None:
|
||
interim.feed(stream.speech_id, delta)
|
||
|
||
return CyberGrillLLM(api_base, client=client,
|
||
on_stream_started=on_stream_started,
|
||
on_assistant_delta=on_assistant_delta)
|
||
|
||
|
||
def bind_voice_session(session: AgentSession, *, llm: CyberGrillLLM,
|
||
ledger: TurnLedger, interim: AssistantInterimPublisher,
|
||
bus: SubtitleBus, stt, receipts) -> None:
|
||
"""把 worker 的全部会话事件回调注册到真 AgentSession(唯一接线点).
|
||
|
||
scripts/gen_hel877_sdk_check.py 在 .12 真实 SDK 上加载本模块并直接驱动
|
||
这里注册的回调,不手抄复刻任何函数。
|
||
"""
|
||
outcomes: dict[str, str] = {} # speech_id -> last outcome (diagnostics)
|
||
|
||
@session.on("user_input_transcribed")
|
||
def _on_transcript(ev) -> None:
|
||
if ev.transcript.strip():
|
||
bus.emit("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()
|
||
# HEL-879:先判定失败/打断并整单放弃(fail-closed)——被放弃的绑定
|
||
# 只属于这一轮,绝不会吞掉下一轮的回执归属。
|
||
failed = handle.exception() is not None
|
||
speech_id = getattr(handle, "id", "")
|
||
if handle.interrupted or failed:
|
||
ledger.discard(handle)
|
||
interim.cancel(speech_id, "interrupted" if handle.interrupted else "failed")
|
||
outcomes[speech_id] = "cancelled"
|
||
return
|
||
stream = ledger.stream_for(handle)
|
||
if stream is None:
|
||
# 无确切归属(生成从未开始/被退役/主动 say 无 LLM 流):不确认、
|
||
# 不发 final——fail-closed。
|
||
interim.cancel(speech_id, "no-generation")
|
||
outcomes[speech_id] = "unattributed"
|
||
return
|
||
if stream.error_phi:
|
||
bus.emit("error", role="assistant", text=stream.error_phi,
|
||
speech_id=speech_id)
|
||
interim.cancel(speech_id, "error_phi")
|
||
outcomes[speech_id] = "error_phi"
|
||
return
|
||
epoch = None
|
||
try:
|
||
epoch = await llm.client.current_epoch()
|
||
except Exception:
|
||
epoch = stream.receipt.get("epoch") if stream.receipt else None
|
||
# Contract v2 (HEL-879 timing fix): assistant_final means the archive
|
||
# really holds this turn — an incomplete stream, or one without a
|
||
# legal same-turn receipt (missing fields / stale epoch), closes with
|
||
# turn_cancel ONLY. The final is never sent first and retracted after.
|
||
if not getattr(stream, "completed", False):
|
||
interim.cancel(speech_id, "incomplete")
|
||
outcomes[speech_id] = "incomplete"
|
||
return
|
||
if should_ack(
|
||
played_to_end=True,
|
||
interrupted=handle.interrupted,
|
||
failed=failed,
|
||
receipt=stream.receipt,
|
||
current_epoch=epoch,
|
||
):
|
||
interim.finish(speech_id, turn_id=stream.turn_id, text=stream.text)
|
||
await receipts.confirm(stream.turn_id, stream.receipt)
|
||
outcomes[speech_id] = "acked"
|
||
else:
|
||
interim.cancel(speech_id, "no-receipt")
|
||
outcomes[speech_id] = "no-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"
|
||
|
||
|
||
async def speak_proactive_row(session: AgentSession, bus: SubtitleBus, row: dict) -> None:
|
||
"""念一条已落库 proactive 行,并给同源 message_id 的字幕起止/打断事件.
|
||
|
||
字幕生命周期绑定在 say 返回的 SpeechHandle 上(proactive_start ->
|
||
proactive_end/proactive_cancel),不借用任何回执分支。
|
||
|
||
真实 SDK 的 AgentSession.say 是同步函数、返回可 await 的 SpeechHandle
|
||
(await 它=等整段播完,HEL-879 timing 修正):先取 handle、立刻发布
|
||
proactive_start 并注册该 handle 的 end/cancel,再等这一条播完——start
|
||
绝不能等声音播完后才发。await 型替身(测试桩)同样支持。
|
||
"""
|
||
result = session.say(row["text"], allow_interruptions=True)
|
||
# iscoroutine (NOT isawaitable): the real SpeechHandle itself defines
|
||
# __await__ (awaiting it = waiting out the playout) — only a coroutine
|
||
# from an await-style stand-in needs resolving to reach the handle.
|
||
handle = await result if inspect.iscoroutine(result) else result
|
||
speech_id = getattr(handle, "id", "")
|
||
bus.emit("proactive_start", role="assistant", text=row["text"],
|
||
speech_id=speech_id, message_id=row["id"])
|
||
|
||
def _on_say_done(h, sid=speech_id, mid=row["id"]) -> None:
|
||
if h.interrupted or h.exception() is not None:
|
||
bus.emit("proactive_cancel", role="assistant", speech_id=sid,
|
||
message_id=mid,
|
||
reason="interrupted" if h.interrupted else "failed")
|
||
else:
|
||
bus.emit("proactive_end", role="assistant", speech_id=sid, message_id=mid)
|
||
|
||
handle.add_done_callback(_on_say_done)
|
||
# 逐条念:等 THIS 行播完再返回(替身 handle 不可 await 时直接返回;
|
||
# 播放中的异常已由 done 回调按 cancel 收口,这里不再向上抛)。
|
||
if inspect.isawaitable(handle):
|
||
with contextlib.suppress(Exception):
|
||
await handle
|
||
|
||
|
||
async def _maybe_open_proactive(session: AgentSession, room, bus: SubtitleBus,
|
||
client=None, already_spoken: set[int] | None = None
|
||
) -> list[int]:
|
||
"""CG-011 主动开口最小接缝(HEL-879:真实代码路径,默认关闭).
|
||
|
||
仅在已开启的语音会话内、只念服务端已落库、标记 proactive=1、未在本房间
|
||
念过的 companion 行(同一 GET /api/messages 入口,无第二人格/无新模型调用),
|
||
`session.say(..., allow_interruptions=True)` 可被用户打断,不新建回执通道
|
||
(文字回执规则独立且已存在)。每会话有界(PROACTIVE_PER_SESSION)。
|
||
这是「会话开时念已落库旧留言」的最小实现,不冒充会话中完整 CG-011 主动
|
||
表达;入口呈现与节奏由总管/视觉总监在接线卡定;批准前置
|
||
CYBERGRIL_PROACTIVE_VOICE=1。返回本次念出的消息 id(接线/验收用;未启用
|
||
返回空)。
|
||
"""
|
||
if not PROACTIVE_VOICE:
|
||
return []
|
||
spoken: set[int] = already_spoken if already_spoken is not None else set()
|
||
rows = await pending_proactive(client, already_spoken=spoken,
|
||
limit=PROACTIVE_PER_SESSION)
|
||
spoken_ids: list[int] = []
|
||
for row in rows:
|
||
await speak_proactive_row(session, bus, row)
|
||
spoken_ids.append(row["id"])
|
||
return spoken_ids
|
||
|
||
|
||
def _shutdown_job(ctx, reason: str) -> None:
|
||
"""AsrUsageGuard 触线回调: 结束本通 job(异步 shutdown 兼容为任务)."""
|
||
print(f"[cybergril-worker] asr window stop: {reason}; ending this call", flush=True)
|
||
with contextlib.suppress(Exception):
|
||
result = ctx.shutdown()
|
||
if inspect.isawaitable(result):
|
||
asyncio.get_running_loop().create_task(result)
|
||
|
||
|
||
async def entrypoint(ctx: JobContext) -> None:
|
||
usage = build_usage_from_env(
|
||
on_exhausted=lambda reason: _shutdown_job(ctx, reason))
|
||
stt = FunASRSTT(usage=usage, call_label=getattr(ctx.room, "name", ""))
|
||
# agent 说话期间短文本/相似文本视为回声丢弃(同通用 worker 的实测做法)
|
||
stt.agent_speaking = False
|
||
stt.agent_recent_text = ""
|
||
|
||
subtitle = make_subtitle_publisher(ctx.room)
|
||
bus = SubtitleBus(subtitle)
|
||
ledger = TurnLedger()
|
||
interim = AssistantInterimPublisher(bus)
|
||
|
||
llm = make_voice_llm(API_BASE, ledger=ledger, interim=interim)
|
||
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},
|
||
},
|
||
)
|
||
bind_voice_session(session, llm=llm, ledger=ledger, interim=interim,
|
||
bus=bus, stt=stt, receipts=receipts)
|
||
|
||
await ctx.connect()
|
||
await session.start(room=ctx.room, agent=Agent(instructions=INSTRUCTIONS_PLACEHOLDER))
|
||
spoken_proactive: set[int] = set()
|
||
try:
|
||
spoken = await _maybe_open_proactive(session, ctx.room, bus, client=llm.client,
|
||
already_spoken=spoken_proactive)
|
||
spoken_proactive.update(spoken)
|
||
except Exception as exc: # seam failure never breaks the session start
|
||
print(f"[cybergril-worker] proactive seam skipped: {type(exc).__name__}: {exc}",
|
||
flush=True)
|
||
print(
|
||
f"[cybergril-worker] session started (api={API_BASE}, "
|
||
f"voice={read_default_voice()}, agent_name={AGENT_NAME}, "
|
||
f"asr_window=({usage.summary_line()}))",
|
||
flush=True,
|
||
)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
cli.run_app(
|
||
WorkerOptions(
|
||
entrypoint_fnc=entrypoint,
|
||
prewarm_fnc=prewarm,
|
||
agent_name=AGENT_NAME,
|
||
port=WORKER_HEALTH_PORT,
|
||
)
|
||
)
|