Repository navigation
feat: add callyour.ai avatar plugin #8859
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
JonasDaWi
wants to merge
7
commits into
livekit:main
Choose a base branch
from
JonasDaWi:feat/callyourai-avatar-plugin
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.
+1,276
−1
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
7c62f6a
feat: add callyour.ai avatar plugin
callyourai 9ad18b3
callyourai: bound API requests, hold speech during recovery, keep voi…
callyourai ab161f8
callyourai: keep a session's id until the API has ended it
callyourai 0a689e3
Merge remote-tracking branch 'origin/main' into feat/callyourai-avata…
callyourai a408ce8
callyourai: recover only an avatar that has the agent's speech
callyourai 16be34a
callyourai: check the avatar is still there before the handoff
callyourai a1e897d
Merge remote-tracking branch 'origin/main' into feat/callyourai-avata…
callyourai 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
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 @@ | ||
| # callyour.ai plugin for LiveKit Agents | ||
|
|
||
| Support for [callyour.ai](https://callyour.ai) virtual avatars: a lip-synced, photo-real face | ||
| for your voice agent, made from one photo. | ||
|
|
||
| ## Installation | ||
|
|
||
| ```bash | ||
| pip install livekit-plugins-callyourai | ||
| ``` | ||
|
|
||
| ## Pre-requisites | ||
|
|
||
| You'll need an API key from callyour.ai, set as the environment variable `CALLYOURAI_API_KEY`. | ||
| Sign-up works over the API, so a coding agent can do it too: see | ||
| [api.callyour.ai/llms.txt](https://api.callyour.ai/llms.txt). New accounts get free credit after | ||
| confirming their email, and a ready-made avatar can be used without uploading a photo. | ||
|
|
||
| ## Usage | ||
|
|
||
| ```python | ||
| from livekit.agents import AgentSession | ||
| from livekit.plugins import callyourai | ||
|
|
||
| session = AgentSession(...) | ||
| avatar = callyourai.AvatarSession(avatar_id="...") | ||
| await avatar.start(session, room=ctx.room) | ||
| await session.start(agent=..., room=ctx.room) | ||
| ``` | ||
|
|
||
| Optional: | ||
|
|
||
| - `wait_seconds=60` waits in a queue when every avatar is busy; the agent talks voice-only | ||
| until the avatar is live. | ||
| - `hd=True` uses Live HD; `upgrade_to_hd=True` starts on a normal avatar and switches to Live HD | ||
| mid-call. | ||
| - `await avatar.set_mood("friendly")` and `await avatar.set_action("wave")` change the face and | ||
| play gestures. |
45 changes: 45 additions & 0 deletions
45
livekit-plugins/livekit-plugins-callyourai/livekit/plugins/callyourai/__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,45 @@ | ||
| # Copyright 2026 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. | ||
|
|
||
| """callyour.ai virtual avatar plugin for LiveKit Agents | ||
|
|
||
| See https://api.callyour.ai/llms.txt for the API, avatars and prices. | ||
| """ | ||
|
|
||
| from .api import CallyouraiAPI, CallyouraiAPIError, CallyouraiError, CallyouraiException | ||
| from .avatar import ACTIONS, MOODS, AvatarSession | ||
| from .version import __version__ | ||
|
|
||
| __all__ = [ | ||
| "ACTIONS", | ||
| "MOODS", | ||
| "AvatarSession", | ||
| "CallyouraiAPI", | ||
| "CallyouraiAPIError", | ||
| "CallyouraiError", | ||
| "CallyouraiException", | ||
| "__version__", | ||
| ] | ||
|
|
||
| from livekit.agents import Plugin | ||
|
|
||
| from .log import logger | ||
|
|
||
|
|
||
| class CallyouraiPlugin(Plugin): | ||
| def __init__(self) -> None: | ||
| super().__init__(__name__, __version__, __package__, logger) | ||
|
|
||
|
|
||
| Plugin.register_plugin(CallyouraiPlugin()) |
208 changes: 208 additions & 0 deletions
208
livekit-plugins/livekit-plugins-callyourai/livekit/plugins/callyourai/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,208 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| import json | ||
| import os | ||
| from typing import Any | ||
|
|
||
| import aiohttp | ||
|
|
||
| from livekit.agents import ( | ||
| DEFAULT_API_CONNECT_OPTIONS, | ||
| NOT_GIVEN, | ||
| APIConnectionError, | ||
| APIConnectOptions, | ||
| APIStatusError, | ||
| APITimeoutError, | ||
| NotGivenOr, | ||
| utils, | ||
| ) | ||
|
|
||
| from .log import logger | ||
|
|
||
| DEFAULT_API_URL = "https://api.callyour.ai" | ||
|
|
||
|
|
||
| class CallyouraiException(Exception): | ||
| """Exception for callyour.ai configuration errors""" | ||
|
|
||
|
|
||
| class CallyouraiAPIError(APIStatusError): | ||
| """The callyour.ai API refused a request. | ||
|
|
||
| ``code`` says why, e.g. ``insufficient_credits`` (HTTP 402: buy credits), | ||
| ``no_capacity`` (HTTP 503: every avatar is busy; see ``wait_seconds``) or | ||
| ``avatar_not_found`` (HTTP 404). | ||
| """ | ||
|
|
||
| def __init__(self, message: str, *, status_code: int, code: str, body: object = None) -> None: | ||
| super().__init__(f"{message} ({code})", status_code=status_code, body=body) | ||
| self.code = code | ||
|
|
||
| @property | ||
| def status(self) -> int: | ||
| """The HTTP status (same as ``status_code``).""" | ||
| return self.status_code | ||
|
|
||
|
|
||
| CallyouraiError = CallyouraiAPIError | ||
| """The name of this exception in plugin versions before 1.9.""" | ||
|
|
||
| # Starting a session can take the API longer than a read: it hands the session to a server. | ||
| _CREATE_TIMEOUT = 30.0 | ||
|
|
||
|
|
||
| class CallyouraiAPI: | ||
| """A small client for the callyour.ai session API (https://api.callyour.ai/llms.txt).""" | ||
|
|
||
| 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: | ||
| """ | ||
| Args: | ||
| api_key: your callyour.ai API key. Defaults to the ``CALLYOURAI_API_KEY`` environment | ||
| variable. | ||
| api_url: base URL of the API. Defaults to ``CALLYOURAI_API_URL`` or | ||
| https://api.callyour.ai. | ||
| conn_options: retry and timeout settings. | ||
| session: an existing aiohttp session to use. | ||
| """ | ||
| key = api_key if utils.is_given(api_key) else os.getenv("CALLYOURAI_API_KEY") | ||
| if not key: | ||
| raise CallyouraiException( | ||
| "api_key must be set by arguments or the CALLYOURAI_API_KEY environment variable" | ||
| ) | ||
| self._api_key = key | ||
| url = api_url if utils.is_given(api_url) else os.getenv("CALLYOURAI_API_URL") | ||
| self._api_url = (url or DEFAULT_API_URL).rstrip("/") | ||
| self._conn_options = conn_options | ||
| self._session = session | ||
|
|
||
| def _http(self) -> aiohttp.ClientSession: | ||
| if self._session is None: | ||
| self._session = utils.http_context.http_session() | ||
| return self._session | ||
|
|
||
| async def create_session( | ||
| self, | ||
| *, | ||
| avatar_id: str, | ||
| livekit_url: str, | ||
| livekit_token: str, | ||
| max_minutes: float | None = None, | ||
| wait_seconds: int = 0, | ||
| hd: bool = False, | ||
| upgrade_from: str | None = None, | ||
| ) -> dict[str, Any]: | ||
| """Start an avatar session. The answer has ``session_id`` and ``status`` | ||
| (``starting``, ``live`` or ``queued`` with ``queue_position``).""" | ||
| body: dict[str, Any] = { | ||
| "avatar_id": avatar_id, | ||
| "livekit_url": livekit_url, | ||
| "livekit_token": livekit_token, | ||
| } | ||
| if max_minutes: | ||
| body["max_minutes"] = max_minutes | ||
| if wait_seconds: | ||
| body["wait_seconds"] = wait_seconds | ||
| if hd: | ||
| body["hd"] = True | ||
| if upgrade_from: | ||
| body["upgrade_from"] = upgrade_from | ||
| return await self._request( | ||
| "POST", | ||
| "/v1/sessions", | ||
| body, | ||
| idempotent=False, | ||
| timeout=max(self._conn_options.timeout, _CREATE_TIMEOUT), | ||
| ) | ||
|
|
||
| async def get_session(self, session_id: str) -> dict[str, Any]: | ||
| return await self._request("GET", f"/v1/sessions/{session_id}") | ||
|
|
||
| async def recover_session( | ||
| self, session_id: str, *, livekit_url: str, livekit_token: str | ||
| ) -> dict[str, Any]: | ||
| """Put a session whose avatar left the room back on another rendering server.""" | ||
| return await self._request( | ||
| "POST", | ||
| f"/v1/sessions/{session_id}/recover", | ||
| {"livekit_url": livekit_url, "livekit_token": livekit_token}, | ||
| ) | ||
|
|
||
| async def end_session(self, session_id: str) -> None: | ||
| await self._request("DELETE", f"/v1/sessions/{session_id}") | ||
|
|
||
| async def _request( | ||
| self, | ||
| method: str, | ||
| path: str, | ||
| body: dict[str, Any] | None = None, | ||
| *, | ||
| idempotent: bool = True, | ||
| timeout: float | None = None, | ||
| ) -> dict[str, Any]: | ||
| """Send a request, retrying failures. | ||
|
|
||
| ``timeout`` (default: ``conn_options.timeout``) bounds the whole request, the body | ||
| included. A request that is not idempotent (creating a session) is only retried | ||
| when the connection could not be opened, so a session is never started twice. | ||
| """ | ||
| total = self._conn_options.timeout if timeout is None else timeout | ||
| for attempt in range(self._conn_options.max_retry + 1): | ||
| try: | ||
| async with self._http().request( | ||
| method, | ||
| self._api_url + path, | ||
| json=body, | ||
| headers={"Authorization": f"Bearer {self._api_key}"}, | ||
| timeout=aiohttp.ClientTimeout( | ||
| total=total, sock_connect=min(total, self._conn_options.timeout) | ||
| ), | ||
| ) as response: | ||
| if response.status >= 400: | ||
| raise await _api_error(response) | ||
| if response.status == 204: | ||
| return {} | ||
| data: dict[str, Any] = await response.json(content_type=None) | ||
| return data | ||
| except CallyouraiAPIError as e: | ||
| if not e.retryable or not idempotent or attempt >= self._conn_options.max_retry: | ||
| raise | ||
| error: Exception = e | ||
| except (aiohttp.ClientConnectorError, aiohttp.ConnectionTimeoutError) as e: | ||
| # nothing was sent: safe to retry any request | ||
| if attempt >= self._conn_options.max_retry: | ||
| raise APIConnectionError(f"could not reach the callyour.ai API: {e}") from e | ||
| error = e | ||
| except asyncio.TimeoutError as e: | ||
| # the server may have accepted the request | ||
| if not idempotent or attempt >= self._conn_options.max_retry: | ||
| raise APITimeoutError("callyour.ai API request timed out") from e | ||
| error = e | ||
| except aiohttp.ClientError as e: | ||
| if not idempotent or attempt >= self._conn_options.max_retry: | ||
| raise APIConnectionError(f"callyour.ai API request failed: {e}") from e | ||
| error = e | ||
| logger.warning( | ||
| "callyour.ai API request failed, retrying", | ||
| extra={"path": path, "attempt": attempt + 1, "error": str(error)}, | ||
| ) | ||
| await asyncio.sleep(self._conn_options.retry_interval) | ||
| raise APIConnectionError("callyour.ai API request failed") # not reached | ||
|
|
||
|
|
||
| async def _api_error(response: aiohttp.ClientResponse) -> CallyouraiAPIError: | ||
| text = await response.text() | ||
| code, message = "http_error", text[:200] | ||
| try: | ||
| error = json.loads(text)["error"] | ||
| code, message = str(error["code"]), str(error["message"]) | ||
| except (ValueError, KeyError, TypeError): | ||
| pass | ||
| return CallyouraiAPIError(message, status_code=response.status, code=code, body=text) | ||
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.
Uh oh!
There was an error while loading. Please reload this page.