fast-jordan-16209
09/01/2025, 11:15 AMtall-airline-16756
09/01/2025, 11:15 AMtall-airline-16756
09/01/2025, 11:16 AMlocal_participant from a Room before you've actually connected to it. To fix this, just make sure you connect first using await room.connect(url, token) and wait until the connection is all set before you work with local_participant.
Here’s a friendly example to guide you:
room = Room()
# Set up event listeners before connecting
@room.on("participant_connected")
def on_participant_connected(participant):
print(f"Participant connected: {participant.identity}")
# Connect to the room first
await room.connect("ws://localhost:7880", "your_token")
# Now it's safe to access local_participant
await room.local_participant.publish_data("Hello Room", reliable=True)
Just swap out "ws://localhost:7880" and "your_token" with your actual server URL and token. If you hit any snags or have more questions, I’m here to help!
Sources: README.md | livekit-rtc/livekit/rtc/room.py | Connecting to LiveKit | LiveKit Docsfast-jordan-16209
09/01/2025, 12:02 PMtall-airline-16756
09/01/2025, 12:02 PMlocal_participant? That way, I can take a closer look and see if there’s anything off with the order of operations or the connection itself.
Also, just to double-check, are you sure the connection to the room is fully established before you try to access local_participant? If you have any logs or messages showing the connection status, feel free to share those too—they’ll really help us figure this out together.fast-jordan-16209
09/01/2025, 12:04 PMclass BaseAgent(Agent):
async def on_enter(self):
agent_name = self.__class__.__name__
logger.info(f"Agent {agent_name} entered")
userdata: AgentData = self.session.userdata
room = userdata.ctx.room
room.connect(LIVEKIT_URL,LIVEKIT_API_KEY)
if userdata.ctx and userdata.ctx.room:
await userdata.ctx.room.local_participant.set_attributes({"agent": agent_name})
chat_ctx = self.chat_ctx.copy()
if userdata.prev_agent:
items_copy = self._truncate_chat_ctx(
userdata.prev_agent.chat_ctx.items, keep_function_call=True
)
existing_ids = {item.id for item in chat_ctx.items}
items_copy = [item for item in items_copy if item.id not in existing_ids]
chat_ctx.items.extend(items_copy)
logger.info(f"input: {userdata.user_input}")
chat_ctx.add_message(
role="system",
content=f"You are the {agent_name}. And you task is {userdata.user_input}"
)
await self.update_chat_ctx(chat_ctx)
self.session.generate_reply()
def _truncate_chat_ctx(
self,
items: list,
keep_last_n_messages: int = 6,
keep_system_message: bool = False,
keep_function_call: bool = False,
) -> list:
"""Truncate the chat context to keep the last n messages."""
def _valid_item(item) -> bool:
if not keep_system_message and item.type == "message" and item.role == "system":
return False
if not keep_function_call and item.type in ["function_call", "function_call_output"]:
return False
return True
new_items = []
for item in reversed(items):
if _valid_item(item):
new_items.append(item)
if len(new_items) >= keep_last_n_messages:
break
new_items = new_items[::-1]
while new_items and new_items[0].type in ["function_call", "function_call_output"]:
new_items.pop(0)
return new_items
async def _transfer_to_agent(self, name: str, *, user_input: str, context: RunContext_T) -> Agent:
userdata = context.userdata
current_agent = context.session.current_agent
next_agent = userdata.personas[name]
userdata.prev_agent = current_agent
userdata.user_input = user_input
return next_agentfast-jordan-16209
09/01/2025, 12:05 PMtall-airline-16756
09/01/2025, 12:05 PMlocal_participant property is being accessed before the room has fully connected. In your code, the room.connect(LIVEKIT_URL, LIVEKIT_API_KEY) call isn’t awaited, so the connection isn’t finished before you try to use local_participant.
No worries though—just make sure to use await with the connect method. Here’s the updated snippet to help you out:
async def on_enter(self):
agent_name = self.__class__.__name__
logger.info(f"Agent {agent_name} entered")
userdata: AgentData = self.session.userdata
room = userdata.ctx.room
# Await the connection to ensure it completes
await room.connect(LIVEKIT_URL, LIVEKIT_API_KEY)
if userdata.ctx and userdata.ctx.room:
await userdata.ctx.room.local_participant.set_attributes({"agent": agent_name})
chat_ctx = self.chat_ctx.copy()
if userdata.prev_agent:
items_copy = self._truncate_chat_ctx(
userdata.prev_agent.chat_ctx.items, keep_function_call=True
)
existing_ids = {item.id for item in chat_ctx.items}
items_copy = [item for item in items_copy if item.id not in existing_ids]
chat_ctx.items.extend(items_copy)
logger.info(f"input: {userdata.user_input}")
chat_ctx.add_message(
role="system",
content=f"You are the {agent_name}. And your task is {userdata.user_input}"
)
await self.update_chat_ctx(chat_ctx)
self.session.generate_reply()
Just a quick reminder to swap out LIVEKIT_URL and LIVEKIT_API_KEY with your actual server URL and API key. Give this a try, and if you hit any snags or want me to walk through anything else, just let me know—I’m here to help!fast-jordan-16209
09/01/2025, 12:07 PMtall-airline-16756
09/01/2025, 12:07 PMLIVEKIT_URL and LIVEKIT_API_KEY tucked away in a .env file, just double-check that you’re loading them properly before using them in your code. Here’s a quick example using the dotenv library to help you out:
from dotenv import load_dotenv\nimport os\n\n# Load environment variables from .env file\nload_dotenv()\n\n# Access the variables\nLIVEKIT_URL = os.getenv("LIVEKIT_URL")\nLIVEKIT_API_KEY = os.getenv("LIVEKIT_API_KEY")\n\n# Make sure they’re actually set\nif not LIVEKIT_URL or not LIVEKIT_API_KEY:\n raise ValueError("LIVEKIT_URL or LIVEKIT_API_KEY is not set in the .env file")
Just be sure to run this code before you try connecting to the room. Feel free to reach out if this helps or if you hit any other snags—I’m here to help!fast-jordan-16209
09/01/2025, 12:09 PMtall-airline-16756
09/01/2025, 12:10 PMengine: signal failure: failed to retrieve region info: error decoding response body: expected value at line 1 column 1 usually means there’s something off with the server URL or the response from your LiveKit server. This might happen if:
• Your LIVEKIT_URL is incorrect or not pointing to a valid LiveKit server.
• The server isn’t reachable or is sending back an unexpected response.
• There’s a network hiccup stopping communication with the server.
Here’s how you can try to fix it:
1. Take a moment to double-check your LIVEKIT_URL and make sure it’s correct and pointing to your LiveKit server (something like `ws://your-livekit-server:7880`).
2. Make sure your LiveKit server is up and running and that you can reach it. You can try opening the URL in a browser or use a tool like curl to test.
3. Check if there are any network blocks, like firewalls, that might be stopping access to the server.
4. Peek at the server logs for any errors or clues about why the response might be coming back invalid.
If you’re still stuck after trying these, just let me know—I’m here to help!fast-jordan-16209
09/01/2025, 12:14 PMtall-airline-16756
09/01/2025, 12:15 PMwss://test-hgbg7ypd.livekit.cloud looks like it’s in the right format for a secure WebSocket connection to a LiveKit cloud-hosted server. To make sure everything’s good to go, here are a few things you can check:
1. Double-check that the server is up and running. You can try opening the URL in a browser or use a handy tool like curl to test it out.
2. Make sure the server is set up to accept connections and that nothing like firewalls or network policies is blocking it.
3. Confirm that the URL matches exactly what’s in your LiveKit cloud project or deployment settings.
If you’ve checked all this and things still aren’t working, just give me a shout—I’m here to help you figure it out!
Sources: README.md | docs/interfaces/LiveKitRoomProps.html | examples/nextjs/.env.example | packages/rpc-demo/.env.localfast-jordan-16209
09/01/2025, 12:18 PMtall-airline-16756
09/01/2025, 12:18 PMcurl output shows that the server is responding with an HTTP 200 status, which is great because it means the server is reachable. However, the response content type is text/plain and the body just says OK, which usually means the server isn't quite handling WebSocket upgrade requests the way it should.
Here are a few things you can try to fix this:
1. Double-check that your LiveKit server is set up correctly to handle WebSocket connections. Make sure the WebSocket endpoint is ready and waiting for connections.
2. Take a peek at the server logs to see if there are any errors or misconfigurations that might explain why the WebSocket upgrade isn't going through.
3. Confirm that your LIVEKIT_URL is pointing to the right WebSocket endpoint. For example, it should look like wss://test-hgbg7ypd.livekit.cloud without a trailing slash.
4. If you're using a reverse proxy like Nginx or AWS ALB, make sure it's set up to properly forward WebSocket upgrade requests.
Feel free to reach out if you want a hand with any of these steps or if something’s still unclear!fast-jordan-16209
09/01/2025, 12:22 PMtall-airline-16756
09/01/2025, 12:23 PMcurl request you can use to test your LiveKit server’s WebSocket endpoint:
curl -i -N \
-H "Connection: Upgrade" \
-H "Upgrade: websocket" \
-H "Host: test-hgbg7ypd.livekit.cloud" \
-H "Origin: https://test-hgbg7ypd.livekit.cloud" \
-H "Sec-WebSocket-Key: SGVsbG9MaXZlS2l0" \
-H "Sec-WebSocket-Version: 13" \
wss://test-hgbg7ypd.livekit.cloud
Just a quick heads-up: if your WebSocket URL is different, be sure to swap out wss://test-hgbg7ypd.livekit.cloud with the right one. This request will try to open a WebSocket connection with your server, and if everything’s set up correctly, you’ll see a successful handshake response.
Feel free to share what you get back or reach out if anything feels off—I’m here to help!fast-jordan-16209
09/01/2025, 12:25 PMtall-airline-16756
09/01/2025, 12:25 PMRefused WebSockets upgrade: 200 usually means the server is sending back an HTTP 200 status instead of switching over to a WebSocket connection. This often happens when the server isn’t set up quite right to handle WebSocket connections.
Here’s how you can fix it:
1. Make sure your LiveKit server is up and running, and that it’s set to accept WebSocket connections on the right port.
2. Double-check that your LIVEKIT_URL is correct and doesn’t have a trailing slash (for example, wss://test-hgbg7ypd.livekit.cloud).
3. If you’re using a reverse proxy like Nginx or AWS ALB, make sure it’s set up to forward those WebSocket upgrade requests properly. For Nginx, that means including headers like Upgrade and Connection in your proxy config.
4. Take a peek at the server logs to see if there are any errors or warnings that might explain why the WebSocket upgrade is getting refused.
If you’re still stuck after trying these steps, just let me know—I’m here to help dig into it with you!fast-jordan-16209
09/01/2025, 12:56 PMtall-airline-16756
09/01/2025, 12:57 PMkeepalive ping timeout; no close frame received basically means the WebSocket connection got closed because it timed out. This usually happens when the server doesn’t respond to those ping messages in time, so the client ends up closing the connection.
Here’s how you can try to fix it:
1. Make sure your LiveKit server is up and running smoothly, with enough resources to handle WebSocket connections.
2. Take a look at your server’s WebSocket timeout settings. If the timeout is set too low, try increasing it so there’s more time for those pings to get a response.
3. Double-check your network for any hiccups like high latency or packet loss that might be causing trouble between the client and server.
4. If you’re using a reverse proxy like Nginx or AWS ALB, confirm it’s set up correctly to support WebSocket connections and isn’t cutting off connections too soon with its own timeouts.
5. Peek at the server logs to see if there are any errors or warnings that could explain why those ping messages aren’t being acknowledged.
If you run into any issues or want a hand going through these, just let me know—I’m here to help!fast-jordan-16209
09/02/2025, 6:49 PMtall-airline-16756
09/02/2025, 6:50 PMpyautogui or something similar.
Could you let me know if you're aiming to control apps inside a browser (like Spotify Web Player) or directly on your desktop? That way, I can point you in the right direction and help you out better!
Sources: LiveKit Docs | livekit/livekit_composite | DeepWiki | Agents Overview | LiveKit Docsfast-jordan-16209
09/03/2025, 1:25 PMtall-airline-16756
09/03/2025, 1:26 PMllama.cpp project).
2. Setting up an AI agent to interpret and run code during a session by creating a custom tool with the LiveKit Agents framework.
Could you help me understand a bit more about what you’re aiming for?
• Are you looking to run Python code locally in a browser or client-side environment?
• Or do you want an AI agent to interpret and execute code during a session?
Knowing this will help me point you in the right direction. I’m here to help!
Sources: OpenAI LLM integration guide | LiveKit Docs | livekit-agents/README.md | OpenAI and LiveKit partner to turn Advanced Voice into an API | .env.example | tools/server/webui/src/components/CanvasPyInterpreter.tsxfast-jordan-16209
09/03/2025, 1:35 PMtall-airline-16756
09/03/2025, 1:35 PMpyautogui can take care of the actual mouse movements and clicks on your desktop.
Here’s a simple overview to get you started:
1. Set up LiveKit for voice commands: Use LiveKit Agents to process voice input and turn it into clear commands. For example, if someone says "Click the search bar," the agent understands and acts on that.
2. Integrate a desktop automation library: Use something like pyautogui (Python) or similar tools to control your mouse and keyboard. For example:
import pyautogui
# Move the mouse to a specific position
pyautogui.moveTo(100, 200)
# Click the mouse
pyautogui.click()
# Type text
pyautogui.write("Hello World")
3. Connect the two systems: When a voice command comes in, the LiveKit agent sends the interpreted command to a local script running your automation library. This can happen via WebSocket, HTTP API, or other ways to communicate.
4. Handle application-specific logic: If you’re working with specific software (like Spotify), you might need to identify UI elements or use extra tools like OCR (Optical Character Recognition) to find buttons and fields dynamically.
Would you like me to walk you through setting up LiveKit for voice commands or help with integrating it with a particular desktop automation library? Just let me know—I’m here to help!fast-jordan-16209
09/03/2025, 2:29 PMtall-airline-16756
09/03/2025, 2:30 PMgetDisplayMedia API to share your screen:
const stream = await navigator.mediaDevices.getDisplayMedia({ video: true });
const screenTrack = new LocalVideoTrack(stream.getVideoTracks()[0]);
room.localParticipant.publishTrack(screenTrack);
2. Join a Room: Make sure your LiveKit agent is connected to the same room where the screen sharing is happening. Then, the agent can subscribe to the screen-sharing track and see your screen live.
3. Process the Screen Feed: If your agent needs to analyze what’s on the screen (like for object detection or OCR), you can use a video processing library to handle the video frames in real-time.
If you’d like, I’m here to help with more detailed steps for a specific setup—whether that’s in a browser, desktop, or mobile environment—or if you want to connect it with an AI agent for extra processing. Just let me know!fast-jordan-16209
09/03/2025, 2:42 PMimport asyncio
import logging
import os
from typing import Optional
import deepgram
import openai
from livekit import agents, rtc
from livekit.agents import WorkerOptions, cli, codecs, transcribe, llm
from livekit.agents.llm import ChatContext, ChatImage, ChatMessage
from livekit.agents.voice_assistant import VoicePipelineAgent
from livekit.plugins import deepgram as dg, openai as openai_plugin
logger = logging.getLogger(__name__)
class AssistantFunction(agents.llm.FunctionContext):
@agents.llm.ai_callable(desc="Called when asked to manipulate the room in any way")
async def manipulate_room(
self,
user_msg: Optional[str] = None,
):
logger.info(f"manipulate room: {user_msg}")
async def get_screen_share_track(room: rtc.Room):
"""Find and return the first remote screen share video track in the room."""
for participant_id, participant in room.remote_participants.items():
for track_id, track_publication in participant.track_publications.items():
if (
track_publication.track
and isinstance(track_publication.track, rtc.RemoteVideoTrack)
and track_publication.source == rtc.TrackSource.SCREEN_SHARE
):
logger.info(
f"Found screen share track {track_publication.track.sid} "
f"from participant {participant_id}"
)
return track_publication.track
logger.warning("No screen share track found")
return None
async def get_latest_frame(room: rtc.Room) -> Optional[rtc.VideoFrame]:
"""Capture and return a single frame from the screen share track."""
video_stream = None
try:
video_track = await get_screen_share_track(room)
if not video_track:
return None
video_stream = rtc.VideoStream(video_track)
async for event in video_stream:
logger.debug("Captured latest video frame")
return event.frame
except Exception as e:
logger.error(f"Failed to get latest frame: {e}")
return None
finally:
if video_stream:
await video_stream.aclose()
async def before_llm_cb(ctx: agents.JobContext, llm: llm.BaseLLM) -> ChatContext:
"""Callback to inject the latest screen frame into the LLM context before response."""
chat_ctx = ctx.proc.userdata["initial_ctx"]
latest_frame = await get_latest_frame(ctx.room)
if latest_frame:
image_content = ChatImage(image=latest_frame)
chat_ctx = chat_ctx.append(
message=ChatMessage(role="user", content=[image_content])
)
logger.debug("Added latest screen frame to LLM context")
return chat_ctx
async def entrypoint(ctx: agents.JobContext):
await ctx.connect(auto_subscribe=agents.AutoSubscribe.SUBSCRIBE_ALL)
initial_ctx = llm.ChatContext().append(
role="system",
text=(
"You are a voice assistant created by LiveKit that can see the user's screen in real-time. "
"Use short and concise responses, avoiding unpronounceable punctuation. "
"When you see a screen frame in the conversation, naturally incorporate what you see "
"into your response. Keep visual descriptions brief but informative. "
"If no screen is shared, respond normally without mentioning vision."
),
)
ctx.proc.userdata["initial_ctx"] = initial_ctx
fnc_ctx = AssistantFunction(base_llm=openai.LLM(model="gpt-4o-mini"))
stt = dg.STT()
tts = openai_plugin.TTS(voice="alloy")
llm_model = openai.LLM(model="gpt-4o-mini")
assistant = VoicePipelineAgent(
vad=agents.transcribe.VAD(),
stt=stt,
llm=llm_model,
tts=tts,
chat_ctx=initial_ctx,
fnc_ctx=fnc_ctx,
before_llm=before_llm_cb,
)
assistant.start(ctx.room, participant="*")
logger.info("Agent is ready")
await asyncio.sleep(3)
await assistant.say("Hey, how can I help?", allow_interruptions=True)
if __name__ == "__main__":
cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
is this code is right for my task?tall-airline-16756
09/03/2025, 2:42 PMget_screen_share_track function does a great job of finding and pulling the screen-sharing track from the room. Just double-check that everyone in the room is actually sharing their screens using the right LiveKit SDK methods.
2. Frame Capture: The get_latest_frame function grabs frames from that screen-sharing track, which is super important for giving your agent real-time visual context.
3. LLM Integration: The before_llm_cb callback smartly adds the latest screen frame into the LLM context, so your agent can “see” what’s happening on the screen when it responds. That’s a solid way to bring visuals into the mix.
4. Voice Assistant: The VoicePipelineAgent is set up with STT, TTS, and LLM components, so it’s ready to handle voice commands and reply smoothly.
To make sure everything runs smoothly:
• Check that your LiveKit server is up and running, and that it’s reachable.
• Confirm that participants are sharing their screens with the correct LiveKit SDK methods.
• Try out the agent in a controlled setting to see if it’s capturing and processing screen frames in real-time as expected.
If you hit any snags or want a hand with anything else, just give me a shout—I’m here to help!fast-jordan-16209
09/04/2025, 4:51 AMtall-airline-16756
09/04/2025, 4:52 AMChatImage isn’t actually part of the LiveKit Agents framework. Instead, you’ll want to use ImageContent, which does the same job of handling images in chat messages.
To fix this, just update your import statement like this:
from livekit.agents.llm import ChatMessage, ImageContent
After that, swap out any place where you used ChatImage with ImageContent. For example:
image_content = ImageContent(image=event.frame)
This should clear up the import error. If you run into any other hiccups, feel free to reach out—I’m here to help!
Sources: Vision Agent Quickstart | LiveKit Docs | livekit-agents/livekit/agents/llm/_provider_format/aws.pyfast-jordan-16209
09/04/2025, 4:53 AMtall-airline-16756
09/04/2025, 4:54 AMlivekit.agents.voice_assistant isn’t actually part of the LiveKit Agents framework. Instead, you’ll want to use livekit.agents.voice.
To get this sorted, just update your import statement like this:
from livekit.agents.voice import Agent, AgentSession
If you’re following an example or tutorial that mentions voice_assistant, it might be a bit outdated or off. Feel free to reach out if you want a hand tweaking your code—I’m here to help!
Sources: livekit-agents/livekit/agents/__init__.py | AI Agents Framework | livekit/livekit_composite | DeepWiki | Voice Assistants | livekit/livekit_composite | DeepWiki | Voice Assistants | livekit/livekit_composite | DeepWiki | templates.yamlfast-jordan-16209
09/04/2025, 4:55 AMasync def entrypoint(ctx: agents.JobContext):
await ctx.connect(auto_subscribe=agents.AutoSubscribe.SUBSCRIBE_ALL)
initial_ctx = llm.ChatContext().append(
role="system",
text=(
"You are a voice assistant created by LiveKit that can see the user's screen in real-time. "
"Use short and concise responses, avoiding unpronounceable punctuation. "
"When you see a screen frame in the conversation, naturally incorporate what you see "
"into your response. Keep visual descriptions brief but informative. "
"If no screen is shared, respond normally without mentioning vision."
),
)
ctx.proc.userdata["initial_ctx"] = initial_ctx
fnc_ctx = AssistantFunction(base_llm=openai.LLM(model="gpt-4o-mini"))
assistant = VoicePipelineAgent(
llm=google.beta.realtime.RealtimeModel(voice="Charon"),
chat_ctx=initial_ctx,
fnc_ctx=fnc_ctx,
before_llm=before_llm_cb,
)
assistant.start(ctx.room, participant="*")
logger.info("Agent is ready")
await asyncio.sleep(3)
await assistant.say("Hey, how can I help?", allow_interruptions=True)
fix this entrypoint functiontall-airline-16756
09/04/2025, 4:56 AMentrypoint function that should work smoothly:
async def entrypoint(ctx: agents.JobContext):\n await ctx.connect(auto_subscribe=agents.AutoSubscribe.SUBSCRIBE_ALL)\n\n # Initialize the chat context\n initial_ctx = llm.ChatContext().append(\n role=\"system\",\n text=(\n \"You are a voice assistant created by LiveKit that can see the user's screen in real-time. \"\n \"Use short and concise responses, avoiding unpronounceable punctuation. \"\n \"When you see a screen frame in the conversation, naturally incorporate what you see \"\n \"into your response. Keep visual descriptions brief but informative. \"\n \"If no screen is shared, respond normally without mentioning vision.\"\n ),\n )\n ctx.proc.userdata[\"initial_ctx\"] = initial_ctx\n\n # Initialize the function context\n fnc_ctx = AssistantFunction(base_llm=openai.LLM(model=\"gpt-4o-mini\"))\n\n # Correct the assistant initialization\n assistant = VoicePipelineAgent(\n llm=openai.LLM(model=\"gpt-4o-mini\"),\n chat_ctx=initial_ctx,\n fnc_ctx=fnc_ctx,\n before_llm=before_llm_cb,\n )\n\n # Start the assistant\n assistant.start(ctx.room, participant=\"*\")\n\n logger.info(\"Agent is ready\")\n\n # Greet the user\n await asyncio.sleep(3)\n await assistant.say(\"Hey, how can I help?\", allow_interruptions=True)
A couple of key fixes to point out:
• Switched google.beta.realtime.RealtimeModel to openai.LLM so everything stays consistent.
• Made sure the VoicePipelineAgent is initialized properly with the right LLM model and contexts.
If you run into any other hiccups or have questions, just let me know—I’m here to help!fast-jordan-16209
09/04/2025, 4:58 AMtall-airline-16756
09/04/2025, 4:59 AMpip install "livekit-agents[openai]~=1.2"
2. Or, if you prefer, install the plugin as a standalone package:
pip install livekit-plugins-openai
Once you've done that, the import from livekit.plugins import openai should work like a charm. If you run into any other hiccups, just give me a shout—I’m here to help!
Sources: LiveKit Agents integrations | LiveKit Docs | OpenAI LLM integration guide | LiveKit Docs | livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/log.pyfast-jordan-16209
09/04/2025, 5:01 AMtall-airline-16756
09/04/2025, 5:01 AMpip install --upgrade livekit-plugins-openai
3. Import Path Issue: It’s worth double-checking your import statement. It should look like this:
from livekit.plugins import openai
4. Environment Conflicts: If you’re using a virtual environment, make sure it’s activated before running your script. Here’s how:
source .venv/bin/activate.venv\Scripts\activate
If you try these and it’s still giving you trouble, just give me a shout—we’ll figure it out together!fast-jordan-16209
09/04/2025, 5:03 AMimport asyncio
import logging
import os
from typing import Optional
import openai
from livekit import agents, rtc
from livekit.agents import WorkerOptions, cli, llm
from livekit.agents.llm import ChatContext, ImageContent, ChatMessage
from livekit.agents.voice import Agent, AgentSession
from livekit.plugins import openai , google
logger = logging.getLogger(__name__)
class AssistantFunction(agents.llm.FunctionContext):
@agents.llm.ai_callable(desc="Called when asked to manipulate the room in any way")
async def manipulate_room(
self,
user_msg: Optional[str] = None,
):
logger.info(f"manipulate room: {user_msg}")
async def get_screen_share_track(room: rtc.Room):
"""Find and return the first remote screen share video track in the room."""
for participant_id, participant in room.remote_participants.items():
for track_id, track_publication in participant.track_publications.items():
if (
track_publication.track
and isinstance(track_publication.track, rtc.RemoteVideoTrack)
and track_publication.source == rtc.TrackSource.SCREEN_SHARE
):
logger.info(
f"Found screen share track {track_publication.track.sid} "
f"from participant {participant_id}"
)
return track_publication.track
logger.warning("No screen share track found")
return None
async def get_latest_frame(room: rtc.Room) -> Optional[rtc.VideoFrame]:
"""Capture and return a single frame from the screen share track."""
video_stream = None
try:
video_track = await get_screen_share_track(room)
if not video_track:
return None
video_stream = rtc.VideoStream(video_track)
async for event in video_stream:
logger.debug("Captured latest video frame")
return event.frame
except Exception as e:
logger.error(f"Failed to get latest frame: {e}")
return None
finally:
if video_stream:
await video_stream.aclose()
async def before_llm_cb(ctx: agents.JobContext, llm: llm.BaseLLM) -> ChatContext:
"""Callback to inject the latest screen frame into the LLM context before response."""
chat_ctx = ctx.proc.userdata["initial_ctx"]
latest_frame = await get_latest_frame(ctx.room)
if latest_frame:
image_content = ImageContent(image=latest_frame)
chat_ctx = chat_ctx.append(
message=ChatMessage(role="user", content=[image_content])
)
logger.debug("Added latest screen frame to LLM context")
return chat_ctx
async def entrypoint(ctx: agents.JobContext):
await ctx.connect(auto_subscribe=agents.AutoSubscribe.SUBSCRIBE_ALL)
# Initialize the chat context
initial_ctx = llm.ChatContext().append(
role="system",
text=(
"You are a voice assistant created by LiveKit that can see the user's screen in real-time. "
"Use short and concise responses, avoiding unpronounceable punctuation. "
"When you see a screen frame in the conversation, naturally incorporate what you see "
"into your response. Keep visual descriptions brief but informative. "
"If no screen is shared, respond normally without mentioning vision."
),
)
ctx.proc.userdata["initial_ctx"] = initial_ctx
# Initialize the function context
fnc_ctx = AssistantFunction(base_llm=openai.LLM(model="gpt-4o-mini"))
# Correct the assistant initialization
assistant = VoicePipelineAgent(
llm=google.beta.realtime.RealtimeModel(voice="Charon"),
chat_ctx=initial_ctx,
fnc_ctx=fnc_ctx,
before_llm=before_llm_cb,
)
# Start the assistant
assistant.start(ctx.room, participant="*")
logger.info("Agent is ready")
# Greet the user
await asyncio.sleep(3)
await assistant.say("Hey, how can I help?", allow_interruptions=True)
if __name__ == "__main__":
cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
mthis is my codefast-jordan-16209
09/04/2025, 5:22 AM