Give me an example of registering an RPC call on a...
# ask-ai
a
Give me an example of registering an RPC call on a react frontend.
t
Thanks for reaching out, Somaan. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hey there! If you want to register an RPC call on a React frontend using LiveKit, here’s a friendly step-by-step guide to help you out: 1. Access the Local Participant: First, grab the
localParticipant
from your room. 2. Register the RPC Method: Next, use the
registerRpcMethod
function on that local participant. Just provide the method name and a handler function. 3. Implement the Handler: This handler function will get an
RpcInvocationData
object and should return a string. If something goes wrong, you can throw an
RpcError
to let the caller know. Here’s a simple example to make it clearer:
Copy code
room.localParticipant?.registerRpcMethod(
  'greet',  // The name of the method
  async (data: RpcInvocationData) => {
    console.log(`Received greeting from ${data.callerIdentity}: ${data.payload}`);
    return `Hello, ${data.callerIdentity}!`;
  }
);
Just a few things to keep in mind: • Your handler needs to be an async function. • It should return a Promise that resolves to a string. • If the handler doesn’t respond before the timeout, the caller will get an error. • If you throw a
RpcError
inside the handler, the caller will receive that error message exactly as you sent it. And don’t forget cleanup: When you’re done with the method, it’s a good idea to unregister it, usually inside a cleanup function:
Copy code
room.localParticipant?.unregisterRpcMethod('greet');
a
Give me the full code with everything included i.e. connection to room, etc...
t
Here’s a complete example of how you can register an RPC call in a React frontend, including how to connect to a room. Think of it as a friendly guide to get you started:
Copy code
import { Room, RoomEvent, RpcError, type RoomConnectOptions } from 'livekit-client-sdk-js';

// Initialize the room
const [room] = useState(new Room());

useEffect(() => {
  const connectToRoom = async () => {
    try {
      const response = await fetch('YOUR_TOKEN_ENDPOINT');
      const { token, url } = await response.json();
      
      await room.connect(url, token, {
        autoSubscribe: true,
      } as RoomConnectOptions);

      // Register an RPC method
      room.localParticipant?.registerRpcMethod('greet', async (data) => {
        console.log(`Received greeting from ${data.callerIdentity}: ${data.payload}`);
        return `Hello, ${data.callerIdentity}!`;
      });

      // Handle room events
      room.on(RoomEvent.Connected, () => {
        console.log('Connected to the room');
        
        // Perform an RPC call
        performRpc();
      });
    } catch (error) {
      console.error('Error connecting to room:', error);
    }
  };

  connectToRoom();
}, [room]);

const performRpc = async () => {
  try {
    const response = await room.localParticipant?.performRpc({
      destinationIdentity: 'recipient-identity',
      method: 'greet',
      payload: 'Hello from React!',
    });
    
    console.log('RPC response:', response);
  } catch (error) {
    console.error('RPC call failed:', error);
  }
};
Key Components:Room Connection: This is where you connect using your LiveKit server URL and token. • RPC Registration: Don’t forget, the recipient needs to register the method before it can be called. • RPC Invocation: Here you call the method on a remote participant and smoothly handle the response or any errors. Usage Notes: • Make sure to replace
'YOUR_TOKEN_ENDPOINT'
with your actual token generation endpoint. • Double-check that the
destinationIdentity
matches the participant you want to reach out to. • It’s a good idea to handle RPC errors properly, like checking for specific error codes such as
RpcError.ErrorCode.UNSUPPORTED_METHOD
.
a
I want to do an RPC call from my agent to my frontend. The call will be called 'get_user_location'. Write the code for both frontend and agent. I want to specifically see how the rpc calls are made and registered on both sides
t
Here’s a friendly example of how you can set up an RPC call between an agent and a frontend for the method `get_user_location`: Agent Implementation (Python)
Copy code
from livekit.agents import llm
from typing import Annotated
import json

class AssistantFnc(llm.FunctionContext):
    @llm.ai_callable()
    async def get_user_location(self,
        high_accuracy: Annotated[
            bool, llm.TypeInfo(description="Whether to use high accuracy mode, which is slower")
        ] = False
    ):
        """Retrieve the user's current geolocation as lat/lng."""
        try:
            # Use room.local_participant to perform the RPC call
            return await room.local_participant.perform_rpc(
                destination_identity=participant.identity,
                method="getUserLocation",
                payload=json.dumps({
                    "highAccuracy": high_accuracy
                }),
                response_timeout=10.0 if high_accuracy else 5.0,
            )
        except Exception:
            return "Unable to retrieve user location"
Frontend Implementation (JavaScript)
Copy code
import { RpcError, RpcInvocationData } from 'livekit-client';

// Register the RPC method when the local participant is connected
localParticipant.registerRpcMethod(
    'getUserLocation',
    async (data: RpcInvocationData) => {
        try {
            let params = JSON.parse(data.payload);
            const position: GeolocationPosition = await new Promise((resolve, reject) => {
                navigator.geolocation.getCurrentPosition(resolve, reject, {
                    enableHighAccuracy: params.highAccuracy ?? false,
                    timeout: data.responseTimeout,
                });
            });
            return JSON.stringify({
                latitude: position.coords.latitude,
                longitude: position.coords.longitude,
            });
        } catch (error) {
            throw new RpcError(1, "Could not retrieve user location");
        }
    }
);
Key Aspects: • The agent defines a
get_user_location
function using the
ai_callable
decorator, making it easy to call. • The agent makes an RPC call to the frontend's
getUserLocation
method to fetch the location. • The frontend registers the
getUserLocation
method to respond to these location requests smoothly. Additional Notes: • We use JSON payloads to pass parameters like the
highAccuracy
flag, keeping things clear and simple. • The browser’s geolocation API is leveraged to get accurate user positioning. • There’s solid error handling in place with
RpcError
, so you’re covered if something goes wrong. • Response timeouts are managed thoughtfully to keep everything running smoothly. If you want me to walk you through any part of this or need more examples, just let me know — I’m happy to help! Sources: Function calling with Voice Agents | LiveKit Docs