How to send data from lk agent (agent.py) to part...
# ask-ai
b
How to send data from lk agent (agent.py) to participants. and how to listen data in client side (js sdk)
t
Thanks for reaching out, G. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm glad you're exploring how to send data from your LiveKit agent (Python) to participants and listen for it on the client side (JavaScript SDK)! You have two great options here: data packets and RPC (Remote Procedure Calls). Let's walk through both together. 1. Sending Data from the Agent (Python):Using Data Packets: You can use
publish_data
to send data to participants. Here's a simple example:
Copy code
await room.local_participant.publish_data(
    payload="Hello world",
    reliable=True,  # or False for lossy delivery
    topic="custom.topic"
)
Using RPC: If you want to call a method on a specific participant,
perform_rpc
is your friend:
Copy code
await ctx.room.local_participant.perform_rpc(
    destination_identity=client_participant.identity,
    method="receive_transcript",
    payload=json.dumps({"transcript": "Hello from agent"})
)
2. Receiving Data on the Client (JavaScript SDK):Listening to Data Packets: Simply listen to the
dataReceived
event like this:
Copy code
room.on('dataReceived', (payload, participant, kind) => {
    const decoder = new TextDecoder();
    const strData = decoder.decode(payload);
    console.log(`Received data: ${strData}`);
});
Listening to RPC: You can register a method using
registerRpcMethod
to handle incoming RPC calls:
Copy code
room.localParticipant.registerRpcMethod('receive_transcript', async (payload) => {
    const data = JSON.parse(payload);
    console.log('Transcript received:', data.transcript);
});
Generally, RPC works wonderfully when you want structured communication, like method-based updates, while data packets are perfect for broadcasting frequent updates to many participants. If you have any questions or want to dive deeper into any part, please don’t hesitate to ask—I’m here to help! Sources: agent/game_host.py | complex-agents/role-playing/agents/base_agent.py | Data packets | LiveKit Docs | Inside a session | LiveKit Docs | Web and mobile frontends | LiveKit Docs