Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions livekit-agents/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ bland = ["livekit-plugins-bland>=1.9.0"]
boson-ai = ["livekit-plugins-boson-ai>=1.9.0"]
boson-avatar = ["livekit-plugins-boson-avatar>=1.9.0"]
browser = ["livekit-plugins-browser>=0.5.0"]
callyourai = ["livekit-plugins-callyourai>=1.9.0"]
cambai = ["livekit-plugins-cambai>=1.9.0"]
cartesia = ["livekit-plugins-cartesia>=1.9.0"]
cerebras = ["livekit-plugins-cerebras>=1.9.0"]
Expand Down
38 changes: 38 additions & 0 deletions livekit-plugins/livekit-plugins-callyourai/README.md
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.
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())
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:
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
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)
Loading
Loading