aloof-airport-60870
08/12/2025, 8:03 AMtall-airline-16756
08/12/2025, 8:03 AMtall-airline-16756
08/12/2025, 8:04 AMlocalParticipant
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:
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:
room.localParticipant?.unregisterRpcMethod('greet');
aloof-airport-60870
08/12/2025, 8:05 AMtall-airline-16756
08/12/2025, 8:05 AMimport { 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
.aloof-airport-60870
08/12/2025, 8:07 AMtall-airline-16756
08/12/2025, 8:08 AMfrom 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)
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