How do I set attributes / metadata as a user / par...
# ask-ai
q
How do I set attributes / metadata as a user / participant in a session ? Doing something like
Copy code
await roomContext.localParticipant.setAttributes({
          someId: '1234567890',
        })
Yields an error
Request to update local metadata timed out
t
Thanks for reaching out, Andrei. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hi there! To set attributes or metadata for a participant in a LiveKit session, you can use the following method:
Copy code
await localParticipant.setAttributes({
  someId: '1234567890',
});
Now, if you’re seeing the error
Request to update local metadata timed out
, it’s usually because of one of these reasons: • Permission Issues: Make sure the participant’s access token has the
canUpdateOwnMetadata
permission included. • Network Connectivity: Sometimes, poor network conditions can cause timeouts. Adding some retry logic might help smooth things out. • Server Load: If the server is really busy, updates might get delayed. You might want to try reducing how often you update or batch updates together for better reliability. Also, keep in mind that attributes and metadata updates aren’t really meant for high-frequency changes. If you need to update things frequently, using data packets could be a better fit. If you’re still running into trouble, double-check your access token permissions, your network connection, and take a peek at the server logs for any clues. I’m here if you need any more help—just let me know! Sources: livekit-rtc/livekit/rtc/participant.py | livekit/src/room/participant/local_participant.rs | Participant attributes and metadata | LiveKit Docs | Livestream Mode | Managing participants | LiveKit Docs
q
Here is how my server implementation looks like:
Copy code
if (!env.LIVEKIT.API_KEY || !env.LIVEKIT.API_SECRET) {
      throw new Error('LiveKit credentials not configured')
    }

    const participantIdentity =
      ctx.user.id + '_' + Math.floor(Math.random() * 10_000)
    const participantName = ctx.user.name
    const roomName = `voice_assistant_room_${Math.floor(Math.random() * 10_000)}`
    const ttlMinutes = 30
    const agentName = undefined

    const accessToken = new AccessToken(
      'devkey', //   env.LIVEKIT.API_KEY,
      'secret', //   env.LIVEKIT.API_SECRET,
      {
        identity: participantIdentity,
        name: participantName,
        ttl: `${ttlMinutes}m`,
        attributes: {
          userid: ctx.user.id,
        },
      } as AccessTokenOptions
    )

    const grant: VideoGrant = {
      room: roomName,
      roomJoin: true,
      canPublish: true,
      canPublishData: true,
      canSubscribe: true,
      canUpdateOwnMetadata: true,
    }

    accessToken.addGrant(grant)

    accessToken.roomConfig = new RoomConfiguration({
      agents: [
        new RoomAgentDispatch({
          agentName: agentName,
          metadata: JSON.stringify({
            userid: ctx.user.id,
            username: ctx.user.name,
          }),
        }),
      ],
    })

    const participantToken = await accessToken.toJwt()

    return {
      serverUrl: 'ws://localhost:7880', // env.LIVEKIT.URL,
      roomName,
      participantName,
      participantToken,
    }
Here is my frontend implementation:
Copy code
const plmid = useParticipantAttribute('plmid', {
    participant: localParticipant,
  })
  console.log('🚀 ~ RoomView ~ plmid:', plmid)

  useEffect(() => {
    async function setPlmid() {
      if (roomContext.localParticipant && !plmid) {
        console.log('setting plmid', roomContext.localParticipant)
        await roomContext.localParticipant.setAttributes({
          plmkey: '1234567890',
        })
        // canUpdateOwnMetadata
        console.log('plmid set')
      }
    }
    setPlmid()
  }, [roomContext?.localParticipant, plmid])
But I still get
Request to update local metadata timed out
Why ?
t
I'm sorry to hear you're encountering the
Request to update local metadata timed out
error. Let's work through some common reasons this might happen and see if we can get things running smoothly for you: • Permission Issues: Please double-check that your access token includes the
canUpdateOwnMetadata
permission. This permission is essential for allowing participants to update their own metadata. • Attribute Size: It's a good idea to verify that the total size of all attribute keys and values stays within 64 KiB to avoid any hiccups. • Network Connectivity: Sometimes, network issues or server overloads can cause timeouts. Implementing retry logic with exponential backoff can really help manage these temporary problems. • Update Frequency: Try to avoid calling
setAttributes
more often than once every few seconds, since rapid updates might not be supported. In your server code, please make sure the
canUpdateOwnMetadata
permission is properly included in the access token. Also, keeping an eye on your network connection and postponing updates during times of poor connectivity can make a big difference. If you'd like, I'm here to help you debug further or check any specific parts of your implementation—just let me know! Sources: livekit/src/room/participant/local_participant.rs | src/room/participant/LocalParticipant.ts | Participant attributes and metadata | LiveKit Docs | pkg/rtc/participant.go
q
Now how do I subscribe to participant attribute changes on the agent side ?
t
I'm happy to help you subscribe to participant attribute changes on the agent side! You can use the
participant_attributes_changed
event for this. Here’s a simple example to get you started:
Copy code
room.on("participant_attributes_changed", (changedAttributes, participant) => {
  console.log("Attributes changed:", changedAttributes);
  console.log("Updated participant attributes:", participant.attributes);
});
Just to clarify, the event handler gives you two important pieces of information: • changedAttributes: This is a dictionary showing only the attributes that were updated in this change. • participant: This is the participant object whose attributes were updated, including their full attributes dictionary, identity, and type. This setup lets you respond smoothly whenever attributes change for any participant in the room, whether local or remote. If you have any questions or want me to walk you through anything else, please don’t hesitate to ask—I’m here to help! Sources: telephony/sip_lifecycle.py | agent/main.py | Participant attributes and metadata | LiveKit Docs | examples/participant_attributes.py
q
How do I send some extra data from the agent to the participant ?
t
I'd be happy to help you send extra data from an agent to a participant in LiveKit! There are a few ways you can do this: • RPC (Remote Procedure Calls): You can use the
perform_rpc
method to send structured data directly to a specific participant. Here's a quick example:
Copy code
await room.localParticipant.perform_rpc({
  destination_identity: participant.identity,
  method: "client.quiz",
  payload: JSON.stringify({ key: "value" })
});
• Data Messages: Another option is the
sendData
method, which lets you send arbitrary data packets. For example:
Copy code
await roomServiceClient.sendData(
  roomName,
  data,  // Uint8Array
  DataPacket_Kind.RELIABLE,  // or LOSSY
  { destinationIdentities: [participantIdentity], topic: "custom-data" }
);
• Text or Byte Streams: If you're dealing with larger or incremental data, streaming APIs for text or bytes might be the way to go. Each method suits different needs—RPC is great for structured calls,
sendData
works well for straightforward messages, and streams shine with large or real-time data. If you'd like, I’m here to guide you through implementing any of these options! Sources: complex-agents/nutrition-assistant/agent.py | livekit-agents/livekit/agents/voice/room_io/_input.py | src/main/kotlin/io/livekit/server/RoomServiceClient.kt | livekit-api/src/services/room.rs | Data packets | LiveKit Docs
q
registerRpcMethod is called on the client side or server side ?
t
The
registerRpcMethod
function is called on the client side. It helps you register RPC handlers on client participants, so they can receive and respond to remote procedure calls from others in the room. For example, in JavaScript:
Copy code
room.localParticipant?.registerRpcMethod(
  'greet',
  async (data) => {
    console.log(`Received greeting from ${data.callerIdentity}: ${data.payload}`);
    return `Hello, ${data.callerIdentity}!`;
  }
);
If you have any questions or need a hand with implementing this, please feel free to ask—I’m here to help! Sources: packages/livekit-rtc/src/participant.ts | Sources/LiveKit/Participant/LocalParticipant+RPC.swift | room.go | Remote method calls (RPC) | LiveKit Docs