livekit-plugins-tavus 1.0.17__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,168 @@
1
+ **/.vscode
2
+ **/.DS_Store
3
+
4
+ # Byte-compiled / optimized / DLL files
5
+ __pycache__/
6
+ *.py[cod]
7
+ *$py.class
8
+
9
+ # C extensions
10
+ *.so
11
+
12
+ # Distribution / packaging
13
+ .Python
14
+ build/
15
+ develop-eggs/
16
+ dist/
17
+ downloads/
18
+ eggs/
19
+ .eggs/
20
+ lib/
21
+ lib64/
22
+ parts/
23
+ sdist/
24
+ var/
25
+ wheels/
26
+ share/python-wheels/
27
+ *.egg-info/
28
+ .installed.cfg
29
+ *.egg
30
+ MANIFEST
31
+
32
+ # PyInstaller
33
+ # Usually these files are written by a python script from a template
34
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
35
+ *.manifest
36
+ *.spec
37
+
38
+ # Installer logs
39
+ pip-log.txt
40
+ pip-delete-this-directory.txt
41
+
42
+ # Unit test / coverage reports
43
+ htmlcov/
44
+ .tox/
45
+ .nox/
46
+ .coverage
47
+ .coverage.*
48
+ .cache
49
+ nosetests.xml
50
+ coverage.xml
51
+ *.cover
52
+ *.py,cover
53
+ .hypothesis/
54
+ .pytest_cache/
55
+ cover/
56
+
57
+ # Translations
58
+ *.mo
59
+ *.pot
60
+
61
+ # Django stuff:
62
+ *.log
63
+ local_settings.py
64
+ db.sqlite3
65
+ db.sqlite3-journal
66
+
67
+ # Flask stuff:
68
+ instance/
69
+ .webassets-cache
70
+
71
+ # Scrapy stuff:
72
+ .scrapy
73
+
74
+ # Sphinx documentation
75
+ docs/_build/
76
+
77
+ # PyBuilder
78
+ .pybuilder/
79
+ target/
80
+
81
+ # Jupyter Notebook
82
+ .ipynb_checkpoints
83
+
84
+ # IPython
85
+ profile_default/
86
+ ipython_config.py
87
+
88
+ # pyenv
89
+ # For a library or package, you might want to ignore these files since the code is
90
+ # intended to run in multiple environments; otherwise, check them in:
91
+ # .python-version
92
+
93
+ # pipenv
94
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
95
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
96
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
97
+ # install all needed dependencies.
98
+ #Pipfile.lock
99
+
100
+ # poetry
101
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
102
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
103
+ # commonly ignored for libraries.
104
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
105
+ #poetry.lock
106
+
107
+ # pdm
108
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
109
+ #pdm.lock
110
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
111
+ # in version control.
112
+ # https://pdm.fming.dev/#use-with-ide
113
+ .pdm.toml
114
+
115
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
116
+ __pypackages__/
117
+
118
+ # Celery stuff
119
+ celerybeat-schedule
120
+ celerybeat.pid
121
+
122
+ # SageMath parsed files
123
+ *.sage.py
124
+
125
+ # Environments
126
+ .env
127
+ .venv
128
+ env/
129
+ venv/
130
+ ENV/
131
+ env.bak/
132
+ venv.bak/
133
+
134
+ # Spyder project settings
135
+ .spyderproject
136
+ .spyproject
137
+
138
+ # Rope project settings
139
+ .ropeproject
140
+
141
+ # mkdocs documentation
142
+ /site
143
+
144
+ # mypy
145
+ .mypy_cache/
146
+ .dmypy.json
147
+ dmypy.json
148
+
149
+ # Pyre type checker
150
+ .pyre/
151
+
152
+ # pytype static type analyzer
153
+ .pytype/
154
+
155
+ # Cython debug symbols
156
+ cython_debug/
157
+
158
+ # PyCharm
159
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
160
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
161
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
162
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
163
+ .idea/
164
+
165
+ node_modules
166
+
167
+ credentials.json
168
+ pyrightconfig.json
@@ -0,0 +1,21 @@
1
+ Metadata-Version: 2.4
2
+ Name: livekit-plugins-tavus
3
+ Version: 1.0.17
4
+ Summary: Agent Framework plugin for Tavus
5
+ Project-URL: Documentation, https://docs.livekit.io
6
+ Project-URL: Website, https://livekit.io/
7
+ Project-URL: Source, https://github.com/livekit/agents
8
+ Author-email: LiveKit <support@livekit.io>
9
+ License-Expression: Apache-2.0
10
+ Keywords: audio,livekit,realtime,video,webrtc
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Topic :: Multimedia :: Sound/Audio
18
+ Classifier: Topic :: Multimedia :: Video
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Requires-Python: >=3.9.0
21
+ Requires-Dist: livekit-agents>=1.0.17
File without changes
@@ -0,0 +1,35 @@
1
+ # Copyright 2023 LiveKit, Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from .avatar import AvatarSession, TavusException
17
+ from .version import __version__
18
+
19
+ __all__ = [
20
+ "TavusException",
21
+ "AvatarSession",
22
+ "__version__",
23
+ ]
24
+
25
+ from livekit.agents import Plugin
26
+
27
+ from .log import logger
28
+
29
+
30
+ class TavusPlugin(Plugin):
31
+ def __init__(self) -> None:
32
+ super().__init__(__name__, __version__, __package__, logger)
33
+
34
+
35
+ Plugin.register_plugin(TavusPlugin())
@@ -0,0 +1,139 @@
1
+ import asyncio
2
+ import os
3
+ from typing import Any, cast
4
+
5
+ import aiohttp
6
+
7
+ from livekit.agents import (
8
+ DEFAULT_API_CONNECT_OPTIONS,
9
+ NOT_GIVEN,
10
+ APIConnectionError,
11
+ APIConnectOptions,
12
+ APIStatusError,
13
+ NotGivenOr,
14
+ utils,
15
+ )
16
+
17
+ from .log import logger
18
+
19
+
20
+ class TavusException(Exception):
21
+ """Exception for Tavus errors"""
22
+
23
+
24
+ DEFAULT_API_URL = "https://tavusapi.com/v2"
25
+
26
+
27
+ class TavusAPI:
28
+ def __init__(
29
+ self,
30
+ api_key: NotGivenOr[str] = NOT_GIVEN,
31
+ api_url: NotGivenOr[str] = NOT_GIVEN,
32
+ *,
33
+ conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS,
34
+ session: aiohttp.ClientSession | None = None,
35
+ ) -> None:
36
+ self._api_key = api_key or os.getenv("TAVUS_API_KEY")
37
+ if self._api_key is None:
38
+ raise TavusException("TAVUS_API_KEY must be set")
39
+ self._api_key = cast(str, self._api_key)
40
+
41
+ self._api_url = api_url or DEFAULT_API_URL
42
+ self._conn_options = conn_options
43
+ self._session = session or aiohttp.ClientSession()
44
+
45
+ async def create_conversation(
46
+ self,
47
+ *,
48
+ replica_id: NotGivenOr[str] = NOT_GIVEN,
49
+ persona_id: NotGivenOr[str] = NOT_GIVEN,
50
+ properties: NotGivenOr[dict[str, Any]] = NOT_GIVEN,
51
+ extra_payload: NotGivenOr[dict[str, Any]] = NOT_GIVEN,
52
+ ) -> str:
53
+ replica_id = replica_id or os.getenv("TAVUS_REPLICA_ID")
54
+ if not replica_id:
55
+ raise TavusException("TAVUS_REPLICA_ID must be set")
56
+
57
+ persona_id = persona_id or os.getenv("TAVUS_PERSONA_ID")
58
+ if not persona_id:
59
+ # create a persona if not provided
60
+ persona_id = await self.create_persona()
61
+
62
+ properties = properties or {}
63
+ payload = {
64
+ "replica_id": replica_id,
65
+ "persona_id": persona_id,
66
+ "properties": properties,
67
+ }
68
+ if utils.is_given(extra_payload):
69
+ payload.update(extra_payload)
70
+
71
+ if "conversation_name" not in payload:
72
+ payload["conversation_name"] = utils.shortuuid("lk_conversation_")
73
+
74
+ response_data = await self._post("conversations", payload)
75
+ return response_data["conversation_id"]
76
+
77
+ async def create_persona(
78
+ self,
79
+ name: NotGivenOr[str] = NOT_GIVEN,
80
+ *,
81
+ extra_payload: NotGivenOr[dict[str, Any]] = NOT_GIVEN,
82
+ ) -> str:
83
+ name = name or utils.shortuuid("lk_persona_")
84
+
85
+ payload = {
86
+ "persona_name": name,
87
+ "pipeline_mode": "echo",
88
+ "layers": {
89
+ "transport": {"transport_type": "livekit"},
90
+ },
91
+ }
92
+
93
+ if utils.is_given(extra_payload):
94
+ payload.update(extra_payload)
95
+
96
+ response_data = await self._post("personas", payload)
97
+ return response_data["persona_id"]
98
+
99
+ async def _post(self, endpoint: str, payload: dict[str, Any]) -> dict[str, Any]:
100
+ """
101
+ Make a POST request to the Tavus API with retry logic.
102
+
103
+ Args:
104
+ endpoint: API endpoint path (without leading slash)
105
+ payload: JSON payload for the request
106
+
107
+ Returns:
108
+ Response data as a dictionary
109
+
110
+ Raises:
111
+ APIConnectionError: If the request fails after all retries
112
+ """
113
+ for i in range(self._conn_options.max_retry):
114
+ try:
115
+ async with self._session.post(
116
+ f"{self._api_url}/{endpoint}",
117
+ headers={
118
+ "Content-Type": "application/json",
119
+ "x-api-key": self._api_key,
120
+ },
121
+ json=payload,
122
+ timeout=self._conn_options.timeout,
123
+ ) as response:
124
+ if not response.ok:
125
+ text = await response.text()
126
+ raise APIStatusError(
127
+ "Server returned an error", status_code=response.status, body=text
128
+ )
129
+ return await response.json()
130
+ except Exception as e:
131
+ if isinstance(e, APIConnectionError):
132
+ logger.warning("failed to call tavus api", extra={"error": str(e)})
133
+ else:
134
+ logger.exception("failed to call tavus api")
135
+
136
+ if i < self._conn_options.max_retry - 1:
137
+ await asyncio.sleep(self._conn_options.retry_interval)
138
+
139
+ raise APIConnectionError("Failed to call Tavus API after all retries")
@@ -0,0 +1,105 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+
5
+ import aiohttp
6
+
7
+ from livekit import api, rtc
8
+ from livekit.agents import (
9
+ DEFAULT_API_CONNECT_OPTIONS,
10
+ NOT_GIVEN,
11
+ AgentSession,
12
+ APIConnectOptions,
13
+ NotGivenOr,
14
+ utils,
15
+ )
16
+ from livekit.agents.voice.avatar import DataStreamAudioOutput
17
+ from livekit.agents.voice.room_io import ATTRIBUTE_PUBLISH_ON_BEHALF
18
+
19
+ from .api import TavusAPI, TavusException
20
+ from .log import logger
21
+
22
+ SAMPLE_RATE = 24000
23
+ _AVATAR_AGENT_IDENTITY = "tavus-avatar-agent"
24
+ _AVATAR_AGENT_NAME = "tavus-avatar-agent"
25
+
26
+
27
+ class AvatarSession:
28
+ """A Tavus avatar session"""
29
+
30
+ def __init__(
31
+ self,
32
+ *,
33
+ replica_id: NotGivenOr[str] = NOT_GIVEN,
34
+ persona_id: NotGivenOr[str] = NOT_GIVEN,
35
+ api_url: NotGivenOr[str] = NOT_GIVEN,
36
+ api_key: NotGivenOr[str] = NOT_GIVEN,
37
+ avatar_participant_identity: NotGivenOr[str] = NOT_GIVEN,
38
+ avatar_participant_name: NotGivenOr[str] = NOT_GIVEN,
39
+ conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS,
40
+ ) -> None:
41
+ self._http_session: aiohttp.ClientSession | None = None
42
+ self._conn_options = conn_options
43
+
44
+ self._persona_id = persona_id
45
+ self._replica_id = replica_id
46
+ self._api = TavusAPI(
47
+ api_url=api_url,
48
+ api_key=api_key,
49
+ conn_options=conn_options,
50
+ session=self._ensure_http_session(),
51
+ )
52
+
53
+ self._avatar_participant_identity = avatar_participant_identity or _AVATAR_AGENT_IDENTITY
54
+ self._avatar_participant_name = avatar_participant_name or _AVATAR_AGENT_NAME
55
+
56
+ def _ensure_http_session(self) -> aiohttp.ClientSession:
57
+ if self._http_session is None:
58
+ self._http_session = utils.http_context.http_session()
59
+
60
+ return self._http_session
61
+
62
+ async def start(
63
+ self,
64
+ agent_session: AgentSession,
65
+ room: rtc.Room,
66
+ *,
67
+ livekit_url: NotGivenOr[str] = NOT_GIVEN,
68
+ livekit_api_key: NotGivenOr[str] = NOT_GIVEN,
69
+ livekit_api_secret: NotGivenOr[str] = NOT_GIVEN,
70
+ ) -> None:
71
+ livekit_url = livekit_url or os.getenv("LIVEKIT_URL")
72
+ livekit_api_key = livekit_api_key or os.getenv("LIVEKIT_API_KEY")
73
+ livekit_api_secret = livekit_api_secret or os.getenv("LIVEKIT_API_SECRET")
74
+ if not livekit_url or not livekit_api_key or not livekit_api_secret:
75
+ raise TavusException(
76
+ "livekit_url, livekit_api_key, and livekit_api_secret must be set "
77
+ "by arguments or environment variables"
78
+ )
79
+
80
+ livekit_token = (
81
+ api.AccessToken()
82
+ .with_kind("agent")
83
+ .with_identity(self._avatar_participant_identity)
84
+ .with_name(self._avatar_participant_name)
85
+ .with_grants(api.VideoGrants(room_join=True, room=room.name))
86
+ # allow the avatar agent to publish audio and video on behalf of your local agent
87
+ .with_attributes({ATTRIBUTE_PUBLISH_ON_BEHALF: room.local_participant.identity})
88
+ .to_jwt()
89
+ )
90
+
91
+ logger.debug("starting avatar session")
92
+ await self._api.create_conversation(
93
+ persona_id=self._persona_id,
94
+ replica_id=self._replica_id,
95
+ properties={"livekit_ws_url": livekit_url, "livekit_room_token": livekit_token},
96
+ )
97
+
98
+ logger.debug("waiting for avatar agent to join the room")
99
+ await utils.wait_for_participant(room=room, identity=self._avatar_participant_identity)
100
+
101
+ agent_session.output.audio = DataStreamAudioOutput(
102
+ room=room,
103
+ destination_identity=self._avatar_participant_identity,
104
+ sample_rate=SAMPLE_RATE,
105
+ )
@@ -0,0 +1,3 @@
1
+ import logging
2
+
3
+ logger = logging.getLogger("livekit.plugins.tavus")
@@ -0,0 +1,15 @@
1
+ # Copyright 2025 LiveKit, Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ __version__ = "1.0.17"
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "livekit-plugins-tavus"
7
+ dynamic = ["version"]
8
+ description = "Agent Framework plugin for Tavus"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.9.0"
12
+ authors = [{ name = "LiveKit", email = "support@livekit.io" }]
13
+ keywords = ["webrtc", "realtime", "audio", "video", "livekit"]
14
+ classifiers = [
15
+ "Intended Audience :: Developers",
16
+ "License :: OSI Approved :: Apache Software License",
17
+ "Topic :: Multimedia :: Sound/Audio",
18
+ "Topic :: Multimedia :: Video",
19
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.9",
22
+ "Programming Language :: Python :: 3.10",
23
+ "Programming Language :: Python :: 3 :: Only",
24
+ ]
25
+ dependencies = ["livekit-agents>=1.0.17"]
26
+
27
+ [project.urls]
28
+ Documentation = "https://docs.livekit.io"
29
+ Website = "https://livekit.io/"
30
+ Source = "https://github.com/livekit/agents"
31
+
32
+ [tool.hatch.version]
33
+ path = "livekit/plugins/tavus/version.py"
34
+
35
+ [tool.hatch.build.targets.wheel]
36
+ packages = ["livekit"]
37
+
38
+ [tool.hatch.build.targets.sdist]
39
+ include = ["/livekit"]