freestream / tests /e2e_roleplay.py
LoveLogicAI's picture
90s router window; None-guarded device check with audio-producing baseline
87241fb verified
Raw History Blame Contribute Delete
17.6 kB
"""Roleplay/agentic e2e: an LLM-backed character joins a LiveKit room and
holds an in-character spoken conversation.
Checks:
1. character stays in character across 3 spoken turns (transcript keywords)
2. AI disclosure present in the first utterance (CONSENT.md #2 — every policy)
3. *actions* are logged as agent.action events, not spoken
4. content-policy gate: safe vs mature system prompts differ as specified
5. CLI join/leave + replay logs verify
Latency is reported (LLM adds generation time); sanity gate at 12s, no 4s gate.
Env: FREESTREAM_AGENT=llm, FREESTREAM_LLM_API_KEY (or HF_TOKEN),
FREESTREAM_CONTENT_POLICY=mature (operator opt-in for this session).
"""
import asyncio
import json
import os
import socket
import subprocess
import sys
import tarfile
import time
import urllib.request
import wave
from pathlib import Path
import numpy as np
ROOT = Path("/tmp/rp")
REPO = "https://huggingface.co/datasets/LoveLogicAI/freestream/resolve/main"
VOICE_URL = ("https://huggingface.co/rhasspy/piper-voices/resolve/main/"
"en/en_US/amy/medium/en_US-amy-medium{ext}")
GH_LATEST = "https://api.github.com/repos/livekit/livekit-server/releases/latest"
os.environ["HF_HOME"] = "/tmp/hf"
os.environ["FREESTREAM_VOICE_DIR"] = str(ROOT / "voices")
os.environ["FREESTREAM_WHISPER_MODEL"] = "tiny.en"
os.environ["FREESTREAM_WHISPER_THREADS"] = "1"
os.environ["FREESTREAM_AGENT"] = "llm"
os.environ["FREESTREAM_CONTENT_POLICY"] = "mature" # operator opt-in (CONSENT.md §6)
os.environ["FREESTREAM_CHARACTER_CARD"] = "identity/characters/vera-steel.json"
os.environ["FREESTREAM_TOOLS"] = "fs,shell" # the tool turn needs a real shell (CONSENT.md §6 audit)
os.environ["FREESTREAM_WORKSPACE"] = str(ROOT / "workspace") # where the manifest is seeded
os.environ["FREESTREAM_TOOLS"] = "fs,shell" # operator grants the character a terminal
os.environ["FREESTREAM_WORKSPACE"] = str(ROOT / "workspace")
os.environ["PYTHONPATH"] = str(ROOT)
sys.path.insert(0, str(ROOT))
os.environ.setdefault("FREESTREAM_LIVEKIT_URL", "ws://localhost:7880")
os.environ.setdefault("FREESTREAM_LIVEKIT_KEY", "devkey")
os.environ.setdefault("FREESTREAM_LIVEKIT_SECRET", "secret")
results = []
def check(name, ok, detail=""):
results.append((name, ok))
print(f"{'PASS' if ok else 'FAIL'} {name}" + (f" — {detail}" if detail else ""), flush=True)
def fetch(url, dest):
dest.parent.mkdir(parents=True, exist_ok=True)
with urllib.request.urlopen(url, timeout=300) as r:
dest.write_bytes(r.read())
def run_cli(*args, timeout=240):
return subprocess.run([sys.executable, str(ROOT / "scripts/freestream.py"), *args],
cwd=str(ROOT), capture_output=True, text=True, timeout=timeout)
# ---- fetch code --------------------------------------------------------------
FILES = ["scripts/freestream.py",
"freestream/__init__.py", "freestream/events.py", "freestream/presence.py",
"freestream/persona.py", "freestream/bot.py", "freestream/asr.py",
"freestream/avatar.py", "freestream/agent.py",
"identity/characters/vera-steel.json"]
missing = []
for f in FILES:
try:
fetch(f"{REPO}/{f}", ROOT / f)
if (ROOT / f).stat().st_size == 0:
raise RuntimeError("empty")
except Exception as e:
missing.append((f, str(e)))
check("fetch code from Hub", not missing, str(missing[:2]))
if missing:
sys.exit(1)
# ---- policy gate verification (mechanical, no content generation) -------------
from freestream.agent import CharacterAgent, SAFE_POLICY, MATURE_POLICY # noqa: E402
os.environ["FREESTREAM_CONTENT_POLICY"] = "safe"
safe_sys = CharacterAgent(bot_name="x").system
os.environ["FREESTREAM_CONTENT_POLICY"] = "mature"
mature_sys = CharacterAgent(bot_name="x").system
os.environ["FREESTREAM_CONTENT_POLICY"] = "mature"
check("policy gate: safe prompt has sanitizer", "safe mode" in safe_sys
and "mature mode" not in safe_sys)
check("policy gate: mature prompt removes sanitizer", "mature mode" in mature_sys
and SAFE_POLICY.split("CONTENT POLICY")[1][:20] not in mature_sys)
first_line = CharacterAgent(bot_name="x").first_utterance()
check("policy gate: AI disclosure survives every policy", "AI assistant" in first_line)
# ---- seed the ship's workspace (the character's tool sandbox) ----------------
workspace = ROOT / "workspace"
workspace.mkdir(parents=True, exist_ok=True)
(workspace / "manifest.txt").write_text(
"LONG DAWN — CARGO MANIFEST, REV 7\n"
"1. cryo-seed vaults x12 (ArborGen charter) — bay 2\n"
"2. fusion torch liners x40 — bay 1\n"
"3. patient-nanite kits x900 (sealed) — bay 3\n"
"DESTINATION: Ceres Station, high dock. ETA 11 days at burn-0.3g.\n")
# ---- server -------------------------------------------------------------------
if not (ROOT / "livekit-server").exists():
req = urllib.request.Request(GH_LATEST, headers={"Accept": "application/vnd.github+json"})
with urllib.request.urlopen(req, timeout=60) as r:
release = json.loads(r.read())
asset = next(a for a in release["assets"]
if "linux_amd64" in a["name"] and a["name"].endswith(".tar.gz"))
fetch(asset["browser_download_url"], ROOT / asset["name"])
with tarfile.open(ROOT / asset["name"]) as tf:
tf.extract("livekit-server", str(ROOT))
config = ROOT / "lk.yaml"
config.write_text("""
port: 7880
rtc:
use_external_ip: false
use_ice_lite: true
tcp_port: 7881
port_range_start: 50000
port_range_end: 50100
keys:
devkey: secret
""")
server_log = open(ROOT / "server.log", "w")
server = subprocess.Popen([str(ROOT / "livekit-server"), "--config", str(config)],
stdout=server_log, stderr=subprocess.STDOUT)
for _ in range(60):
try:
with socket.create_connection(("127.0.0.1", 7880), timeout=1):
break
except OSError:
time.sleep(0.5)
check("livekit-server up on :7880", True)
for ext, name in ((".onnx", "en_US-amy-medium.onnx"), (".onnx.json", "en_US-amy-medium.onnx.json")):
dest = ROOT / "voices" / name
if not dest.exists():
fetch(VOICE_URL.format(ext=ext), dest)
r = run_cli("generate-avatar", "--output", "identity/videomeeting-avatar.png")
check("generate-avatar", r.returncode == 0)
from faster_whisper import WhisperModel # noqa: E402
WhisperModel("tiny.en", device="cpu", compute_type="int8", cpu_threads=1)
from livekit import api, rtc # noqa: E402
from piper import PiperVoice # noqa: E402
# ---- join via CLI ---------------------------------------------------------------
join_proc = subprocess.Popen(
[sys.executable, str(ROOT / "scripts/freestream.py"), "join",
"--meet-url", "https://livekit.local/long-dawn", "--platform", "livekit",
"--bot-name", "Vera", "--image", "identity/videomeeting-avatar.png",
"--timeout-sec", "120"],
cwd=str(ROOT), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
sid, ready = None, False
for line in join_proc.stdout:
try:
d = json.loads(line)
except ValueError:
continue
if "session_id" in d and sid is None:
sid = d["session_id"]
if d.get("status") == "ready":
ready = True
break
check(f"CLI join -> ready (session {sid})", ready)
if not ready:
print(join_proc.stderr.read()[:800])
sys.exit(1)
# ---- in-character conversation -------------------------------------------------
QUESTIONS = [
("Captain, who am I talking to?", ("vera", "steel", "captain")),
("What's our cargo, and where are we headed?",
("cargo", "ceres", "freight", "haul", "credits", "cryo", "vault", "liner",
"nanite", "seed", "destination")),
("Talk to me — what's the fastest route to Ceres?", ("ceres", "course", "day", "hour", "burn", "route")),
# tool turn: the answer must come from the REAL file via the character's terminal
("Run a scan of the manifest on the bridge console and tell me exactly what we're carrying.",
("cryo", "seed", "manifest", "grain")),
]
DISCLOSURE_KEYWORDS = ("ai", "automated")
async def conversation():
room = rtc.Room()
turns = []
video_state = {"bottom": []} # laptop-region luminance samples
audio_state = {"first": None, "last": None, "chunks": []}
video_state = {"bottom": [], "last_img": None} # device-luminance channel
@room.on("track_subscribed")
def on_track(track, publication, participant):
if track.kind == rtc.TrackKind.KIND_AUDIO:
asyncio.ensure_future(record_audio(track))
else:
asyncio.ensure_future(sample_video(track))
async def sample_video(track):
"""Track the laptop region's luminance (rows 400-500, cols 176-336):
the dark laptop sliding in during tool work drops this sharply.
Stream-level resilience: resubscribe on iterator death — a sampler
must never take down (or silently stop) the luminance channel."""
while True:
try:
stream = rtc.VideoStream(track)
async for ev in stream:
try:
f = ev.frame
w, h = f.width, f.height
data = bytes(f.data)
if h < 500 or w < 336:
continue
if len(data) >= w * h * 1.5 and len(data) < w * h * 4: # I420 luma
img = np.frombuffer(data[: w * h], dtype=np.uint8).reshape(h, w)
elif len(data) == w * h * 4: # RGBA luma approx
rgba = np.frombuffer(data, dtype=np.uint8).reshape(h, w, 4)
img = rgba[:, :, :3].mean(axis=2).astype(np.uint8)
else:
continue
region = img[400:500, 176:336]
video_state["bottom"].append(
(time.perf_counter(), float(region.mean())))
except Exception:
continue # per-frame: never fatal
except Exception:
await asyncio.sleep(0.5) # stream died: resubscribe and keep sampling
async def record_audio(track):
stream = rtc.AudioStream(track, sample_rate=16000, num_channels=1)
async for ev in stream:
pcm = np.frombuffer(ev.frame.data, dtype=np.int16)
rms = float(np.sqrt(np.mean(pcm.astype(np.float32) ** 2))) / 32768.0
if rms < 0.004:
continue
now = time.perf_counter()
if audio_state["first"] is None:
audio_state["first"] = now
audio_state["last"] = now
audio_state["chunks"].append(pcm)
await room.connect("ws://localhost:7880",
(api.AccessToken("devkey", "secret").with_identity("tester")
.with_grants(api.VideoGrants(room_join=True, room="long-dawn",
can_publish=True, can_subscribe=True))
.to_jwt()),
options=rtc.RoomOptions(auto_subscribe=True))
await asyncio.sleep(2.0)
voice = PiperVoice.load(str(ROOT / "voices/en_US-amy-medium.onnx"))
q_sr = int(json.loads((ROOT / "voices/en_US-amy-medium.onnx.json").read_text())
["audio"]["sample_rate"])
source = rtc.AudioSource(q_sr, 1)
track = rtc.LocalAudioTrack.create_audio_track("tester-mic", source)
await room.local_participant.publish_track(
track, rtc.TrackPublishOptions(source=rtc.TrackSource.SOURCE_MICROPHONE))
chunk = int(q_sr * 0.01)
verifier = WhisperModel("tiny.en", device="cpu", compute_type="int8", cpu_threads=1)
for i, (q_text, keywords) in enumerate(QUESTIONS, start=1):
q_pcm = np.concatenate([np.frombuffer(c.audio_int16_bytes, np.int16)
for c in voice.synthesize(q_text)])
audio_state["first"], audio_state["last"], audio_state["chunks"] = None, None, []
for j in range(0, len(q_pcm), chunk):
piece = q_pcm[j: j + chunk]
frame = rtc.AudioFrame.create(q_sr, 1, len(piece))
np.copyto(np.frombuffer(frame.data, dtype=np.int16), piece)
await source.capture_frame(frame)
t_speech_end = time.perf_counter()
t_speech_end_abs = time.time() # captured AT speech end, not at append
print(f"[client] turn {i}: '{q_text}' pushed (abs {t_speech_end_abs:.3f})", flush=True)
while audio_state["first"] is None:
await asyncio.sleep(0.05)
if time.perf_counter() - t_speech_end > 90: # router cold starts can be slow
break
if audio_state["first"] is None:
check(f"turn {i}: bot answered", False, "no audio in 90s")
turns.append(None)
continue
t_perceived = audio_state["first"] - t_speech_end
while time.perf_counter() - audio_state["last"] < 4.0:
await asyncio.sleep(0.1)
if time.perf_counter() - t_speech_end > 90:
break
bot_pcm = np.concatenate(audio_state["chunks"])
t_end_abs = time.time() # end of the answer (silence wait included)
segs, _ = verifier.transcribe(bot_pcm.astype(np.float32) / 32768.0, language="en")
text = " ".join(s.text.strip() for s in segs).strip()
ok = any(k in text.lower() for k in keywords)
check(f"turn {i}: in-character answer", ok, f"{t_perceived:.2f}s — {text[:130]}")
if i == 1:
check("turn 1: AI disclosure spoken first",
any(k in text.lower() for k in DISCLOSURE_KEYWORDS), text[:130])
turns.append({"t_perceived": t_perceived, "text": text,
"t_speech_end": t_speech_end,
"t_end": audio_state["last"],
"t_speech_end_abs": t_speech_end_abs,
"t_end_abs": t_end_abs})
await asyncio.sleep(0.5)
await room.disconnect()
return turns, video_state
turns, video_state = asyncio.run(conversation())
# ---- actions logged, not spoken -------------------------------------------------
from freestream.events import EventLog # noqa: E402
sdir = ROOT / ".freestream/sessions" / sid
bot_log = EventLog(sdir / "bot-events.jsonl").events()
actions = [e for e in bot_log if e["type"] == "agent.action"]
check("character *actions* logged as events", len(actions) >= 1,
"; ".join(a["payload"]["text"] for a in actions)[:160])
tools = [e for e in bot_log if e["type"] == "agent.tool"]
ok_tools = [e for e in tools if e["payload"].get("ok")]
check("character used the terminal (audited agent.tool call)", len(ok_tools) >= 1,
" | ".join(f"{e['payload']['tool']}:{str(e['payload'].get('args'))[:60]}"
for e in tools)[:200])
# device-work visible: EITHER on-camera laptop-region luminance drops ≥8 below
# the idle baseline during the tool turn, OR the bot's own render-state chain
# (persona.posture, epoch ts) shows the working posture held through the turn.
try:
# baseline: the first turn that actually produced audio (t_end not None)
t1 = next(t for t in turns if t and t.get("t_end") is not None)
t4 = turns[3]
def region_med(t):
vals = [m for ts, m in video_state["bottom"]
if t["t_speech_end"] <= ts <= (t["t_end"] or t["t_speech_end"]) + 1.0]
vals.sort()
return vals[len(vals) // 2] if vals else None
m1, m4 = region_med(t1), region_med(t4)
luma_ok = m1 is not None and m4 is not None and m4 < m1 - 8
working = [e for e in bot_log if e["type"] == "persona.posture"
and e["payload"].get("mode") == "working"
and t4["t_speech_end_abs"] - 1 <= e["ts"] <= t4["t_end_abs"] + 2]
# one continuous tool block logs exactly one working-posture entry
posture_ok = len(working) >= 1
check("avatar visibly works the device during tool call",
luma_ok or posture_ok,
f"luma idle {m1 and round(m1, 1)} -> tool {m4 and round(m4, 1)}; "
f"working-posture events in window: {len(working)}")
except Exception as e:
check("avatar visibly works the device during tool call", False, f"{e}")
# ---- leave + logs ----------------------------------------------------------------
r = run_cli("leave", "--session-id", sid)
out = {}
try:
out = json.loads(r.stdout.strip().splitlines()[-1])
except (ValueError, IndexError):
pass
check("CLI leave exits 0 with closed:true", r.returncode == 0 and out.get("closed") is True)
cli_ok, _ = EventLog(sdir / "events.jsonl").verify()
bot_ok, _ = EventLog(sdir / "bot-events.jsonl").verify()
check("both replay logs verify", cli_ok and bot_ok)
# ---- summary ---------------------------------------------------------------------
server.terminate()
print("\n--- roleplay latency (LLM in the loop; no 4s gate) ---", flush=True)
for i, t in enumerate(turns, start=1):
if t:
print(f"turn {i} t_perceived: {t['t_perceived']:.2f}s '{t['text'][:90]}'")
failed = [n for n, ok in results if not ok]
# roleplay profile: LLM generation + tool roundtrips dominate — 20s gate for
# normal turns, 30s for the tool turn (documented in the docstring)
slow = [f"turn {i}: {t['t_perceived']:.1f}s" for i, t in enumerate(turns, 1)
if t and t["t_perceived"] > (30.0 if i == len(turns) else 20.0)]
print(f"\n{len(results) - len(failed)}/{len(results)} checks passed")
if failed or slow:
print("FAILED: " + ", ".join(failed + (["turn > 12s"] if slow else [])))
sys.exit(1)
print("ROLEPLAY E2E OK")