|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import os |
| 5 | + |
| 6 | +import aiohttp |
| 7 | + |
| 8 | +from livekit import api, rtc |
| 9 | +from livekit.agents import ( |
| 10 | + DEFAULT_API_CONNECT_OPTIONS, |
| 11 | + NOT_GIVEN, |
| 12 | + AgentSession, |
| 13 | + APIConnectionError, |
| 14 | + APIConnectOptions, |
| 15 | + APIStatusError, |
| 16 | + NotGivenOr, |
| 17 | + get_job_context, |
| 18 | + utils, |
| 19 | +) |
| 20 | +from livekit.agents.voice.avatar import DataStreamAudioOutput |
| 21 | +from livekit.agents.voice.room_io import ATTRIBUTE_PUBLISH_ON_BEHALF |
| 22 | + |
| 23 | +from .log import logger |
| 24 | + |
| 25 | +DEFAULT_API_URL = "https://api.dev.runwayml.com" |
| 26 | +API_VERSION = "2024-11-06" |
| 27 | +SAMPLE_RATE = 16000 |
| 28 | +_AVATAR_AGENT_IDENTITY = "runway-avatar-agent" |
| 29 | +_AVATAR_AGENT_NAME = "runway-avatar-agent" |
| 30 | + |
| 31 | + |
| 32 | +class RunwayException(Exception): |
| 33 | + """Exception for Runway errors""" |
| 34 | + |
| 35 | + |
| 36 | +class AvatarSession: |
| 37 | + """A Runway Characters avatar session. |
| 38 | +
|
| 39 | + Creates a realtime session backed by Runway's avatar inference pipeline. |
| 40 | + The customer's LiveKit agent owns the conversational AI stack (STT, LLM, TTS); |
| 41 | + Runway provides the visual layer — audio in, avatar video out. |
| 42 | + """ |
| 43 | + |
| 44 | + def __init__( |
| 45 | + self, |
| 46 | + *, |
| 47 | + avatar_id: NotGivenOr[str | None] = NOT_GIVEN, |
| 48 | + preset_id: NotGivenOr[str | None] = NOT_GIVEN, |
| 49 | + max_duration: NotGivenOr[int] = NOT_GIVEN, |
| 50 | + api_url: NotGivenOr[str] = NOT_GIVEN, |
| 51 | + api_key: NotGivenOr[str] = NOT_GIVEN, |
| 52 | + avatar_participant_identity: NotGivenOr[str] = NOT_GIVEN, |
| 53 | + avatar_participant_name: NotGivenOr[str] = NOT_GIVEN, |
| 54 | + conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS, |
| 55 | + ) -> None: |
| 56 | + if not avatar_id and not preset_id: |
| 57 | + raise RunwayException("Either avatar_id or preset_id must be provided") |
| 58 | + if avatar_id and preset_id: |
| 59 | + raise RunwayException("Provide avatar_id or preset_id, not both") |
| 60 | + |
| 61 | + self._avatar_id = avatar_id |
| 62 | + self._preset_id = preset_id |
| 63 | + self._max_duration = max_duration |
| 64 | + |
| 65 | + self._api_url = api_url or os.getenv("RUNWAYML_BASE_URL", DEFAULT_API_URL) |
| 66 | + self._api_key = api_key or os.getenv("RUNWAYML_API_SECRET") |
| 67 | + if self._api_key is None: |
| 68 | + raise RunwayException( |
| 69 | + "api_key must be set either by passing it to AvatarSession or " |
| 70 | + "by setting the RUNWAYML_API_SECRET environment variable" |
| 71 | + ) |
| 72 | + |
| 73 | + self._avatar_participant_identity = avatar_participant_identity or _AVATAR_AGENT_IDENTITY |
| 74 | + self._avatar_participant_name = avatar_participant_name or _AVATAR_AGENT_NAME |
| 75 | + self._http_session: aiohttp.ClientSession | None = None |
| 76 | + self._conn_options = conn_options |
| 77 | + |
| 78 | + def _ensure_http_session(self) -> aiohttp.ClientSession: |
| 79 | + if self._http_session is None: |
| 80 | + self._http_session = utils.http_context.http_session() |
| 81 | + return self._http_session |
| 82 | + |
| 83 | + async def start( |
| 84 | + self, |
| 85 | + agent_session: AgentSession, |
| 86 | + room: rtc.Room, |
| 87 | + *, |
| 88 | + livekit_url: NotGivenOr[str] = NOT_GIVEN, |
| 89 | + livekit_api_key: NotGivenOr[str] = NOT_GIVEN, |
| 90 | + livekit_api_secret: NotGivenOr[str] = NOT_GIVEN, |
| 91 | + ) -> None: |
| 92 | + livekit_url = livekit_url or (os.getenv("LIVEKIT_URL") or NOT_GIVEN) |
| 93 | + livekit_api_key = livekit_api_key or (os.getenv("LIVEKIT_API_KEY") or NOT_GIVEN) |
| 94 | + livekit_api_secret = livekit_api_secret or (os.getenv("LIVEKIT_API_SECRET") or NOT_GIVEN) |
| 95 | + if not livekit_url or not livekit_api_key or not livekit_api_secret: |
| 96 | + raise RunwayException( |
| 97 | + "livekit_url, livekit_api_key, and livekit_api_secret must be set " |
| 98 | + "by arguments or environment variables" |
| 99 | + ) |
| 100 | + |
| 101 | + job_ctx = get_job_context() |
| 102 | + local_participant_identity = job_ctx.local_participant_identity |
| 103 | + |
| 104 | + livekit_token = ( |
| 105 | + api.AccessToken(api_key=livekit_api_key, api_secret=livekit_api_secret) |
| 106 | + .with_kind("agent") |
| 107 | + .with_identity(self._avatar_participant_identity) |
| 108 | + .with_name(self._avatar_participant_name) |
| 109 | + .with_grants(api.VideoGrants(room_join=True, room=room.name)) |
| 110 | + .with_attributes({ATTRIBUTE_PUBLISH_ON_BEHALF: local_participant_identity}) |
| 111 | + .to_jwt() |
| 112 | + ) |
| 113 | + |
| 114 | + logger.debug("starting Runway avatar session") |
| 115 | + await self._create_session(livekit_url, livekit_token, room.name) |
| 116 | + |
| 117 | + agent_session.output.audio = DataStreamAudioOutput( |
| 118 | + room=room, |
| 119 | + destination_identity=self._avatar_participant_identity, |
| 120 | + wait_remote_track=rtc.TrackKind.KIND_VIDEO, |
| 121 | + sample_rate=SAMPLE_RATE, |
| 122 | + ) |
| 123 | + |
| 124 | + async def _create_session(self, livekit_url: str, livekit_token: str, room_name: str) -> None: |
| 125 | + assert self._api_key is not None |
| 126 | + assert isinstance(self._api_url, str) |
| 127 | + |
| 128 | + if self._avatar_id: |
| 129 | + avatar = {"type": "custom", "avatarId": self._avatar_id} |
| 130 | + else: |
| 131 | + avatar = {"type": "runway-preset", "presetId": self._preset_id} |
| 132 | + |
| 133 | + body: dict = { |
| 134 | + "model": "gwm1_avatars", |
| 135 | + "avatar": avatar, |
| 136 | + "livekit": { |
| 137 | + "url": livekit_url, |
| 138 | + "token": livekit_token, |
| 139 | + "roomName": room_name, |
| 140 | + }, |
| 141 | + } |
| 142 | + |
| 143 | + if self._max_duration: |
| 144 | + body["maxDuration"] = self._max_duration |
| 145 | + |
| 146 | + for attempt in range(self._conn_options.max_retry): |
| 147 | + try: |
| 148 | + async with self._ensure_http_session().post( |
| 149 | + f"{self._api_url}/v1/realtime_sessions", |
| 150 | + headers={ |
| 151 | + "Authorization": f"Bearer {self._api_key}", |
| 152 | + "X-Runway-Version": API_VERSION, |
| 153 | + }, |
| 154 | + json=body, |
| 155 | + timeout=aiohttp.ClientTimeout(sock_connect=self._conn_options.timeout), |
| 156 | + ) as response: |
| 157 | + if not response.ok: |
| 158 | + text = await response.text() |
| 159 | + raise APIStatusError( |
| 160 | + "Runway API returned an error", |
| 161 | + status_code=response.status, |
| 162 | + body=text, |
| 163 | + ) |
| 164 | + return |
| 165 | + |
| 166 | + except Exception as error: |
| 167 | + if isinstance(error, APIStatusError): |
| 168 | + raise |
| 169 | + |
| 170 | + if isinstance(error, APIConnectionError): |
| 171 | + logger.warning( |
| 172 | + "failed to call Runway avatar API", |
| 173 | + extra={"error": str(error)}, |
| 174 | + ) |
| 175 | + else: |
| 176 | + logger.exception("failed to call Runway avatar API") |
| 177 | + |
| 178 | + if attempt < self._conn_options.max_retry - 1: |
| 179 | + await asyncio.sleep(self._conn_options.retry_interval) |
| 180 | + |
| 181 | + raise APIConnectionError("Failed to start Runway Avatar Session after all retries") |
0 commit comments