LoveLogicAI's picture
Render/publish errors logged + skipped, never fatal
4b260b9 verified
Raw History Blame Contribute Delete
22.1 kB
"""FREESTREAM bot β€” the MVP LiveKit session process (run with -m freestream.bot).
One bot = one LiveKit session:
join room -> publish mic (Piper audio) + camera (animated face) tracks
-> subscribe remote audio -> energy-VAD -> faster-whisper -> agent reply
-> Piper synthesis -> audio push with 150ms avatar pre-roll.
Status protocol: JSON lines on stdout ("status"/"timing" events) plus
state.json in the session dir (what the CLI polls). SIGTERM closes the
session gracefully.
"""
from __future__ import annotations
import argparse
import asyncio
import json
import os
import signal
import sys
import time
from pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from freestream import avatar as avatar_mod
from freestream.agent import load_agent
from freestream.asr import Segmenter, Transcriber
from freestream.events import EventLog
from freestream.persona import VoiceBackend
AVATAR_FPS = avatar_mod.FPS
PRE_ROLL_S = 0.15
IDLE_FPS = 2 # static face refresh when not speaking
def emit(obj: dict):
print(json.dumps(obj), flush=True)
class BotSession:
def __init__(self, url: str, token: str, room_name: str, bot_name: str,
image: Path, voice: str, session_dir: Path, session_id: str,
system_prompt: str | None):
self.url, self.token, self.room_name = url, token, room_name
self.bot_name = bot_name
self.image = image
self.voice_backend = VoiceBackend(voice)
self.session_dir = Path(session_dir)
self.session_dir.mkdir(parents=True, exist_ok=True)
self.session_id = session_id
self.state = "connecting"
self.log = EventLog(self.session_dir / "bot-events.jsonl") # separate chain from the CLI log
self.agent = load_agent(system_prompt, bot_name,
card_path=os.environ.get("FREESTREAM_CHARACTER_CARD"))
self.renderer = avatar_mod.AvatarRenderer(image if image.exists() else None)
self.mouth = 0.0 # current openness, driven by the speak loop
self.speaking_until = 0.0
self.transcriber = Transcriber()
self.segmenter = Segmenter()
self.first_utterance_done = False
self.disclosure_segment = None # (pcm, sr) consent line, cached at warmup
self._tool_depth = 0 # >0 while the character is in her toolbelt
def _tool_start(tool):
self._tool_depth += 1 # avatar posture -> WORKING (live)
def _tool_end(tool):
self._tool_depth = max(0, self._tool_depth - 1)
self.agent = load_agent(system_prompt, bot_name,
card_path=os.environ.get("FREESTREAM_CHARACTER_CARD"),
on_tool_start=_tool_start, on_tool_end=_tool_end)
self._spec_task: asyncio.Task | None = None
self._spec_cancel: asyncio.Event | None = None
self._handled_speculative = False
# -- cgroup throttle probe (contention investigation) -------------------
@staticmethod
def _read_cpu_stat() -> dict:
try:
fields = dict(line.split() for line in
open("/sys/fs/cgroup/cpu.stat").read().splitlines())
return {k: int(v) for k, v in fields.items() if k in
("nr_throttled", "throttled_usec", "nr_periods")}
except OSError:
return {}
def _throttle_delta(self) -> dict:
"""cgroup CPU throttling accumulated during this turn β€” the direct
measure of quota contention (docs/LATENCY.md, remaining lever b)."""
now = self._read_cpu_stat()
prev = getattr(self, "_cpu_stat_prev", None)
self._cpu_stat_prev = now
if not now or not prev:
return {}
return {"throttled_periods": now.get("nr_throttled", 0) - prev.get("nr_throttled", 0),
"throttled_ms": round((now.get("throttled_usec", 0)
- prev.get("throttled_usec", 0)) / 1000, 1)}
# -- state ---------------------------------------------------------------
def set_state(self, s: str, **extra):
self.state = s
payload = {"session_id": self.session_id, "status": s, **extra}
(self.session_dir / "state.json").write_text(json.dumps(payload))
self.log.append("session.status", status=s)
emit({"event": "status", **payload})
# -- tracks ---------------------------------------------------------------
async def publish_tracks(self, room):
import livekit.rtc as rtc
# camera
self.video_source = rtc.VideoSource(avatar_mod.SIZE, avatar_mod.SIZE)
vtrack = rtc.LocalVideoTrack.create_video_track("freestream-face", self.video_source)
vopts = rtc.TrackPublishOptions(source=rtc.TrackSource.SOURCE_CAMERA)
vopts.video_encoding.max_framerate = float(AVATAR_FPS) # proto message: set subfields,
vopts.video_encoding.max_bitrate = 800_000 # not the whole sub-message
await room.local_participant.publish_track(vtrack, vopts)
# microphone
self.audio_source = rtc.AudioSource(22050, 1)
atrack = rtc.LocalAudioTrack.create_audio_track("freestream-voice", self.audio_source)
aopts = rtc.TrackPublishOptions(source=rtc.TrackSource.SOURCE_MICROPHONE)
await room.local_participant.publish_track(atrack, aopts)
async def video_loop(self):
"""Render the face continuously; mouth openness follows speech energy.
FREESTREAM_PAUSE_RENDER=1 skips rendering while the bot is not
speaking (thinking/ASR) β€” experiment knob for in-context contention.
"""
import livekit.rtc as rtc
pause_render = os.environ.get("FREESTREAM_PAUSE_RENDER") == "1"
frame_us = int(1e6 / (AVATAR_FPS if self.mouth > 0 else IDLE_FPS))
last = time.perf_counter()
while True:
if pause_render and self.mouth <= 0 and time.perf_counter() >= self.speaking_until:
await asyncio.sleep(0.25) # idle: no render, no encode work
continue
# posture state machine (docs/LATENCY.md): speaking > working > thinking > idle
if self.mouth > 0 or time.perf_counter() < self.speaking_until:
mode = "speaking"
elif self._tool_depth > 0:
mode = "working"
elif self.state == "thinking":
mode = "thinking"
else:
mode = "idle"
img = self.renderer.frame(self.mouth, mode)
if mode != getattr(self, "_last_posture", None):
self._last_posture = mode
self.log.append("persona.posture", mode=mode) # render-state timeline
try:
rgba = np.ascontiguousarray(np.asarray(img))
vf = rtc.VideoFrame(avatar_mod.SIZE, avatar_mod.SIZE,
rtc.VideoBufferType.RGBA, rgba.tobytes())
self.video_source.capture_frame(vf, timestamp_us=int(time.time() * 1e6))
except Exception as e: # a render/publish error must never kill video
self.log.append("avatar.render_error", error=str(e)[:150], mode=mode)
continue
now = time.perf_counter()
fps = AVATAR_FPS if time.perf_counter() < self.speaking_until or self.mouth > 0 else IDLE_FPS
await asyncio.sleep(max(0.0, 1.0 / fps - (now - last)))
last = time.perf_counter()
async def push_audio(self, pcm: np.ndarray, sr: int):
import livekit.rtc as rtc
chunk = int(sr * 0.01) # 10ms
for i in range(0, len(pcm), chunk):
piece = pcm[i : i + chunk]
frame = rtc.AudioFrame.create(sr, 1, len(piece))
np.copyto(np.frombuffer(frame.data, dtype=np.int16), piece)
await self.audio_source.capture_frame(frame)
async def speak(self, text: str, pre_segment=None, cancel: asyncio.Event | None = None,
**timing):
"""Pipelined sentence synthesis (docs/LATENCY.md #2): playback starts
while later sentences are still synthesizing. pre_segment is an
optional (pcm, sr) already synthesized at session start β€” the fixed
consent disclosure β€” so the first audible output pays no synth cost.
cancel: speculative-turn cancellation; checked before playout starts."""
import re
sentences = [s.strip() for s in re.split(r"(?<=[.!?])\s+", text) if s.strip()]
if not sentences:
sentences = [text]
# Clause-level chunking: the first audible chunk pays full synth cost
# (measured 7.47s for a 99-char first sentence), so cap chunk length at
# comma boundaries β€” later chunks pipeline behind playback anyway.
MAX_CHUNK = 60
chunks = []
for sent in sentences:
if len(sent) <= MAX_CHUNK:
chunks.append(sent)
continue
buf = ""
for part in re.split(r"(?<=[,;:])\s+", sent):
cand = f"{buf} {part}".strip()
if buf and len(cand) > MAX_CHUNK:
chunks.append(buf)
buf = part
else:
buf = cand
if buf:
chunks.append(buf)
sentences = chunks or [text]
t0 = timing["t0"]
first_audio = None
total_audio = 0.0
total_chars = 0
rest_q: asyncio.Queue = asyncio.Queue()
async def synth_rest():
try:
for s in sentences:
if cancel is not None and cancel.is_set():
raise asyncio.CancelledError() # stop paying synth cost early
p, r = await asyncio.to_thread(self.voice_backend.synthesize, s)
await rest_q.put((p, r, len(s)))
finally:
await rest_q.put(None) # always release the playback loop
rest_task = asyncio.create_task(synth_rest()) # synthesizes while we play
async def play_one(pcm_i, sr_i, chars):
nonlocal total_audio, total_chars, first_audio
mouth = avatar_mod.build_mouth_sequence(pcm_i, sr_i)
duration = len(pcm_i) / sr_i
total_audio += duration
total_chars += chars
self.speaking_until = time.perf_counter() + duration + 0.3
async def mouth_driver(seq=mouth):
for openness in seq:
self.mouth = float(openness)
await asyncio.sleep(1.0 / AVATAR_FPS)
self.mouth = 0.0
task = asyncio.create_task(mouth_driver())
if first_audio is None:
if cancel is not None and cancel.is_set():
# speech resumed during synthesis β€” cancel before playout
task.cancel()
raise asyncio.CancelledError()
await asyncio.sleep(PRE_ROLL_S) # avatar starts moving first
first_audio = time.perf_counter()
# absolute wall-clock, cross-process comparable with the harness
emit({"event": "timing", "session_id": self.session_id,
"abs_first_push": time.time()})
await self.push_audio(pcm_i, sr_i)
await task
if pre_segment is not None:
await play_one(pre_segment[0], pre_segment[1], 0)
while True:
item = await rest_q.get()
if item is None:
break
p, r, chars = item
await play_one(p, r, chars)
await rest_task
if first_audio is None:
raise RuntimeError("synthesis produced no audio")
self.log.append("tts.synthesized", text=text, chars=total_chars,
backend="piper", seconds=round(first_audio - t0, 3),
sentences=len(sentences), pre_cached=pre_segment is not None)
emit({"event": "timing", "session_id": self.session_id,
"tts_first_s": round(first_audio - t0, 3),
"spoken_chars": total_chars, "audio_s": round(total_audio, 3)})
# -- receive loop ----------------------------------------------------------
async def on_track(self, room, track, publication, participant):
import livekit.rtc as rtc
if track.kind != rtc.TrackKind.KIND_AUDIO:
return
stream = rtc.AudioStream(track, sample_rate=16000, num_channels=1)
async for ev in stream:
pcm = np.frombuffer(ev.frame.data, dtype=np.int16).astype(np.float32) / 32768.0
for kind, utt in self.segmenter.feed(pcm):
if kind == "final":
await self.handle_utterance(utt, speculative=False)
elif kind == "speculative":
self._start_speculative(utt)
elif kind == "resumed":
self._cancel_speculative(reason="speech_resumed")
# -- speculative dispatch (concept mitigation #1) ----------------------------
def _start_speculative(self, utt: np.ndarray):
if self._spec_task is not None and not self._spec_task.done():
return # a speculative turn is already running
cancel = asyncio.Event()
self._spec_cancel = cancel
self._spec_task = asyncio.create_task(self._speculative_turn(utt, cancel))
def _cancel_speculative(self, reason: str):
if self._spec_cancel is not None and not self._spec_cancel.is_set():
self._spec_cancel.set()
self.log.append("agent.speculative_canceled", reason=reason)
async def _speculative_turn(self, utt: np.ndarray, cancel: asyncio.Event):
"""Dispatch ASR+agent+first-chunk synth at ~300ms of silence, before
the utterance is final. If speech resumes before playout, cancel."""
try:
t0 = time.perf_counter()
self.set_state("thinking")
text, asr_s = await asyncio.to_thread(self.transcriber.transcribe, utt)
if cancel.is_set() or not text:
self.set_state("listening")
return
self.log.append("asr.speculative", text=text, seconds=round(asr_s, 3),
audio_s=round(len(utt) / 16000, 2))
reply = await asyncio.to_thread(self._agent_reply, text)
pre = None
if not self.first_utterance_done:
pre = self.disclosure_segment
self.first_utterance_done = True
self.log.append("agent.speak", text=reply)
self.set_state("speaking")
try:
await self.speak(reply, pre_segment=pre, cancel=cancel, t0=t0)
except asyncio.CancelledError:
self.log.append("agent.speculative_canceled",
reason="speech_resumed_before_playout")
self.set_state("listening")
return
except Exception as e: # noqa: BLE001
import traceback
self.log.append("session.error", error=str(e)[:200],
traceback=traceback.format_exc()[-600:])
self.set_state("listening")
return
# the speculative answer IS the answer; the "final" event for the
# same audio must not trigger a duplicate turn
self._handled_speculative = True
self.log.append("turn.completed", total_s=round(time.perf_counter() - t0, 3),
asr_s=round(asr_s, 3), speculative=True,
**self._throttle_delta())
self.set_state("listening")
finally:
self._spec_task = None
self._spec_cancel = None
def _agent_reply(self, text: str) -> str:
"""Agent reply + event-log the character's physical actions (never
spoken) and tool calls (always audited β€” docs/CONSENT.md Β§6). Runs in
a worker thread (LLM call); increments _tool_depth so the avatar
holds its 'working' posture while the toolbelt runs."""
self._tool_depth = getattr(self, "_tool_depth", 0) + 1
try:
reply = self.agent.reply(text)
finally:
self._tool_depth -= 1
for action in getattr(self.agent, "last_actions", []):
self.log.append("agent.action", text=action[:200])
for tc in getattr(self.agent, "last_tool_calls", []):
self.log.append("agent.tool", tool=tc["tool"],
args=json.dumps(tc["args"])[:200],
ok=tc["ok"], output=tc["output"][:300])
return reply
async def handle_utterance(self, utt: np.ndarray, speculative: bool = False):
if self._handled_speculative and not speculative:
# the speculative pipeline already answered this utterance
self._handled_speculative = False
return
task = self._spec_task
if task is not None and not task.done() and not speculative:
if self._spec_cancel is not None and self._spec_cancel.is_set():
# canceled mid-flight (speech resumed): drain it, then answer
# the extended utterance fresh
await task
else:
# speculative turn owns this utterance and will answer it
return
t_speech_end = time.perf_counter()
self.set_state("thinking")
text, asr_s = await asyncio.to_thread(self.transcriber.transcribe, utt)
t_asr = time.perf_counter()
if not text:
self.set_state("listening")
return
self.log.append("asr.final", text=text, seconds=round(asr_s, 3),
audio_s=round(len(utt) / 16000, 2))
reply = await asyncio.to_thread(self._agent_reply, text)
pre = None
if not self.first_utterance_done:
pre = self.disclosure_segment # cached consent line, zero synth cost
self.first_utterance_done = True
self.log.append("agent.speak", text=reply)
self.set_state("speaking")
try:
await self.speak(reply, pre_segment=pre, t0=t_speech_end)
except Exception as e: # noqa: BLE001 β€” surface as session error, keep bot alive
import traceback
self.log.append("session.error", error=str(e)[:200],
traceback=traceback.format_exc()[-600:])
self.set_state("listening")
return
total = time.perf_counter() - t_speech_end
self.log.append("turn.completed", total_s=round(total, 3),
asr_s=round(t_asr - t_speech_end, 3), speculative=False,
**self._throttle_delta())
self.set_state("listening")
self._spec_task = None
self._spec_cancel = None
# -- lifecycle ---------------------------------------------------------------
async def run(self):
import livekit.rtc as rtc
room = rtc.Room()
self.set_state("connecting")
await room.connect(self.url, self.token,
options=rtc.RoomOptions(auto_subscribe=True))
t_connected = time.perf_counter()
await self.publish_tracks(room)
# Warm identity assets before reporting ready, so the first turn
# doesn't pay whisper/piper model-load cost (docs/LATENCY.md #4).
try:
await asyncio.to_thread(self.transcriber._load)
await asyncio.to_thread(self.voice_backend.synthesize, "Warmup.")
# Pre-synthesize the fixed consent disclosure (CONSENT.md #2): it is
# static text, so the first turn's first audio never pays Piper's
# in-context synth latency (measured RTF ~1.2 in-process).
self.disclosure_segment = await asyncio.to_thread(
self.voice_backend.synthesize, self.agent.first_utterance())
except Exception as e: # noqa: BLE001
self.log.append("session.error", error=f"warmup failed: {e}")
self.set_state("error", error=str(e)[:200])
return
self.set_state("ready", video_published=True, room=self.room_name)
@room.on("track_subscribed")
def _on_track(track, publication, participant):
asyncio.ensure_future(self.on_track(room, track, publication, participant))
video_task = asyncio.create_task(self.video_loop())
stop = asyncio.Event()
loop = asyncio.get_event_loop()
for sig in (signal.SIGTERM, signal.SIGINT):
loop.add_signal_handler(sig, stop.set)
emit({"event": "timing", "session_id": self.session_id,
"join_s": round(time.perf_counter() - t_connected, 3)})
await stop.wait()
self.set_state("closed")
await room.disconnect()
video_task.cancel()
def main():
# Measured (ml-intern-freestream-debug-perf): piper's default ONNX session
# runs at RTF 0.33-0.65 while an OMP_NUM_THREADS=8 override degraded the
# bot to RTF ~1.5 β€” do not set OMP threads for onnxruntime here.
p = argparse.ArgumentParser(prog="freestream-bot")
p.add_argument("--url", required=True)
p.add_argument("--token", required=True)
p.add_argument("--room", required=True)
p.add_argument("--bot-name", required=True)
p.add_argument("--image", required=True)
p.add_argument("--voice", required=True)
p.add_argument("--session-id", required=True)
p.add_argument("--session-dir", required=True)
p.add_argument("--system-prompt", default=None)
args = p.parse_args()
session = BotSession(args.url, args.token, args.room, args.bot_name,
Path(args.image), args.voice, Path(args.session_dir),
args.session_id, args.system_prompt)
try:
asyncio.run(session.run())
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()