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
15 changes: 15 additions & 0 deletions livekit-plugins/livekit-plugins-livetalking/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# LiveTalking plugin for LiveKit Agents

Support for the [LiveTalking](https://github.com/lipku/livetalking) virtual avatar.

See the [LiveTalking integration docs](https://docs.livekit.io/agents/models/avatar/plugins/livetalking/) for more information.

## Installation

```bash
pip install livekit-plugins-livetalking
```

## Pre-requisites

You'll need an API key from [LiveTalking](https://livetalking.top/). It can be set as an environment variable: `LIVETALKING_API_KEY`
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Copyright 2023 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.


from .avatar import AvatarSession
from .version import __version__

__all__ = [
"AvatarSession",
"__version__",
]
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.

from livekit.agents import Plugin

from .log import logger


class LiveTalkingPlugin(Plugin):
def __init__(self) -> None:
super().__init__(__name__, __version__, __package__, logger)


Plugin.register_plugin(LiveTalkingPlugin())
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
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 .log import logger

DEFAULT_API_URL = "https://livetalking.top/api/stream"


class LivetalkingAPI:
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:
livetalking_api_key = api_key or os.getenv("LIVETALKING_API_KEY") or ""
# if livetalking_api_key is None:
# raise Exception("LIVETALKING_API_KEY must be set")
self._api_key = livetalking_api_key # livetalking_api_key

self._api_url = api_url or DEFAULT_API_URL
self._conn_options = conn_options
self._session = session or aiohttp.ClientSession()

async def create_conversation(
self,
*,
avatar_id: NotGivenOr[str] = NOT_GIVEN,
properties: NotGivenOr[dict[str, Any]] = NOT_GIVEN,
extra_payload: NotGivenOr[dict[str, Any]] = NOT_GIVEN,
) -> str:

properties = properties or {}
if avatar_id:
payload = {
"avatar": avatar_id,
# "properties": properties,
}
else:
payload = {}
payload.update(properties)
if utils.is_given(extra_payload):
payload.update(extra_payload)

# if "conversation_name" not in payload:
# payload["conversation_name"] = utils.shortuuid("lk_conversation_")

response_data = await self._post("livekit", payload)
logger.debug(f"create_conversation response: {response_data}")
return response_data.get("data", {}).get("sessionid") # type: ignore

# async def create_persona(
# self,
# name: NotGivenOr[str] = NOT_GIVEN,
# *,
# extra_payload: NotGivenOr[dict[str, Any]] = NOT_GIVEN,
# ) -> str:
# name = name or utils.shortuuid("lk_persona_")

# payload = {
# "persona_name": name,
# "pipeline_mode": "echo",
# "layers": {
# "transport": {"transport_type": "livekit"},
# },
# }

# if utils.is_given(extra_payload):
# payload.update(extra_payload)

# response_data = await self._post("personas", payload)
# return response_data["persona_id"] # type: ignore

async def _post(self, endpoint: str, payload: dict[str, Any]) -> dict[str, Any]:
"""
Make a POST request to the Tavus API with retry logic.

Args:
endpoint: API endpoint path (without leading slash)
payload: JSON payload for the request

Returns:
Response data as a dictionary

Raises:
APIConnectionError: If the request fails after all retries
"""
for i in range(self._conn_options.max_retry):
try:
async with self._session.post(
f"{self._api_url}/{endpoint}",
headers={
"Content-Type": "application/json",
"x-token": 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(
"Server returned an error", status_code=response.status, body=text
)
return await response.json() # type: ignore
except Exception as e:
if isinstance(e, APIConnectionError):
logger.warning("failed to call livetalking api", extra={"error": str(e)})
else:
logger.exception("failed to call livetalking api")

if i < self._conn_options.max_retry - 1:
await asyncio.sleep(self._conn_options.retry_interval)

raise APIConnectionError("Failed to call LiveTalking API after all retries")
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
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 AvatarSession as BaseAvatarSession, DataStreamAudioOutput
from livekit.agents.voice.room_io import ATTRIBUTE_PUBLISH_ON_BEHALF

from .api import LivetalkingAPI
from .log import logger

SAMPLE_RATE = 16000
_AVATAR_AGENT_IDENTITY = "livetalking-avatar-agent"
_AVATAR_AGENT_NAME = "livetalking-avatar-agent"


class AvatarSession(BaseAvatarSession):
"""A Livetalking avatar session"""

def __init__(
self,
*,
avatar_id: NotGivenOr[str] = NOT_GIVEN,
api_url: NotGivenOr[str] = NOT_GIVEN,
api_key: NotGivenOr[str] = NOT_GIVEN,
avatar_participant_identity: NotGivenOr[str] = NOT_GIVEN,
avatar_participant_name: NotGivenOr[str] = NOT_GIVEN,
conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS,
) -> None:
super().__init__()
self._http_session: aiohttp.ClientSession | None = None
self._conn_options = conn_options
self.conversation_id: str | None = None
self._avatar_id = avatar_id
self._api = LivetalkingAPI(
api_url=api_url,
api_key=api_key,
conn_options=conn_options,
session=self._ensure_http_session(),
)

self._avatar_participant_identity = avatar_participant_identity or _AVATAR_AGENT_IDENTITY
self._avatar_participant_name = avatar_participant_name or _AVATAR_AGENT_NAME

@property
def avatar_identity(self) -> str:
return self._avatar_participant_identity

@property
def provider(self) -> str:
return "livetalking"

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:
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
await super().start(agent_session, room)

livekit_url = livekit_url or (os.getenv("LIVEKIT_URL") or NOT_GIVEN)
livekit_api_key = livekit_api_key or (os.getenv("LIVEKIT_API_KEY") or NOT_GIVEN)
livekit_api_secret = livekit_api_secret or (os.getenv("LIVEKIT_API_SECRET") or NOT_GIVEN)
if not livekit_url or not livekit_api_key or not livekit_api_secret:
raise Exception(
"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))
# allow the avatar agent to publish audio and video on behalf of your local agent
.with_attributes({ATTRIBUTE_PUBLISH_ON_BEHALF: local_participant_identity})
.to_jwt()
)

logger.debug("starting avatar session")
self.conversation_id = await self._api.create_conversation(
avatar_id=self._avatar_id,
properties={"livekit_ws_url": livekit_url, "livekit_room_token": livekit_token},
)

agent_session.output.replace_audio_tail(
DataStreamAudioOutput(
room=room,
destination_identity=self._avatar_participant_identity,
sample_rate=SAMPLE_RATE,
wait_remote_track=rtc.TrackKind.KIND_VIDEO,
),
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import logging

logger = logging.getLogger("livekit.plugins.livetalking")
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__ = "2.0.1"
42 changes: 42 additions & 0 deletions livekit-plugins/livekit-plugins-livetalking/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "livekit-plugins-livetalking"
dynamic = ["version"]
description = "Agent Framework plugin for LiveTalking"
readme = "README.md"
license = "Apache-2.0"
requires-python = ">=3.10.0"
authors = [{ name = "LiveKit", email = "support@livekit.io" }]
keywords = ["voice", "ai", "realtime", "audio", "video", "livekit", "webrtc", "livetalking", "avatar"]
classifiers = [
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Topic :: Multimedia :: Sound/Audio",
"Topic :: Multimedia :: Video",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3 :: Only",
]
dependencies = ["livekit-agents>=1.6.7"]

[project.urls]
Documentation = "https://docs.livekit.io"
Website = "https://livekit.io/"
Source = "https://github.com/livekit/agents"

[tool.hatch.version]
path = "livekit/plugins/livetalking/version.py"

[tool.hatch.build.targets.wheel]
packages = ["livekit"]

[tool.hatch.build.targets.sdist]
include = ["/livekit"]

[tool.uv]
exclude-newer = "1 days"
exclude-newer-package = { livekit-agents = "0 days" }