give me an example in python: I want to send RPC f...
# ask-ai
r
give me an example in python: I want to send RPC from agent to the remote user (frontend)
t
Thanks for reaching out, Ivan. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking for a Python example to send an RPC from a LiveKit agent to a remote frontend user. Below is a concise example you can adapt.
Copy code
import json
import asyncio
from livekit.agents import get_job_context, function_tool

@function_tool()
async def send_rpc_to_frontend(self, context, message: str, method: str = "showNotification"):
    """
    Send an RPC from an agent (local participant) to a remote frontend participant.
    """
    job_ctx = get_job_context()
    room = job_ctx.room

    # pick a remote participant (adjust selection as needed)
    remote_participants = room.remote_participants
    if not remote_participants:
        raise Exception("No remote participants in the room")

    remote_participant = next(iter(remote_participants.values()))

    payload = json.dumps({
        "message": message,
        "sent_at": asyncio.get_event_loop().time()
    })

    try:
        response = await room.local_participant.perform_rpc(
            destination_identity=remote_participant.identity,
            method=method,
            payload=payload,
            response_timeout=10.0
        )
        return {"status": "sent", "response": response}
    except Exception as e:
        raise Exception(f"Failed to send RPC: {e}")
Notes: •
method
must match the RPC handler registered in the frontend. •
payload
must be a JSON string; adjust its structure to your frontend's expectations. • Change how you select the target participant if you need a specific user (by identity or metadata). Would you like an example of the corresponding frontend RPC handler (JS) or help selecting a specific participant? Sources: External data and RAG | LiveKit Docs | Remote method calls | LiveKit docs