-
Notifications
You must be signed in to change notification settings - Fork 3k
feat: Add D-ID avatar plugin #5232
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
osimhi213
wants to merge
7
commits into
livekit:main
Choose a base branch
from
de-id:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
0b84a00
Chore/add d id as vendor (#3)
osimhi213 095fd7b
Fix number of attempts (#4)
osimhi213 4385220
Merge remote-tracking branch 'upstream/main'
osimhi213 ff1e778
Fix num of attempts (#5)
osimhi213 013255f
Fix version
osimhi213 f898483
Merge remote-tracking branch 'upstream/main'
osimhi213 e7a7b2e
Merge remote-tracking branch 'upstream/main'
osimhi213 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| # LiveKit D-ID Avatar Agent | ||
|
|
||
| This example demonstrates how to create an animated avatar using [D-ID](https://www.d-id.com/). | ||
|
|
||
| ## Usage | ||
|
|
||
| * Update the environment: | ||
|
|
||
| ```bash | ||
| # D-ID Config | ||
| export DID_API_KEY="..." | ||
| export DID_AGENT_ID="..." | ||
|
|
||
| # OpenAI config (or other models, tts, stt) | ||
| export OPENAI_API_KEY="..." | ||
|
|
||
| # LiveKit config | ||
| export LIVEKIT_API_KEY="..." | ||
| export LIVEKIT_API_SECRET="..." | ||
| export LIVEKIT_URL="..." | ||
| ``` | ||
|
|
||
| * Start the agent worker: | ||
|
|
||
| ```bash | ||
| python examples/avatar_agents/did/agent_worker.py dev | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| import logging | ||
| import os | ||
|
|
||
| from dotenv import load_dotenv | ||
|
|
||
| from livekit.agents import Agent, AgentServer, AgentSession, JobContext, cli | ||
| from livekit.plugins import did, openai | ||
|
|
||
| logger = logging.getLogger("did-avatar-example") | ||
| logger.setLevel(logging.INFO) | ||
|
|
||
| load_dotenv() | ||
|
|
||
| server = AgentServer() | ||
|
|
||
|
|
||
| @server.rtc_session() | ||
| async def entrypoint(ctx: JobContext): | ||
| session = AgentSession( | ||
| llm=openai.realtime.RealtimeModel(voice="alloy"), | ||
| resume_false_interruption=False, | ||
| ) | ||
|
|
||
| agent_id = os.getenv("DID_AGENT_ID") | ||
| did_avatar = did.AvatarSession(agent_id=agent_id) | ||
| await did_avatar.start(session, room=ctx.room) | ||
|
|
||
| # start the agent, it will join the room and wait for the avatar to join | ||
| await session.start( | ||
| agent=Agent(instructions="Talk to me!"), | ||
| room=ctx.room, | ||
| ) | ||
|
|
||
| session.generate_reply(instructions="say hello to the user") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| cli.run_app(server) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| # D-ID plugin for LiveKit Agents | ||
|
|
||
| Support for the [D-ID](https://d-id.com/) virtual avatar. | ||
|
|
||
| See the [D-ID integration docs](https://docs.livekit.io/agents/models/avatar/plugins/did/) for more information. | ||
|
|
||
| ## Installation | ||
|
|
||
| ```bash | ||
| pip install livekit-plugins-did | ||
| ``` | ||
|
|
||
| ## Pre-requisites | ||
|
|
||
| You'll need an API key from D-ID. It can be set as an environment variable: `DID_API_KEY` |
42 changes: 42 additions & 0 deletions
42
livekit-plugins/livekit-plugins-did/livekit/plugins/did/__init__.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| # Copyright 2025 LiveKit, Inc. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| """D-ID virtual avatar plugin for LiveKit Agents | ||
|
|
||
| See https://docs.livekit.io/agents/integrations/avatar/did/ for more information. | ||
| """ | ||
|
|
||
| from .avatar import AvatarSession | ||
| from .errors import DIDException | ||
| from .types import AudioConfig | ||
| from .version import __version__ | ||
|
|
||
| __all__ = [ | ||
| "AudioConfig", | ||
| "AvatarSession", | ||
| "DIDException", | ||
| "__version__", | ||
| ] | ||
|
|
||
| from livekit.agents import Plugin | ||
|
|
||
| from .log import logger | ||
|
|
||
|
|
||
| class DIDPlugin(Plugin): | ||
| def __init__(self) -> None: | ||
| super().__init__(__name__, __version__, __package__, logger) | ||
|
|
||
|
|
||
| Plugin.register_plugin(DIDPlugin()) |
92 changes: 92 additions & 0 deletions
92
livekit-plugins/livekit-plugins-did/livekit/plugins/did/api.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| import asyncio | ||
| import os | ||
| from typing import Any | ||
|
|
||
| import aiohttp | ||
|
|
||
| from livekit.agents import ( | ||
| DEFAULT_API_CONNECT_OPTIONS, | ||
| NOT_GIVEN, | ||
| APIConnectionError, | ||
| APIConnectOptions, | ||
| APIStatusError, | ||
| NotGivenOr, | ||
| utils, | ||
| ) | ||
|
|
||
| from .errors import DIDException | ||
| from .log import logger | ||
|
|
||
| DEFAULT_API_URL = "https://api.d-id.com" | ||
|
|
||
|
|
||
| class DIDAPI: | ||
| def __init__( | ||
| self, | ||
| api_key: NotGivenOr[str] = NOT_GIVEN, | ||
| api_url: NotGivenOr[str] = NOT_GIVEN, | ||
| *, | ||
| conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS, | ||
| session: aiohttp.ClientSession | None = None, | ||
| ) -> None: | ||
| did_api_key = api_key if utils.is_given(api_key) else os.getenv("DID_API_KEY") | ||
| if not did_api_key: | ||
| raise DIDException("DID_API_KEY must be set") | ||
| self._api_key = did_api_key | ||
|
|
||
| self._api_url = api_url if utils.is_given(api_url) else DEFAULT_API_URL | ||
| self._conn_options = conn_options | ||
| self._session = session or aiohttp.ClientSession() | ||
|
|
||
| async def join_session( | ||
| self, | ||
| *, | ||
| agent_id: str, | ||
| transport: dict[str, Any], | ||
| audio_config: dict[str, Any], | ||
| ) -> str: | ||
| """Dispatch a D-ID avatar worker into the room. | ||
|
|
||
| Returns the session id. | ||
| """ | ||
| payload: dict[str, Any] = { | ||
| "transport": transport, | ||
| "audio_config": audio_config, | ||
| } | ||
| response_data = await self._post(f"v2/agents/{agent_id}/sessions/join", payload) | ||
| return response_data["id"] # type: ignore | ||
|
|
||
| async def _post(self, endpoint: str, payload: dict[str, Any]) -> dict[str, Any]: | ||
| url = f"{self._api_url}/{endpoint}" | ||
| num_attempts = self._conn_options.max_retry + 1 | ||
| for attempt in range(num_attempts): | ||
| try: | ||
| async with self._session.post( | ||
| url, | ||
| headers={ | ||
| "Content-Type": "application/json", | ||
| "Authorization": f"Basic {self._api_key}", | ||
| }, | ||
| json=payload, | ||
| timeout=aiohttp.ClientTimeout(sock_connect=self._conn_options.timeout), | ||
| ) as response: | ||
| if not response.ok: | ||
| text = await response.text() | ||
| raise APIStatusError( | ||
| "D-ID API error", | ||
| status_code=response.status, | ||
| body=text, | ||
| ) | ||
| return await response.json() # type: ignore | ||
| except APIStatusError: | ||
| raise | ||
| except (aiohttp.ClientError, asyncio.TimeoutError) as e: | ||
| logger.warning( | ||
| f"D-ID API request failed (attempt {attempt + 1}/{num_attempts})", | ||
| extra={"error": str(e)}, | ||
| ) | ||
| if attempt == num_attempts - 1: | ||
| raise APIConnectionError(f"Failed to connect to D-ID API at {url}") from e | ||
| await asyncio.sleep(self._conn_options.retry_interval) | ||
|
|
||
| raise APIConnectionError(f"Failed to connect to D-ID API at {url}") | ||
126 changes: 126 additions & 0 deletions
126
livekit-plugins/livekit-plugins-did/livekit/plugins/did/avatar.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,126 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import os | ||
|
|
||
| import aiohttp | ||
|
|
||
| from livekit import api, rtc | ||
| from livekit.agents import ( | ||
| DEFAULT_API_CONNECT_OPTIONS, | ||
| NOT_GIVEN, | ||
| AgentSession, | ||
| APIConnectOptions, | ||
| NotGivenOr, | ||
| get_job_context, | ||
| utils, | ||
| ) | ||
| from livekit.agents.voice.avatar import DataStreamAudioOutput | ||
| from livekit.agents.voice.room_io import ATTRIBUTE_PUBLISH_ON_BEHALF | ||
|
|
||
| from .api import DIDAPI | ||
| from .errors import DIDException | ||
| from .log import logger | ||
| from .types import AudioConfig | ||
|
|
||
| _AVATAR_AGENT_IDENTITY = "d-id-avatar-agent" | ||
| _AVATAR_AGENT_NAME = "d-id-avatar-agent" | ||
|
|
||
|
|
||
| class AvatarSession: | ||
| """A D-ID avatar session""" | ||
|
|
||
| def __init__( | ||
| self, | ||
| *, | ||
| agent_id: str, | ||
| api_url: NotGivenOr[str] = NOT_GIVEN, | ||
| api_key: NotGivenOr[str] = NOT_GIVEN, | ||
| audio_config: AudioConfig | None = None, | ||
| avatar_participant_identity: NotGivenOr[str] = NOT_GIVEN, | ||
| avatar_participant_name: NotGivenOr[str] = NOT_GIVEN, | ||
| conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS, | ||
| ) -> None: | ||
| self._http_session: aiohttp.ClientSession | None = None | ||
| self._conn_options = conn_options | ||
| self._agent_id = agent_id | ||
| self._audio_config = audio_config or AudioConfig() | ||
| self.session_id: str | None = None | ||
|
|
||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. we should throw an informative error if the |
||
| self._api = DIDAPI( | ||
| api_url=api_url, | ||
| api_key=api_key, | ||
| conn_options=conn_options, | ||
| session=self._ensure_http_session(), | ||
| ) | ||
|
|
||
| self._avatar_participant_identity = ( | ||
| avatar_participant_identity | ||
| if utils.is_given(avatar_participant_identity) | ||
| else _AVATAR_AGENT_IDENTITY | ||
| ) | ||
| self._avatar_participant_name = ( | ||
| avatar_participant_name | ||
| if utils.is_given(avatar_participant_name) | ||
| else _AVATAR_AGENT_NAME | ||
| ) | ||
|
|
||
| def _ensure_http_session(self) -> aiohttp.ClientSession: | ||
| if self._http_session is None: | ||
| self._http_session = utils.http_context.http_session() | ||
|
|
||
| return self._http_session | ||
|
|
||
| async def start( | ||
| self, | ||
| agent_session: AgentSession, | ||
| room: rtc.Room, | ||
| *, | ||
| livekit_url: NotGivenOr[str] = NOT_GIVEN, | ||
| livekit_api_key: NotGivenOr[str] = NOT_GIVEN, | ||
| livekit_api_secret: NotGivenOr[str] = NOT_GIVEN, | ||
| ) -> None: | ||
| _livekit_url = livekit_url if utils.is_given(livekit_url) else os.getenv("LIVEKIT_URL") | ||
| _livekit_api_key = ( | ||
| livekit_api_key if utils.is_given(livekit_api_key) else os.getenv("LIVEKIT_API_KEY") | ||
| ) | ||
| _livekit_api_secret = ( | ||
| livekit_api_secret | ||
| if utils.is_given(livekit_api_secret) | ||
| else os.getenv("LIVEKIT_API_SECRET") | ||
| ) | ||
| if not _livekit_url or not _livekit_api_key or not _livekit_api_secret: | ||
| raise DIDException( | ||
| "livekit_url, livekit_api_key, and livekit_api_secret must be set " | ||
| "by arguments or environment variables" | ||
| ) | ||
|
|
||
| job_ctx = get_job_context() | ||
| local_participant_identity = job_ctx.local_participant_identity | ||
| livekit_token = ( | ||
| api.AccessToken(api_key=_livekit_api_key, api_secret=_livekit_api_secret) | ||
| .with_kind("agent") | ||
| .with_identity(self._avatar_participant_identity) | ||
| .with_name(self._avatar_participant_name) | ||
| .with_grants(api.VideoGrants(room_join=True, room=room.name)) | ||
| .with_attributes({ATTRIBUTE_PUBLISH_ON_BEHALF: local_participant_identity}) | ||
| .to_jwt() | ||
| ) | ||
|
|
||
| logger.debug("starting avatar session") | ||
| self.session_id = await self._api.join_session( | ||
| agent_id=self._agent_id, | ||
| transport={ | ||
| "provider": "livekit", | ||
| "server_url": _livekit_url, | ||
| "token": livekit_token, | ||
| "room_name": room.name, | ||
| }, | ||
| audio_config={"sample_rate": self._audio_config.sample_rate}, | ||
| ) | ||
|
|
||
| agent_session.output.audio = DataStreamAudioOutput( | ||
| room=room, | ||
| destination_identity=self._avatar_participant_identity, | ||
| sample_rate=self._audio_config.sample_rate, | ||
| wait_remote_track=rtc.TrackKind.KIND_VIDEO, | ||
| ) | ||
4 changes: 4 additions & 0 deletions
4
livekit-plugins/livekit-plugins-did/livekit/plugins/did/errors.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| class DIDException(Exception): | ||
| """Custom exception for D-ID API errors.""" | ||
|
|
||
| pass |
3 changes: 3 additions & 0 deletions
3
livekit-plugins/livekit-plugins-did/livekit/plugins/did/log.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| import logging | ||
|
|
||
| logger = logging.getLogger("livekit.plugins.did") |
Empty file.
14 changes: 14 additions & 0 deletions
14
livekit-plugins/livekit-plugins-did/livekit/plugins/did/types.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| from dataclasses import dataclass | ||
|
|
||
| DEFAULT_SAMPLE_RATE = 24000 | ||
|
|
||
|
|
||
| @dataclass | ||
| class AudioConfig: | ||
| """Configuration for the audio sent to the D-ID avatar. | ||
|
|
||
| Attributes: | ||
| sample_rate: Sample rate in Hz. Supported values: 16000, 24000, 48000. | ||
| """ | ||
|
|
||
| sample_rate: int = DEFAULT_SAMPLE_RATE |
15 changes: 15 additions & 0 deletions
15
livekit-plugins/livekit-plugins-did/livekit/plugins/did/version.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| # Copyright 2025 LiveKit, Inc. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| __version__ = "1.5.1" |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
are only v2 avatars supported for the plugin? it might be worth making a note in the readme