livekit-plugins-keyframe 1.4.4__py3-none-any.whl

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,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 @@
1
+
@@ -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,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,11 @@
1
+ livekit/plugins/keyframe/__init__.py,sha256=hTb3_6H4v3G1Zoet0fGGpNUJ_AepeEeL_OsvBe6qrqo,1041
2
+ livekit/plugins/keyframe/api.py,sha256=OfvJm9snjQeoOxXC40JBO6TWMw2AEhNkNkI74L94QRs,4177
3
+ livekit/plugins/keyframe/avatar.py,sha256=6dWK0vXtV24bTAuQ7ARweFGXMoxuF8jywm_M_ZuL6Ss,6077
4
+ livekit/plugins/keyframe/errors.py,sha256=CCD-XKfxHeAFkKzl1W6Ixuz7IwM_QqiCXRw1eercNH4,99
5
+ livekit/plugins/keyframe/log.py,sha256=wy2ZsjHZnSJwRrhmFmK5JXppiaP_M_9PvE_nxKIb1og,71
6
+ livekit/plugins/keyframe/py.typed,sha256=Nqnn8clbgv-5l0PgxcTOldg8mkMKrFn4TvPL-rYUUGg,1
7
+ livekit/plugins/keyframe/types.py,sha256=Xi-oJwJIZB4lEY-ZO3X9MPLj8DhVuTLtJMR_kgD9gns,82
8
+ livekit/plugins/keyframe/version.py,sha256=6stz_YFBRP_lguydVylsTgSmj3VTb6WFq8Sp45WYQyY,22
9
+ livekit_plugins_keyframe-1.4.4.dist-info/METADATA,sha256=oYj7LLolXcjiWVAkPpU0ht7xMe69On3w___ogYiaxSQ,1796
10
+ livekit_plugins_keyframe-1.4.4.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
11
+ livekit_plugins_keyframe-1.4.4.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any