Hi, how to register rpc method in python? Gimme fu...
# ask-ai
a
Hi, how to register rpc method in python? Gimme full code of simple agent implementation.
t
Thanks for reaching out, Gamal. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
To register an RPC method in Python, you can use the
register_rpc_method
function on the
local_participant
of the room. Below is a complete example of a simple agent implementation:
Copy code
import logging
import json
from livekit.agents import JobContext, WorkerOptions, cli, RoomOutputOptions
from livekit.rtc import RpcInvocationData

logger = logging.getLogger("simple-rpc-agent")
logger.setLevel(logging.INFO)

async def handle_ping(data: RpcInvocationData) -> str:
    """Simple RPC handler that responds to ping with pong and echoes payload."""
    try:
        payload = json.loads(data.payload) if data.payload else {}
        logger.info(f"Received ping from {data.participant_identity}, payload: {payload}")
        return json.dumps({"response": "pong", "echo": payload})
    except Exception as e:
        logger.error(f"Error in handle_ping: {e}")
        return json.dumps({"error": str(e)})

async def entrypoint(ctx: JobContext):
    logger.info("Agent starting up")

    # Connect the agent to the room
    await ctx.connect()

    # Register the RPC method
    logger.info("Registering RPC method: ping")
    ctx.room.local_participant.register_rpc_method("ping", handle_ping)

    # Start the agent session
    await ctx.room.local_participant.start(
        room_output_options=RoomOutputOptions(audio_enabled=True)
    )

if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
This example shows you how to: • Define an async handler function (
handle_ping
) that processes RPC requests and returns a JSON response. • Register the handler using
register_rpc_method
with a unique method name (like "ping"). • Start the agent and connect it to a room. If you have any questions or need a hand with anything else, just let me know! I'm here to help. Sources: Remote method calls (RPC) | LiveKit Docs | agent/game_host.py | complex-agents/role-playing/agent.py
a
Then, how to use @ attributes to register some rpc?
t
To use
@
attributes (decorators) for registering RPC methods in Python, you can simply decorate an async function with
@room.local_participant.register_rpc_method("method_name")
. Here’s a friendly example to help you get started:
Copy code
@room.local_participant.register_rpc_method("greet")
async def handle_greet(data: RpcInvocationData) -> str:
    print(f"Received greeting from {data.caller_identity}: {data.payload}")
    return f"Hello, {data.caller_identity}!"
Here’s a little breakdown: •
"greet"
is the method name that remote participants will use to call this function. • The handler function
handle_greet
gets an
RpcInvocationData
object, which carries useful info like who called and the payload. • The function then sends back a string response to the caller. You can register as many RPC methods as you need, just like this:
Copy code
@room.local_participant.register_rpc_method("get_order_state")
async def get_order_state(data: RpcInvocationData) -> str:
    return json.dumps({"total": 25.99, "items": ["burger", "fries"]})
If anything feels unclear or you’d like more examples, please don’t hesitate to ask—I’m here to help! Sources: livekit-rtc/livekit/rtc/participant.py | Remote method calls (RPC) | LiveKit Docs | avatars/hedra/education_avatar/agent.py
a
Great! Gimme full simple agent code that implement that @ decorator for registering RPC function.
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!
a
How to register RPC method right on agent entered room?