|
4 | 4 |
|
5 | 5 | from livekit import rtc |
6 | 6 |
|
| 7 | +from ..types import ATTRIBUTE_AGENT_NAME |
| 8 | + |
| 9 | + |
| 10 | +async def wait_for_agent( |
| 11 | + room: rtc.Room, |
| 12 | + *, |
| 13 | + agent_name: str | None = None, |
| 14 | +) -> rtc.RemoteParticipant: |
| 15 | + """ |
| 16 | + Wait for an agent participant to join the room. |
| 17 | +
|
| 18 | + Args: |
| 19 | + room: The room to wait for the agent in. |
| 20 | + agent_name: If provided, waits for an agent with matching lk.agent.name attribute. |
| 21 | + If None, returns the first agent participant found. |
| 22 | +
|
| 23 | + Returns: |
| 24 | + The agent participant. |
| 25 | +
|
| 26 | + Raises: |
| 27 | + RuntimeError: If the room is not connected. |
| 28 | + """ |
| 29 | + if not room.isconnected(): |
| 30 | + raise RuntimeError("room is not connected") |
| 31 | + |
| 32 | + fut: asyncio.Future[rtc.RemoteParticipant] = asyncio.Future() |
| 33 | + |
| 34 | + def matches_agent(p: rtc.RemoteParticipant) -> bool: |
| 35 | + if p.kind != rtc.ParticipantKind.PARTICIPANT_KIND_AGENT: |
| 36 | + return False |
| 37 | + if agent_name is None: |
| 38 | + return True |
| 39 | + return p.attributes.get(ATTRIBUTE_AGENT_NAME) == agent_name |
| 40 | + |
| 41 | + def on_participant_connected(p: rtc.RemoteParticipant) -> None: |
| 42 | + if matches_agent(p) and not fut.done(): |
| 43 | + fut.set_result(p) |
| 44 | + |
| 45 | + def on_attributes_changed(changed: list[str], p: rtc.Participant) -> None: |
| 46 | + if isinstance(p, rtc.RemoteParticipant) and matches_agent(p) and not fut.done(): |
| 47 | + fut.set_result(p) |
| 48 | + |
| 49 | + room.on("participant_connected", on_participant_connected) |
| 50 | + room.on("participant_attributes_changed", on_attributes_changed) |
| 51 | + |
| 52 | + try: |
| 53 | + # Check existing participants |
| 54 | + for p in room.remote_participants.values(): |
| 55 | + if matches_agent(p): |
| 56 | + return p |
| 57 | + |
| 58 | + return await fut |
| 59 | + finally: |
| 60 | + room.off("participant_connected", on_participant_connected) |
| 61 | + room.off("participant_attributes_changed", on_attributes_changed) |
| 62 | + |
7 | 63 |
|
8 | 64 | async def wait_for_participant( |
9 | 65 | room: rtc.Room, |
|
0 commit comments