how can i create an agent that gets the audio and ...
# ask-ai
m
how can i create an agent that gets the audio and need to do some processing which takes a bit of time?
t
Thanks for reaching out, James. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how to build an agent that receives audio and runs processing that can take some time. I can help — below is a concise, practical approach and an example pattern you can adapt. Which environment are you using (Python or TypeScript)? If you want code for one specifically, tell me which and I’ll provide a focused example. High-level approach 1. Subscribe to the participant audio track (use on_track_subscribed). 2. Wrap the track with
rtc.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
Copy code
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 Processing
m
What if I want the output to be the audio that I received + generated frame for the video?
t
You're asking how to output the received audio unchanged while also publishing generated video frames. I can help — below is a concise pattern and a question so I can give a concrete code sample. What to do (high-level) 1. Subscribe to the incoming audio track and either: ◦ Forward/publish the same audio track from the agent (so listeners hear the original audio), or ◦ Capture frames with
rtc.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 Docs
m
I have the following example, how should i update it for this purpose?
Copy code
import 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)
t
You're asking how to update your avatar example so the agent forwards the original audio unchanged while publishing generated video frames. Below is a concise, targeted change set and a runnable pattern you can drop into your existing code. Key changes 1. Do not replace or consume the remote audio track — subscribe and leave it published, or forward it back by publishing a new audio track if needed. In your avatar flow you're already launching an avatar participant; that avatar will hear the room audio if you set ATTRIBUTE_PUBLISH_ON_BEHALF so no extra forwarding is required for playback. 2. Create a
VideoSource
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:
Copy code
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:
Copy code
# 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:
Copy code
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?
m
I will betteer explain myself. Below is an example, that use openai to generate response, then the audio is taken to create an avatar which is a moving waveform. Instead of the waveform I want to put something else, however, it takes longer to create the frame than the wave generator. What is the correct way to do something like this?
Copy code
import 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)
Copy code
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))
t
Thanks — this is clear and helpful. You're asking how to replace the fast waveform generator with a slower frame-generation pipeline without blocking the avatar runner or dropping frames. Below are concise, practical options and a small, targeted code pattern you can drop into your existing VideoGenerator to handle long frame generation. Which option do you prefer? tell me if your generator is CPU-bound (e.g., image processing, ML inference) or I/O-bound (e.g., calling an external API) and I’ll provide the matching snippet. Recommended approaches (pick one) • Offload heavy frame generation to a background worker/executor and push completed frames into an async queue consumed by the VideoGenerator. This keeps the generator loop responsive and preserves timing. • Generate lower-fidelity placeholder frames (or progressive frames) immediately, then replace them when the heavy frame is ready by publishing an updated frame stream or toggling a composed canvas. • Batch or pipeline work: produce frames at your target fps using the last available result, while continuously scheduling new heavy generation tasks so you never block the frame loop. Minimal pattern to integrate into your AudioWaveGenerator 1) Add an async-safe output queue for completed video frames. 2) Submit heavy work to an executor or background task; when done, put the resulting frame into the queue. 3) In the generator loop, prefer frames from the output queue; if none available, render a fallback (idle/last frame) to maintain fps. Example changes (conceptual — adapt into your class) • add fields:
Copy code
self._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:
Copy code
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:
Copy code
# 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?
m
My generator is CPU\GPU bound using ml inference to create the next frame, do i need to do something differently?
t
Good — since your generator is CPU/GPU-bound (ML inference), use a non-blocking producer/consumer pattern: schedule inference off the avatar runner’s hot path, keep yielding frames at the target fps, and swap in heavy frames when they become available. Key changes to implement • Offload ML inference to a dedicated worker pool or separate process (not the generator loop). Use
run_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:
Copy code
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:
Copy code
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?
m
Isn't this solution will give bad lipsync? The audio is streaming, while each frame my take time to generate? Is there some runtime the generator must have to make it work?
t
You're right to worry about lip‑sync — slow ML inference can cause drift if frames are naively produced on the audio hot path. Here’s a concise plan that preserves sync and keeps the avatar responsive, plus concrete runtime guidance. Short answer • Do not block audio sending while waiting for heavy frames. Instead, have a dedicated avatar generator (process/service) receive the audio stream and publish synchronized audio+video itself. If you must generate frames in your runner, offload inference to a separate worker (process/GPU service) and use timestamps to align frames to audio when publishing. Recommended architectures (pick one) 1. Avatar generation server (preferred) ◦ Agent streams audio (real‑time) to a separate avatar server/process that owns generation. ◦ Avatar server performs ML inference, composes frames, and publishes both audio+video synchronized into the room. ◦ Pros: best lip‑sync, GPU usage isolated, easier cancellation and playback signaling. 1. Local runner + background inference workers ◦ Keep the runner producing audio immediately. ◦ Offload heavy frame generation to a ProcessPoolExecutor or separate inference service (GPU process/container). ◦ Runner publishes video frames produced by the worker; runner keeps emitting fallback/last frames to maintain FPS until heavy frames arrive. ◦ Use timestamps/request IDs so completed frames are placed at the right logical audio position. Implementation pattern (if you keep generation in your code) • Producer/consumer: ◦ Input: audio chunks with timestamps. ◦ Submit inference tasks only when out_queue not full (throttle). ◦ Worker returns (frame, timestamp, request_id) into an async out queue. ◦ Generator loop (ticked at video_fps) chooses: ▪︎ If there’s a frame whose timestamp matches current playback time → publish it. ▪︎ Else → publish fallback (last completed frame or a lightweight visualization) to avoid dropped frames. • Never await inference on the generator hot path; always run blocking ML in a separate process or service (avoid Python GIL / contention). • Small queue sizes (1–4) and max inflight tasks to avoid memory/GPU overload. Synchronization details • Timestamp audio chunks when they are emitted; carry that metadata through to the inference request and resulting frames. • If tight sync is required, match the video frame’s presentation timestamp to the audio timestamp before publishing. • If exact alignment isn’t possible, use the last-completed frame for several ticks; user perception is usually acceptable if initial latency is low. Runtime recommendations • Use GPU-backed inference (separate process or container) for real-time avatar models. • Keep end-to-first-frame latency low (<200–300ms ideally). • Use ProcessPoolExecutor or a dedicated inference service rather than ThreadPoolExecutor if using native Python ML frameworks. • Batch requests if the model supports it and latency/throughput tradeoffs permit. Handling interruptions & UX • Allow cancellation: when speech is interrupted, cancel pending in-flight generation jobs and switch to listening/idle animation frames. • Send playback-complete or cancel RPCs between agent and avatar generator so state remains consistent. Quick mapping to your code • Replace synchronous _generate_frame ML work with: ◦ submit to a process executor or remote inference endpoint ◦ push results (frame + timestamp) into _out_queue ◦ in _video_generation_impl yield frames every tick: prefer queued frames that match the current audio position, else fallback to fast waveform or last frame • Limit inflight jobs and queue size; drop/replace oldest frames when overloaded. If you want, I can: • Provide a concrete patch for your AudioWaveGenerator that uses ProcessPoolExecutor + timestamped requests and a small out queue. • Or sketch the avatar server flow (audio ByteStream → inference → publish synchronized tracks) if you prefer that architecture. Which would you like: a patch for your generator, or a reference implementation of a separate avatar generation server? Sources: Bringing AI avatars to voice agents | Virtual avatar plugins | LiveKit Docs
m
give implementation of separate avatar server
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!
m
you asked me "Which would you like: a patch for your generator, or a reference implementation of a separate avatar generation server?" I prefer the separate avatar option
?