Can we use realtime models in livekit with screen ...
# ask-ai
c
Can we use realtime models in livekit with screen sharing use case, I need to add image frames in chatcontext as we do in normal flow of tts + llm + stt flow. And will the realtime voice to voice model supporting the image be able to get that
t
Thanks for reaching out, Divyanshu. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm happy to share that LiveKit does support real-time models with screen sharing! This means you can easily add image frames to your chat context and use TTS + LLM + STT flows seamlessly. You have the flexibility to integrate real-time AI models for rich multimodal interactions, including bidirectional audio and video streaming. Screen sharing is fully supported, and you can capture video frames—whether from live video or screen sharing—and include them in the chat context using the
ImageContent
object. This supports base64-encoded data URLs, external URLs, or direct video frame objects from tracks. LiveKit is designed to work with both traditional STT-LLM-TTS pipelines and real-time models. These real-time models handle speech input and output directly, with integrated STT and TTS, or you can pair them with external TTS providers if you want a more customized speech experience. For instance, you can capture the latest video frame during speech detection and add it to the LLM context for enhanced multimodal reasoning. This is beautifully demonstrated in the Vision Agent example, which processes live video from a user’s camera or screen sharing, combines it with STT transcriptions, and responds using TTS. If you’d like more details or need a hand with implementation, please don’t hesitate to reach out—I’m here to help! Sources: Realtime model plugins | LiveKit Docs | Real-time AI Models & Streaming | livekit/livekit_composite | DeepWiki | docs/index.yaml | Vision | LiveKit Docs | livekit-agents/livekit/agents/voice/agent.py
c
can you help me on how to do this in my code, or even give a sample screen sharing agent which uses google realtime voice to voice model, and also takes screen frames ::: ---- class VisionAgent(DynamicVoiceAgent): """Vision-enabled agent with dynamic configuration and video stream handling.""" def __init__(self, **kwargs) -> None: self._latest_frame = None self._video_stream = None self._tasks = [] self._turn_counter = 0 self._session_folder = None self._conversation_history = [] # Track conversation manually self._max_context_messages = 10 # Keep last 10 messages (5 turns) super().__init__(**kwargs) def set_session_folder(self, folder_path: str) -> None: """Set the session folder for logging chat history.""" self._session_folder = folder_path async def on_enter(self): room = get_job_context().room # Find the first video track (if any) from the remote participant if room.remote_participants: remote_participant = next(iter(room.remote_participants.values())) video_tracks = [ publication.track for publication in list(remote_participant.track_publications.values()) if publication.track and publication.track.kind == rtc.TrackKind.KIND_VIDEO ] if video_tracks: self._create_video_stream(video_tracks[0]) # Watch for new video tracks being published @room.on("track_subscribed") def on_track_subscribed( track: rtc.Track, publication: rtc.RemoteTrackPublication, participant: rtc.RemoteParticipant, ): if track.kind == rtc.TrackKind.KIND_VIDEO: logger.info(f"📹 New video track subscribed: {track.sid}") self._create_video_stream(track) # Watch for video tracks being unpublished (e.g., camera turned off) @room.on("track_unsubscribed") def on_track_unsubscribed( track: rtc.Track, publication: rtc.RemoteTrackPublication, participant: rtc.RemoteParticipant, ): if track.kind == rtc.TrackKind.KIND_VIDEO: logger.info(f"📹 Video track unsubscribed: {track.sid}") # Clear the latest frame when video source is removed self._latest_frame = None if self._video_stream is not None: close_task = asyncio.create_task(self._video_stream.aclose()) self._tasks.append(close_task) self._video_stream = None async def on_user_turn_completed( self, turn_ctx: ChatContext, new_message: ChatMessage ) -> None: has_frame = self._latest_frame is not None # Add the latest video frame, if any, to the new message if self._latest_frame: new_message.content.append(ImageContent(image=self._latest_frame)) self._latest_frame = None ----- # Helper method to buffer the latest video frame from the user's track def _create_video_stream(self, track: rtc.Track): # Close any existing stream (we only want one at a time) if self._video_stream is not None: logger.info("🔄 Closing existing video stream to switch to new track") close_task = asyncio.create_task(self._video_stream.aclose()) self._tasks.append(close_task) self._video_stream = None # Create a new stream to receive frames logger.info(f"🎥 Creating new video stream for track: {track.sid}") self._video_stream = rtc.VideoStream(track) async def read_stream(): try: async for event in self._video_stream: # Store the latest frame for use later self._latest_frame = event.frame except Exception as e: logger.warning(f"⚠️ Video stream ended or error: {e}") self._latest_frame = None # Store the async task task = asyncio.create_task(read_stream()) task.add_done_callback( lambda t: self._tasks.remove(t) if t in self._tasks else None ) self._tasks.append(task) --- agent = VisionAgent( instructions=VISION_AGENT_PROMPT_WITH_MINDTICKLE_DEMO, llm=google.beta.realtime.RealtimeModel(), ) # Store room reference for end_call function agent.set_room(ctx.room) session_first_message_time = 0 # Start session with transcript logging session = AgentSession()
t
I'm happy to guide you through implementing a screen sharing agent in LiveKit using Google’s real-time voice-to-voice model along with capturing screen frames. Let’s walk through it step-by-step: Backend Agent Implementation Here’s a Python example for the backend to get you started:
Copy code
import logging
from livekit.agents import (
    Agent, AgentSession, JobContext, RoomInputOptions, RoomOutputOptions, WorkerOptions, cli, voice,
)
from livekit.plugins import google, silero

logger = logging.getLogger("screen-share-agent")

async def entrypoint(ctx: JobContext):
    session = AgentSession(
        vad=silero.VAD.load(),
        llm=google.realtime.RealtimeModel(
            model="gemini-2.0-flash-live-001",
            voice="Puck",
            temperature=0.8,
            instructions="You are an AI assistant that interacts with users via voice and can see their screen."
        ),
    )

    agent = Agent(
        instructions="You are an AI assistant that can see and discuss what users show on their screen through screen sharing."
    )

    await session.start(
        agent=agent,
        room=ctx.room,
        room_input_options=RoomInputOptions(video_enabled=True),
        room_output_options=RoomOutputOptions(transcription_enabled=True),
    )

    await session.generate_reply(
        instructions="Greet the user and ask what they’d like help with on their screen."
    )

if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
Frontend Implementation For the web (React), you’ll want to enable screen sharing in
app-config.ts
like this:
Copy code
export const APP_CONFIG_DEFAULTS: AppConfig = {
  supportsVideoInput: true,
  supportsScreenShare: true,
}
And for Android, you can use
MediaProjectionManager
to manage screen capture permissions and enable screen sharing smoothly. Video Frame Processing To optimize performance, video frames are sampled based on voice activity: • 1 frame per second while speaking • 0.3 frames per second when silent Frames are JPEG-encoded with a max resolution of 1024×1024 pixels. If you want to customize this, here’s how you can adjust it:
Copy code
session = AgentSession(
    vad=silero.VAD.load(),
    llm=google.realtime.RealtimeModel(),
    video_sampler=voice.VoiceActivityVideoSampler(
        speaking_fps=2.0,
        silent_fps=0.5,
    ),
)
Authentication Don’t forget to set these environment variables to keep things running smoothly:
Copy code
LIVEKIT_URL=your-livekit-instance-url
LIVEKIT_API_KEY=your-api-key
LIVEKIT_API_SECRET=your-api-secret
GOOGLE_API_KEY=your-google-api-key
Reference Implementations • Vision Demo: An iOS app showcasing screen sharing and Gemini integration • Agent Starter React: A web app with screen share support • Android Voice Assistant: Android implementation featuring screen sharing If you have any questions or need me to clarify any part, please don’t hesitate to ask. I’m here to help you every step of the way! Sources: Gemini Live API plugin | LiveKit docs | livekit-plugins/livekit-plugins-google/livekit/plugins/google/realtime/real... | Gemini Live API plugin | LiveKit docs | README.md | app/src/main/java/io/livekit/android/example/voiceassistant/screen/VoiceAss...