livekit-plugins-keyframe 1.4.4__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,179 @@
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
+ # trunk
150
+ .trunk/
151
+
152
+ # Pyre type checker
153
+ .pyre/
154
+
155
+ # pytype static type analyzer
156
+ .pytype/
157
+
158
+ # Cython debug symbols
159
+ cython_debug/
160
+
161
+ # PyCharm
162
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
163
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
164
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
165
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
166
+ .idea/
167
+
168
+ node_modules
169
+
170
+ credentials.json
171
+ pyrightconfig.json
172
+ docs/
173
+
174
+ # Database files
175
+ *.db
176
+
177
+
178
+ # Examples for development
179
+ examples/dev/*
@@ -0,0 +1,57 @@
1
+ Metadata-Version: 2.4
2
+ Name: livekit-plugins-keyframe
3
+ Version: 1.4.4
4
+ Summary: Agent Framework plugin for Keyframe Labs avatars
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: ai,audio,avatar,livekit,realtime,video,voice,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.10
16
+ Classifier: Topic :: Multimedia :: Sound/Audio
17
+ Classifier: Topic :: Multimedia :: Video
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Requires-Python: >=3.10.0
20
+ Requires-Dist: livekit-agents>=1.4.4
21
+ Description-Content-Type: text/markdown
22
+
23
+ # livekit-plugins-keyframe
24
+
25
+ Agent Framework plugin for [Keyframe Labs](https://keyframelabs.com) avatars.
26
+
27
+ ## Installation
28
+
29
+ ```bash
30
+ pip install livekit-plugins-keyframe
31
+ ```
32
+
33
+ ## Usage
34
+
35
+ ```python
36
+ from livekit.agents import AgentSession
37
+ from livekit.plugins import keyframe
38
+
39
+ session = AgentSession(stt=..., llm=..., tts=...)
40
+
41
+ avatar = keyframe.AvatarSession(
42
+ persona_id="ab85a2a0-0555-428d-87b2-ff3019a58b93", # or persona_slug="public:cosmo_persona-1.5-live"
43
+ api_key="keyframe_sk_live_...", # or set KEYFRAME_API_KEY env var
44
+ )
45
+
46
+ await avatar.start(session, room=ctx.room)
47
+ await session.start(room=ctx.room, agent=my_agent)
48
+ ```
49
+
50
+ ## Authentication
51
+
52
+ Set the following environment variables:
53
+
54
+ - `KEYFRAME_API_KEY` - Your Keyframe API key
55
+ - `LIVEKIT_URL` - LiveKit server URL
56
+ - `LIVEKIT_API_KEY` - LiveKit API key
57
+ - `LIVEKIT_API_SECRET` - LiveKit API secret
@@ -0,0 +1,35 @@
1
+ # livekit-plugins-keyframe
2
+
3
+ Agent Framework plugin for [Keyframe Labs](https://keyframelabs.com) avatars.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install livekit-plugins-keyframe
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```python
14
+ from livekit.agents import AgentSession
15
+ from livekit.plugins import keyframe
16
+
17
+ session = AgentSession(stt=..., llm=..., tts=...)
18
+
19
+ avatar = keyframe.AvatarSession(
20
+ persona_id="ab85a2a0-0555-428d-87b2-ff3019a58b93", # or persona_slug="public:cosmo_persona-1.5-live"
21
+ api_key="keyframe_sk_live_...", # or set KEYFRAME_API_KEY env var
22
+ )
23
+
24
+ await avatar.start(session, room=ctx.room)
25
+ await session.start(room=ctx.room, agent=my_agent)
26
+ ```
27
+
28
+ ## Authentication
29
+
30
+ Set the following environment variables:
31
+
32
+ - `KEYFRAME_API_KEY` - Your Keyframe API key
33
+ - `LIVEKIT_URL` - LiveKit server URL
34
+ - `LIVEKIT_API_KEY` - LiveKit API key
35
+ - `LIVEKIT_API_SECRET` - LiveKit API secret
@@ -0,0 +1,37 @@
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
+ from .avatar import AvatarSession
16
+ from .errors import KeyframeException
17
+ from .types import Emotion
18
+ from .version import __version__
19
+
20
+ __all__ = [
21
+ "AvatarSession",
22
+ "Emotion",
23
+ "KeyframeException",
24
+ "__version__",
25
+ ]
26
+
27
+ from livekit.agents import Plugin
28
+
29
+ from .log import logger
30
+
31
+
32
+ class KeyframePlugin(Plugin):
33
+ def __init__(self) -> None:
34
+ super().__init__(__name__, __version__, __package__, logger)
35
+
36
+
37
+ Plugin.register_plugin(KeyframePlugin())
@@ -0,0 +1,119 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from typing import Any
5
+
6
+ import aiohttp
7
+
8
+ from livekit.agents import (
9
+ DEFAULT_API_CONNECT_OPTIONS,
10
+ APIConnectionError,
11
+ APIConnectOptions,
12
+ APIStatusError,
13
+ )
14
+
15
+ from .log import logger
16
+
17
+ DEFAULT_API_URL = "https://api.keyframelabs.com"
18
+
19
+
20
+ class KeyframeAPI:
21
+ """Asynchronous client for the Keyframe Labs session API."""
22
+
23
+ def __init__(
24
+ self,
25
+ api_key: str,
26
+ api_url: str,
27
+ *,
28
+ conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS,
29
+ session: aiohttp.ClientSession | None = None,
30
+ ) -> None:
31
+ self._api_key = api_key
32
+ self._api_url = api_url
33
+ self._conn_options = conn_options
34
+ self._session = session
35
+ self._own_session = session is None
36
+
37
+ async def __aenter__(self) -> KeyframeAPI:
38
+ if self._own_session:
39
+ self._session = aiohttp.ClientSession()
40
+ return self
41
+
42
+ async def __aexit__(
43
+ self, exc_type: type | None, exc_val: Exception | None, exc_tb: Any
44
+ ) -> None:
45
+ if self._own_session and self._session and not self._session.closed:
46
+ await self._session.close()
47
+
48
+ async def create_plugin_session(
49
+ self,
50
+ *,
51
+ persona_id: str | None = None,
52
+ persona_slug: str | None = None,
53
+ room_name: str,
54
+ livekit_url: str,
55
+ livekit_token: str,
56
+ source_participant_identity: str,
57
+ ) -> dict[str, Any]:
58
+ """Create a plugin session via POST /v1/sessions/plugins/livekit.
59
+
60
+ Returns dict with reservation_id and avatar_participant_identity.
61
+ """
62
+ payload: dict[str, Any] = {
63
+ "room_name": room_name,
64
+ "livekit_url": livekit_url,
65
+ "livekit_token": livekit_token,
66
+ "source_participant_identity": source_participant_identity,
67
+ }
68
+ if persona_id:
69
+ payload["persona_id"] = persona_id
70
+ if persona_slug:
71
+ payload["persona_slug"] = persona_slug
72
+
73
+ headers = {
74
+ "Authorization": f"Bearer {self._api_key}",
75
+ "Content-Type": "application/json",
76
+ }
77
+ return await self._post("/v1/sessions/plugins/livekit", payload, headers)
78
+
79
+ async def _post(
80
+ self, endpoint: str, payload: dict[str, Any], headers: dict[str, str]
81
+ ) -> dict[str, Any]:
82
+ url = f"{self._api_url}{endpoint}"
83
+ session = self._session or aiohttp.ClientSession()
84
+ try:
85
+ for i in range(self._conn_options.max_retry + 1):
86
+ try:
87
+ async with session.post(
88
+ url,
89
+ headers=headers,
90
+ json=payload,
91
+ timeout=aiohttp.ClientTimeout(sock_connect=self._conn_options.timeout),
92
+ ) as response:
93
+ if not response.ok:
94
+ text = await response.text()
95
+ raise APIStatusError(
96
+ f"Keyframe API error for {url}: {response.status}",
97
+ status_code=response.status,
98
+ body=text,
99
+ )
100
+ return await response.json() # type: ignore
101
+ except Exception as e:
102
+ if isinstance(e, APIStatusError) and not e.retryable:
103
+ raise APIConnectionError(
104
+ f"Failed to call Keyframe API at {url} with non-retryable error",
105
+ retryable=False,
106
+ ) from e
107
+
108
+ if isinstance(e, APIConnectionError):
109
+ logger.warning("Failed to call Keyframe API", extra={"error": str(e)})
110
+ else:
111
+ logger.exception("Failed to call Keyframe API")
112
+
113
+ if i < self._conn_options.max_retry:
114
+ await asyncio.sleep(self._conn_options._interval_for_retry(i))
115
+ finally:
116
+ if not self._session:
117
+ await session.close()
118
+
119
+ raise APIConnectionError("Failed to call Keyframe API after all retries.")
@@ -0,0 +1,172 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+
5
+ from livekit import api, rtc
6
+ from livekit.agents import (
7
+ DEFAULT_API_CONNECT_OPTIONS,
8
+ NOT_GIVEN,
9
+ AgentSession,
10
+ APIConnectOptions,
11
+ NotGivenOr,
12
+ get_job_context,
13
+ utils,
14
+ )
15
+ from livekit.agents.voice.avatar import DataStreamAudioOutput
16
+ from livekit.agents.voice.room_io import ATTRIBUTE_PUBLISH_ON_BEHALF
17
+
18
+ from .api import DEFAULT_API_URL, KeyframeAPI
19
+ from .errors import KeyframeException
20
+ from .log import logger
21
+ from .types import Emotion
22
+
23
+ SAMPLE_RATE = 24000
24
+ CONTROL_TOPIC = "lk.control"
25
+ _AVATAR_AGENT_IDENTITY = "keyframe-avatar-agent"
26
+ _AVATAR_AGENT_NAME = "keyframe-avatar-agent"
27
+
28
+
29
+ class AvatarSession:
30
+ """A Keyframe avatar session for the LiveKit Agents framework."""
31
+
32
+ def __init__(
33
+ self,
34
+ *,
35
+ persona_id: NotGivenOr[str] = NOT_GIVEN,
36
+ persona_slug: NotGivenOr[str] = NOT_GIVEN,
37
+ api_url: NotGivenOr[str] = NOT_GIVEN,
38
+ api_key: NotGivenOr[str] = NOT_GIVEN,
39
+ avatar_participant_identity: NotGivenOr[str] = NOT_GIVEN,
40
+ avatar_participant_name: NotGivenOr[str] = NOT_GIVEN,
41
+ conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS,
42
+ ) -> None:
43
+ self._room: rtc.Room | None = None
44
+ self._conn_options = conn_options
45
+ self._avatar_participant_identity = (
46
+ avatar_participant_identity
47
+ if utils.is_given(avatar_participant_identity)
48
+ else _AVATAR_AGENT_IDENTITY
49
+ )
50
+ self._avatar_participant_name = (
51
+ avatar_participant_name
52
+ if utils.is_given(avatar_participant_name)
53
+ else _AVATAR_AGENT_NAME
54
+ )
55
+
56
+ # Resolve persona
57
+ has_id = utils.is_given(persona_id)
58
+ has_slug = utils.is_given(persona_slug)
59
+ if has_id == has_slug:
60
+ raise KeyframeException("Provide exactly one of persona_id or persona_slug")
61
+
62
+ self._persona_id: str | None = None
63
+ self._persona_slug: str | None = None
64
+ if utils.is_given(persona_id):
65
+ self._persona_id = persona_id
66
+ if utils.is_given(persona_slug):
67
+ self._persona_slug = persona_slug
68
+
69
+ # Resolve API config
70
+ api_url_val = (
71
+ api_url if utils.is_given(api_url) else os.getenv("KEYFRAME_API_URL", DEFAULT_API_URL)
72
+ )
73
+ api_key_val = api_key if utils.is_given(api_key) else os.getenv("KEYFRAME_API_KEY")
74
+
75
+ if not api_key_val:
76
+ raise KeyframeException(
77
+ "KEYFRAME_API_KEY must be set by arguments or environment variables"
78
+ )
79
+
80
+ self._api_url = api_url_val
81
+ self._api_key = api_key_val
82
+
83
+ async def start(
84
+ self,
85
+ agent_session: AgentSession,
86
+ room: rtc.Room,
87
+ *,
88
+ livekit_url: NotGivenOr[str] = NOT_GIVEN,
89
+ livekit_api_key: NotGivenOr[str] = NOT_GIVEN,
90
+ livekit_api_secret: NotGivenOr[str] = NOT_GIVEN,
91
+ ) -> None:
92
+ livekit_url = livekit_url or (os.getenv("LIVEKIT_URL") or NOT_GIVEN)
93
+ livekit_api_key = livekit_api_key or (os.getenv("LIVEKIT_API_KEY") or NOT_GIVEN)
94
+ livekit_api_secret = livekit_api_secret or (os.getenv("LIVEKIT_API_SECRET") or NOT_GIVEN)
95
+ if not livekit_url or not livekit_api_key or not livekit_api_secret:
96
+ raise KeyframeException(
97
+ "livekit_url, livekit_api_key, and livekit_api_secret must be set "
98
+ "by arguments or environment variables"
99
+ )
100
+
101
+ job_ctx = get_job_context()
102
+ local_participant_identity = job_ctx.local_participant_identity
103
+
104
+ # Mint a LiveKit token for the avatar worker with publish_on_behalf
105
+ livekit_token = (
106
+ api.AccessToken(
107
+ api_key=livekit_api_key,
108
+ api_secret=livekit_api_secret,
109
+ )
110
+ .with_kind("agent")
111
+ .with_identity(self._avatar_participant_identity)
112
+ .with_name(self._avatar_participant_name)
113
+ .with_grants(
114
+ api.VideoGrants(
115
+ room_join=True,
116
+ room=room.name,
117
+ can_publish=True,
118
+ can_subscribe=True,
119
+ )
120
+ )
121
+ .with_attributes({ATTRIBUTE_PUBLISH_ON_BEHALF: local_participant_identity})
122
+ .to_jwt()
123
+ )
124
+
125
+ # Call API to create a reservation and dispatch
126
+ async with KeyframeAPI(
127
+ api_key=self._api_key,
128
+ api_url=self._api_url,
129
+ conn_options=self._conn_options,
130
+ ) as keyframe_api:
131
+ result = await keyframe_api.create_plugin_session(
132
+ persona_id=self._persona_id,
133
+ persona_slug=self._persona_slug,
134
+ room_name=room.name,
135
+ livekit_url=livekit_url,
136
+ livekit_token=livekit_token,
137
+ source_participant_identity=local_participant_identity,
138
+ )
139
+ logger.debug(
140
+ "Keyframe plugin session created: reservation_id=%s",
141
+ result.get("reservation_id"),
142
+ )
143
+
144
+ self._room = room
145
+
146
+ agent_session.output.audio = DataStreamAudioOutput(
147
+ room=room,
148
+ destination_identity=self._avatar_participant_identity,
149
+ sample_rate=SAMPLE_RATE,
150
+ wait_remote_track=rtc.TrackKind.KIND_VIDEO,
151
+ clear_buffer_timeout=None,
152
+ )
153
+
154
+ async def set_emotion(self, emotion: Emotion) -> None:
155
+ """Set the avatar's emotional expression.
156
+
157
+ Sends a control message to the avatar worker to change its facial
158
+ expression and demeanor.
159
+
160
+ Args:
161
+ emotion: The emotion to express ('neutral', 'happy', 'sad', 'angry').
162
+ """
163
+ if self._room is None:
164
+ logger.warning("set_emotion() called before start()")
165
+ return
166
+
167
+ await self._room.local_participant.publish_data(
168
+ f"emotion:{emotion}".encode(),
169
+ reliable=False,
170
+ topic=CONTROL_TOPIC,
171
+ destination_identities=[self._avatar_participant_identity],
172
+ )
@@ -0,0 +1,4 @@
1
+ class KeyframeException(Exception):
2
+ """Base exception for Keyframe plugin errors."""
3
+
4
+ pass
@@ -0,0 +1,3 @@
1
+ import logging
2
+
3
+ logger = logging.getLogger("livekit.plugins.keyframe")
@@ -0,0 +1,3 @@
1
+ from typing import Literal
2
+
3
+ Emotion = Literal["neutral", "happy", "sad", "angry"]
@@ -0,0 +1 @@
1
+ __version__ = "1.4.4"
@@ -0,0 +1,38 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "livekit-plugins-keyframe"
7
+ dynamic = ["version"]
8
+ description = "Agent Framework plugin for Keyframe Labs avatars"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.10.0"
12
+ authors = [{ name = "LiveKit", email = "support@livekit.io" }]
13
+ keywords = ["voice", "ai", "realtime", "audio", "video", "livekit", "webrtc", "avatar"]
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.10",
22
+ "Programming Language :: Python :: 3 :: Only",
23
+ ]
24
+ dependencies = ["livekit-agents>=1.4.4"]
25
+
26
+ [project.urls]
27
+ Documentation = "https://docs.livekit.io"
28
+ Website = "https://livekit.io/"
29
+ Source = "https://github.com/livekit/agents"
30
+
31
+ [tool.hatch.version]
32
+ path = "livekit/plugins/keyframe/version.py"
33
+
34
+ [tool.hatch.build.targets.wheel]
35
+ packages = ["livekit"]
36
+
37
+ [tool.hatch.build.targets.sdist]
38
+ include = ["/livekit"]