most-match-32106
12/03/2025, 12:45 PMtall-airline-16756
12/03/2025, 12:45 PMtall-airline-16756
12/03/2025, 12:45 PMrtc.AudioStream to receive AudioFrame objects.
3. Buffer frames until you have the amount you need (e.g., N seconds), or stream them to a queue for batch processing.
4. Combine frames into a single audio blob (WAV/PCM) and call your processing function or external service.
5. If processing must not be interrupted, disable interruptions inside the tool (run_ctx.disallow_interruptions()).
6. While processing, give the user feedback (e.g., session.generate_reply() or an RPC to the client) so they know work is in progress.
7. For long or heavy work, offload to a background worker or external service and return an interim acknowledgement.
Minimal Python example pattern
• Detect audio track subscription
• Collect ~7s of frames
• Combine into WAV bytes
• Send to async processor
from livekit import rtc
from livekit.agents import AudioStream, combine_audio_frames
async def on_track_subscribed(track: rtc.Track, *_):
if track.kind != rtc.TrackKind.KIND_AUDIO:
return
stream = rtc.AudioStream(track)
buffer = []
start_ts = None
async for frame in stream:
if start_ts is None:
start_ts = frame.timestamp
buffer.append(frame)
# stop after ~7 seconds
if (frame.timestamp - start_ts) >= 7_000:
break
combined = combine_audio_frames(buffer)
wav_bytes = combined.to_wav_bytes()
# If processing should not be interrupted:
# run_ctx.disallow_interruptions()
result = await process_audio(wav_bytes) # your async processing
await session.generate_reply(f"Processing complete: {result}")
Notes & best practices
• Use buffering or a queue if you need continuous capture + asynchronous processing.
• For realtime lower-latency needs, process smaller windows and stream partial results.
• Offload heavy ML or external API work to background workers to keep the agent responsive.
• Use disallow_interruptions() when the tool must finish without being preempted.
• For full-session recordings, use RecorderIO instead of AudioStream.
Tell me which language you prefer (Python or TypeScript), how long processing typically takes, and whether you need streaming partial results — I’ll give you a tailored code sample and integration notes.
Sources: Tool definition and use | LiveKit docs | Capturing the First Few Seconds of a Call for Processingmost-match-32106
12/03/2025, 1:19 PMtall-airline-16756
12/03/2025, 1:19 PMrtc.AudioStream, buffer/combine only for processing while also continuing to forward the original track.
1. Create a video source (e.g., VideoSource / LocalVideoTrack) and publish it from the agent's local participant.
2. In a loop generate frames (images) and push them to the VideoSource at your target framerate.
3. If you need tight A/V sync, use the AV synchronizer utility or timestamp frames to align with audio.
4. For long audio processing, offload heavy work to background tasks and keep the published audio/video tracks active; optionally send interim UI feedback with RPC or session.generate_reply().
Minimal pattern (conceptual)
• Keep the remote audio track published/forwarded so audio remains unchanged.
• Publish a separate generated video track from the agent.
• Optionally process buffered audio for analysis without replacing the live audio stream.
Quick question so I can give runnable code: do you want the example in Python or TypeScript, and do you need the generated video to be synchronized to specific audio timestamps (tight sync) or just loosely aligned?
Sources: Camera & microphone | LiveKit docs | Bringing AI avatars to voice agents | Vision | LiveKit Docsmost-match-32106
12/03/2025, 1:22 PMimport argparse
import logging
import sys
from dataclasses import asdict, dataclass
from functools import partial
import httpx
from dotenv import load_dotenv
from livekit import api, rtc
from livekit.agents import Agent, AgentServer, AgentSession, JobContext, cli
from livekit.agents.voice.avatar import DataStreamAudioOutput
from livekit.agents.voice.io import PlaybackFinishedEvent
from livekit.agents.voice.room_io import ATTRIBUTE_PUBLISH_ON_BEHALF
from livekit.plugins import openai
load_dotenv()
logger = logging.getLogger("avatar-example")
logger.setLevel(logging.INFO)
server = AgentServer()
AVATAR_IDENTITY = "avatar_worker"
@dataclass
class AvatarConnectionInfo:
room_name: str
url: str
"""LiveKit server URL"""
token: str
"""Token for avatar worker to join"""
async def launch_avatar(ctx: JobContext, avatar_dispatcher_url: str, avatar_identity: str) -> None:
"""
Send a request to the avatar service for it to join the room
This function should be wrapped in a avatar plugin.
"""
# create a token for the avatar to join the room
token = (
api.AccessToken()
.with_identity(avatar_identity)
.with_name("Avatar Runner")
.with_grants(api.VideoGrants(room_join=True, room=ctx.room.name))
.with_kind("agent")
.with_attributes({ATTRIBUTE_PUBLISH_ON_BEHALF: ctx.local_participant_identity})
.to_jwt()
)
logger.info(f"Sending connection info to avatar dispatcher {avatar_dispatcher_url}")
connection_info = AvatarConnectionInfo(room_name=ctx.room.name, url=ctx._info.url, token=token)
async with httpx.AsyncClient() as client:
response = await client.post(avatar_dispatcher_url, json=asdict(connection_info))
response.raise_for_status()
logger.info("Avatar handshake completed")
async def entrypoint(ctx: JobContext, avatar_dispatcher_url: str):
await ctx.connect()
agent = Agent(instructions="Talk to me!")
session = AgentSession(
llm=openai.realtime.RealtimeModel(),
# stt=deepgram.STT(),
# llm=openai.LLM(model="gpt-4o-mini"),
# tts=cartesia.TTS(),
resume_false_interruption=False,
)
await launch_avatar(ctx, avatar_dispatcher_url, AVATAR_IDENTITY)
session.output.audio = DataStreamAudioOutput(
ctx.room,
destination_identity=AVATAR_IDENTITY,
# (optional) wait for the avatar to publish video track before generating a reply
wait_remote_track=rtc.TrackKind.KIND_VIDEO,
)
# start agent with room input and room text output
await session.start(
agent=agent,
room=ctx.room,
)
@session.output.audio.on("playback_finished")
def on_playback_finished(ev: PlaybackFinishedEvent) -> None:
# the avatar should notify when the audio playback is finished
logger.info(
"playback_finished",
extra={
"playback_position": ev.playback_position,
"interrupted": ev.interrupted,
},
)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--avatar-url", type=str, default="http://localhost:8089/launch")
args, remaining_args = parser.parse_known_args()
sys.argv = sys.argv[:1] + remaining_args
server.rtc_session(partial(entrypoint, avatar_dispatcher_url=args.avatar_url))
cli.run_app(server)tall-airline-16756
12/03/2025, 1:22 PMVideoSource and LocalVideoTrack, publish that track from the agent's local participant, and push generated frames into the VideoSource.
3. If you want A/V sync, optionally timestamp frames or use AVSynchronizer utilities.
4. Keep your DataStreamAudioOutput for generating audio replies (if used) but do not silence or remove the incoming audio.
Minimal code additions Add these imports near the top:
from livekit import rtc
from livekit.agents.video import VideoSource, LocalVideoTrack # adjust import path if needed
import asyncio
import numpy as np # for simple frame generation example
Inside your entrypoint after await launch_avatar(...) and before await session.start(...), create and publish the generated video track:
# create a generated video source and publish it from this agent
video_source = VideoSource(width=640, height=480)
video_track = LocalVideoTrack.create_video_track("generated-video", video_source)
await ctx.room.local_participant.publish_track(video_track)
Add a background task to generate frames and push them to the source (example 10 FPS with a moving color bar). Start it before session.start so video is available to the avatar:
async def generate_frames_loop():
x = 0
while True:
# create a simple RGB frame (height, width, 3)
frame = (np.zeros((480, 640, 3), dtype=np.uint8))
frame[:, x:x+50] = [0, 255, 0] # green bar
# convert to the expected frame object if required by VideoSource API
video_source.capture_frame(frame)
x = (x + 5) % 640
await asyncio.sleep(0.1) # ~10 FPS
# start generator in background
asyncio.create_task(generate_frames_loop())
Notes about audio handling
• If the avatar participant (launched by launch_avatar) is joining the room with ATTRIBUTE_PUBLISH_ON_BEHALF set, the avatar will publish on behalf of your agent identity; the remote audio stays active for listeners. Do not call methods that remove or mute the incoming audio track if you want the original audio preserved.
• If you need to process audio (for analysis) while leaving playback intact, use AudioStream to read frames non-destructively and buffer/process them in the background; do not unpublish the original track.
Optional: Tight A/V sync
• If you need tight synchronization to audio timestamps, use the AVSynchronizer helper (or timestamp frames) so generated frames align to audio frame timing.
Where to insert
• Place the video creation and generator task right after await launch_avatar(...) and before await session.start(...) so the avatar sees the video when it joins.
• Keep session.output.audio = DataStreamAudioOutput(...) as-is if you want the agent to play synthesized audio to the avatar in addition to the original live audio.
If you want, I can:
• Provide a TypeScript equivalent.
• Replace the simple numpy frame generator with an example that uses Pillow, OpenCV, or ffmpeg frames.
• Show how to read remote audio non-destructively with rtc.AudioStream and run analysis in a separate background worker.
Which would you like next?most-match-32106
12/03/2025, 1:25 PMimport argparse
import logging
import sys
from dataclasses import asdict, dataclass
from functools import partial
import httpx
from dotenv import load_dotenv
from livekit import api, rtc
from livekit.agents import Agent, AgentServer, AgentSession, JobContext, cli
from livekit.agents.voice.avatar import DataStreamAudioOutput
from livekit.agents.voice.io import PlaybackFinishedEvent
from livekit.agents.voice.room_io import ATTRIBUTE_PUBLISH_ON_BEHALF
from livekit.plugins import openai
load_dotenv()
logger = logging.getLogger("avatar-example")
logger.setLevel(logging.INFO)
server = AgentServer()
AVATAR_IDENTITY = "avatar_worker"
@dataclass
class AvatarConnectionInfo:
room_name: str
url: str
"""LiveKit server URL"""
token: str
"""Token for avatar worker to join"""
async def launch_avatar(ctx: JobContext, avatar_dispatcher_url: str, avatar_identity: str) -> None:
"""
Send a request to the avatar service for it to join the room
This function should be wrapped in a avatar plugin.
"""
# create a token for the avatar to join the room
token = (
api.AccessToken()
.with_identity(avatar_identity)
.with_name("Avatar Runner")
.with_grants(api.VideoGrants(room_join=True, room=ctx.room.name))
.with_kind("agent")
.with_attributes({ATTRIBUTE_PUBLISH_ON_BEHALF: ctx.local_participant_identity})
.to_jwt()
)
logger.info(f"Sending connection info to avatar dispatcher {avatar_dispatcher_url}")
connection_info = AvatarConnectionInfo(room_name=ctx.room.name, url=ctx._info.url, token=token)
async with httpx.AsyncClient() as client:
response = await client.post(avatar_dispatcher_url, json=asdict(connection_info))
response.raise_for_status()
logger.info("Avatar handshake completed")
async def entrypoint(ctx: JobContext, avatar_dispatcher_url: str):
await ctx.connect()
agent = Agent(instructions="Talk to me!")
session = AgentSession(
llm=openai.realtime.RealtimeModel(),
# stt=deepgram.STT(),
# llm=openai.LLM(model="gpt-4o-mini"),
# tts=cartesia.TTS(),
resume_false_interruption=False,
)
await launch_avatar(ctx, avatar_dispatcher_url, AVATAR_IDENTITY)
session.output.audio = DataStreamAudioOutput(
ctx.room,
destination_identity=AVATAR_IDENTITY,
# (optional) wait for the avatar to publish video track before generating a reply
wait_remote_track=rtc.TrackKind.KIND_VIDEO,
)
# start agent with room input and room text output
await session.start(
agent=agent,
room=ctx.room,
)
@session.output.audio.on("playback_finished")
def on_playback_finished(ev: PlaybackFinishedEvent) -> None:
# the avatar should notify when the audio playback is finished
logger.info(
"playback_finished",
extra={
"playback_position": ev.playback_position,
"interrupted": ev.interrupted,
},
)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--avatar-url", type=str, default="http://localhost:8089/launch")
args, remaining_args = parser.parse_known_args()
sys.argv = sys.argv[:1] + remaining_args
server.rtc_session(partial(entrypoint, avatar_dispatcher_url=args.avatar_url))
cli.run_app(server)
import asyncio
import logging
import sys
import time
from collections import deque
from collections.abc import AsyncGenerator, AsyncIterator
from pathlib import Path
from typing import Optional, Union
import numpy as np
from livekit import rtc
from livekit.agents import utils
from livekit.agents.types import TOPIC_TRANSCRIPTION
from livekit.agents.voice.avatar import (
AudioSegmentEnd,
AvatarOptions,
AvatarRunner,
DataStreamAudioReceiver,
VideoGenerator,
)
sys.path.insert(0, str(Path(__file__).parent))
from wave_viz import WaveformVisualizer
logger = logging.getLogger("avatar-example")
class AudioWaveGenerator(VideoGenerator):
def __init__(self, options: AvatarOptions):
self._options = options
self._audio_queue = asyncio.Queue[Union[rtc.AudioFrame, AudioSegmentEnd]]()
self._audio_resampler: Optional[rtc.AudioResampler] = None
self._canvas = np.zeros((options.video_height, options.video_width, 4), dtype=np.uint8)
self._canvas.fill(255)
self._wave_visualizer = WaveformVisualizer(sample_rate=options.audio_sample_rate)
# use AudioByteStream to chunk the audio frames to expected frame size
self._audio_bstream = utils.audio.AudioByteStream(
sample_rate=options.audio_sample_rate,
num_channels=options.audio_channels,
samples_per_channel=options.audio_sample_rate // options.video_fps,
)
self._frame_ts: deque[float] = deque(maxlen=options.video_fps)
# -- VideoGenerator abstract methods --
async def push_audio(self, frame: rtc.AudioFrame | AudioSegmentEnd) -> None:
"""Called by the runner to push audio frames to the generator."""
await self._audio_queue.put(frame)
def clear_buffer(self) -> None:
"""Called by the runner to clear the audio buffer"""
while not self._audio_queue.empty():
try:
self._audio_queue.get_nowait()
except asyncio.QueueEmpty:
break
self._audio_bstream.flush()
def __aiter__(
self,
) -> AsyncIterator[rtc.VideoFrame | rtc.AudioFrame | AudioSegmentEnd]:
"""
Generate a continuous stream of video and audio frames.
Notes:
- When the audio buffer is empty, idle (silent) video frames are produced.
- Frame streaming speed is automatically paced to match the `video_fps` option.
- When an `AudioSegmentEnd` is encountered, it is yielded to notify the runner
that playback of the current audio segment is complete.
"""
return self._video_generation_impl()
# -- End of VideoGenerator abstract methods --
async def _video_generation_impl(
self,
) -> AsyncGenerator[rtc.VideoFrame | rtc.AudioFrame | AudioSegmentEnd, None]:
while True:
try:
# timeout has to be shorter than the frame interval to avoid starvation
frame = await asyncio.wait_for(
self._audio_queue.get(), timeout=0.5 / self._options.video_fps
)
self._audio_queue.task_done()
except asyncio.TimeoutError:
# generate frame without audio (e.g. silence state)
yield self._generate_frame(None)
self._frame_ts.append(time.time())
continue
audio_frames: list[rtc.AudioFrame] = []
if isinstance(frame, rtc.AudioFrame):
# resample audio if needed
if not self._audio_resampler and (
frame.sample_rate != self._options.audio_sample_rate
or frame.num_channels != self._options.audio_channels
):
self._audio_resampler = rtc.AudioResampler(
input_rate=frame.sample_rate,
output_rate=self._options.audio_sample_rate,
num_channels=self._options.audio_channels,
)
if self._audio_resampler:
for f in self._audio_resampler.push(frame):
audio_frames += self._audio_bstream.push(f.data)
else:
audio_frames += self._audio_bstream.push(frame.data)
else:
if self._audio_resampler:
for f in self._audio_resampler.flush():
audio_frames += self._audio_bstream.push(f.data)
audio_frames += self._audio_bstream.flush()
# generate video frames
for audio_frame in audio_frames:
video_frame = self._generate_frame(audio_frame)
yield video_frame
yield audio_frame
self._frame_ts.append(time.time())
# send the AudioSegmentEnd back to notify the playback finished
if isinstance(frame, AudioSegmentEnd):
yield AudioSegmentEnd()
def _generate_frame(self, audio_frame: rtc.AudioFrame | None) -> rtc.VideoFrame:
canvas = self._canvas.copy()
if audio_frame is None:
# idle frame, no audio
audio_data = np.zeros((1, self._options.audio_channels))
else:
audio_data = np.frombuffer(audio_frame.data, dtype=np.int16).reshape(
-1, audio_frame.num_channels
)
self._wave_visualizer.draw(canvas, audio_samples=audio_data, fps=self._get_fps())
video_frame = rtc.VideoFrame(
width=canvas.shape[1],
height=canvas.shape[0],
type=rtc.VideoBufferType.RGBA,
data=canvas.tobytes(),
)
return video_frame
def _get_fps(self) -> float | None:
if len(self._frame_ts) < 2:
return None
return (len(self._frame_ts) - 1) / (self._frame_ts[-1] - self._frame_ts[0])
@utils.log_exceptions(logger=logger)
async def main(api_url: str, api_token: str):
# connect to the room
room = rtc.Room()
await room.connect(api_url, api_token)
def on_transcription_received(reader: rtc.TextStreamReader, participant_identity: str):
# ignore transcription from the room
pass
room.register_text_stream_handler(TOPIC_TRANSCRIPTION, on_transcription_received)
should_stop = asyncio.Event()
# stop when disconnect from the room or the agent disconnects
@room.on("participant_disconnected")
def _on_participant_disconnected(participant: rtc.RemoteParticipant):
if participant.kind == rtc.ParticipantKind.PARTICIPANT_KIND_AGENT:
logging.info(f"Agent {participant.identity} disconnected, stopping worker")
should_stop.set()
@room.on("disconnected")
def _on_disconnected():
logging.info("Room disconnected, stopping worker")
should_stop.set()
# define the avatar options and start the runner
avatar_options = AvatarOptions(
video_width=1280,
video_height=720,
video_fps=30,
audio_sample_rate=24000,
audio_channels=1,
)
video_gen = AudioWaveGenerator(avatar_options)
runner = AvatarRunner(
room, audio_recv=DataStreamAudioReceiver(room), video_gen=video_gen, options=avatar_options
)
try:
await runner.start()
# run until stopped or the runner is complete/failed
tasks = [
asyncio.create_task(runner.wait_for_complete()),
asyncio.create_task(should_stop.wait()),
]
await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
finally:
await utils.aio.cancel_and_wait(*tasks)
await runner.aclose()
await room.disconnect()
logger.info("avatar runner stopped")
if __name__ == "__main__":
import os
from livekit.agents.cli.log import setup_logging
setup_logging("DEBUG", devmode=True, console=True)
livekit_url = os.getenv("LIVEKIT_URL")
livekit_token = os.getenv("LIVEKIT_TOKEN")
assert livekit_url and livekit_token, "LIVEKIT_URL and LIVEKIT_TOKEN must be set"
asyncio.run(main(livekit_url, livekit_token))tall-airline-16756
12/03/2025, 1:25 PMself._out_queue: asyncio.Queue[rct.VideoFrame] = asyncio.Queue(maxsize=4)
self._last_frame: Optional[rtc.VideoFrame] = None
self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=2)
• create a helper that runs heavy work in background:
async def _schedule_heavy(self, audio_chunk_bytes):
loop = asyncio.get_running_loop()
# run blocking CPU-bound or sync API call in threadpool
frame = await loop.run_in_executor(self._executor, blocking_frame_generator, audio_chunk_bytes)
await self._out_queue.put(frame)
• in your audio->video pipeline (where you now call _generate_frame(audio_frame)), instead:
# when you have an audio_frame to visualize:
audio_bytes = audio_frame.data
# start background generation (do not await)
asyncio.create_task(self._schedule_heavy(audio_bytes))
# try to get a ready heavy frame, otherwise fallback to wave or last_frame
try:
video_frame = self._out_queue.get_nowait()
self._last_frame = video_frame
except asyncio.QueueEmpty:
# produce fast fallback (waveform or composed canvas) to keep fps
video_frame = self._generate_fast_fallback(audio_frame)
# keep last_frame so you can reuse it if generator stalls
• ensure pacing: keep yielding frames at video_fps intervals (your existing timeout loop does this).
Notes and best practices
• Use a small output queue (1–4) to avoid memory growth; drop or overwrite oldest frames if queue is full.
• For CPU-bound ML inference, use a dedicated process or GPU-backed service; call it via async I/O or an executor.
• For I/O-bound external APIs, await the call but keep it off the hot path; schedule it in background and use placeholders until ready.
• If frames must not be skipped and you need tight A/V sync, timestamp requests and place finished frames into their correct time slot; otherwise, accept slight drift and always keep producing frames.
• Callers of your VideoGenerator expect a continuous stream — do not block the iterator; always yield a frame each tick.
If you want, I can:
• Produce a concrete patch for your AudioWaveGenerator replacing _generate_frame with this background pattern.
• Provide a blocking blocking_frame_generator example for an image model or an external API call.
Which would you like?most-match-32106
12/03/2025, 1:30 PMtall-airline-16756
12/03/2025, 1:30 PMrun_in_executor for CPU-bound or a separate inference process/service for GPU to avoid Python GIL and resource contention.
• Use a small async output queue (1–4) for completed frames. The generator consumes from this queue each tick.
• Render a fast fallback frame each tick if no heavy frame is ready (e.g., last completed frame, low‑cost visualization, or progressive build).
• Throttle submissions: only schedule inference for new audio chunks when the queue isn’t full to avoid piling up work.
• Preserve pacing: keep yielding one frame per tick (use existing fps timing). Never await inference on the hot path.
Concrete pattern (what to add)
1. Add fields to your generator:
self._out_q = asyncio.Queue(maxsize=2)
self._inflight = 0
self._executor = concurrent.futures.ProcessPoolExecutor(max_workers=1) # or ThreadPoolExecutor for async C libs
self._last_frame = None
1. Background scheduler for each new audio chunk:
async def _schedule_inference(self, audio_bytes):
loop = asyncio.get_running_loop()
# blocking_infer is a sync function that runs the ML model and returns an rtc.VideoFrame
frame = await loop.run_in_executor(self._executor, blocking_infer, audio_bytes)
try:
await self._out_q.put(frame)
except asyncio.CancelledError:
pass
finally:
self._inflight -= 1
1. In your generation loop, replace direct heavy generation with:
• If audio chunk -> if self._inflight < MAX_INFLIGHT and not self._out_q.full(): launch asyncio.create_task(self._schedule_inference(audio_bytes)); self._inflight += 1
• Try non-blocking get from `self._out_q`:
◦ If available: use it and set self._last_frame = frame
◦ Else: produce fast fallback via _generate_fast_fallback(audio_frame) or reuse self._last_frame
• Yield the chosen frame and then the associated audio_frame
1. Resource considerations
• Use a ProcessPoolExecutor or run inference in a separate service/container to allow GPU usage and avoid blocking the agent process.
• Set max inflight workers to match model throughput/latency and GPU memory limits.
• Prefer batching if model supports it: accumulate small audio inputs and infer in batches to improve GPU utilization.
1. Sync/timestamps
• If you need tight A/V sync, timestamp audio chunks, attach request IDs, and when a heavy frame completes, insert it at the appropriate logical time (or use it for subsequent frames). For most avatars, using the last completed frame and keeping steady fps is sufficient.
Would you like a concrete patch to your AudioWaveGenerator implementing this pattern (with ProcessPoolExecutor and a sample blocking_infer stub)? Which inference setup do you use (PyTorch/onnx/tensorflow) and do you run on GPU in the same host or a separate service?most-match-32106
12/03/2025, 1:32 PMtall-airline-16756
12/03/2025, 1:33 PMmost-match-32106
12/03/2025, 1:35 PMtall-airline-16756
12/03/2025, 1:36 PMmost-match-32106
12/03/2025, 1:36 PMmost-match-32106
12/03/2025, 1:41 PM