livekit-plugins-protoface 1.0.0__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,10 @@
1
+ .DS_Store
2
+ .pytest_cache/
3
+ .ruff_cache/
4
+ .venv/
5
+ .smoke-venv/
6
+ __pycache__/
7
+ *.egg-info/
8
+ *.pyc
9
+ dist/
10
+ build/
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,38 @@
1
+ Metadata-Version: 2.4
2
+ Name: livekit-plugins-protoface
3
+ Version: 1.0.0
4
+ Summary: Agent Framework plugin for Protoface avatar
5
+ Project-URL: Documentation, https://docs.protoface.com
6
+ Project-URL: Website, https://protoface.com/
7
+ Project-URL: Source, https://github.com/protoface-ai/livekit-plugins-protoface
8
+ Author-email: Protoface Team <info@protoface.com>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: ai,audio,avatar,livekit,protoface,realtime,video,voice
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
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.10.0
21
+ Requires-Dist: livekit-agents>=1.6.1
22
+ Description-Content-Type: text/markdown
23
+
24
+ # Protoface plugin for LiveKit Agents
25
+
26
+ Support for the [Protoface](https://protoface.com/) virtual avatar.
27
+
28
+ See the [Protoface docs](https://docs.protoface.com/) for more information.
29
+
30
+ ## Installation
31
+
32
+ ```bash
33
+ pip install livekit-plugins-protoface
34
+ ```
35
+
36
+ ## Pre-requisites
37
+
38
+ You'll need an API key from Protoface. It can be set as an environment variable: `PROTOFACE_API_KEY`
@@ -0,0 +1,15 @@
1
+ # Protoface plugin for LiveKit Agents
2
+
3
+ Support for the [Protoface](https://protoface.com/) virtual avatar.
4
+
5
+ See the [Protoface docs](https://docs.protoface.com/) for more information.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ pip install livekit-plugins-protoface
11
+ ```
12
+
13
+ ## Pre-requisites
14
+
15
+ You'll need an API key from Protoface. It can be set as an environment variable: `PROTOFACE_API_KEY`
@@ -0,0 +1,24 @@
1
+ """Protoface avatar plugin for LiveKit Agents."""
2
+
3
+ from .avatar import DEFAULT_STOCK_AVATAR_ID, AvatarSession
4
+ from .errors import ProtofaceException
5
+ from .version import __version__
6
+
7
+ __all__ = [
8
+ "DEFAULT_STOCK_AVATAR_ID",
9
+ "AvatarSession",
10
+ "ProtofaceException",
11
+ "__version__",
12
+ ]
13
+
14
+ from livekit.agents import Plugin
15
+
16
+ from .log import logger
17
+
18
+
19
+ class ProtofacePlugin(Plugin):
20
+ def __init__(self) -> None:
21
+ super().__init__(__name__, __version__, __package__, logger)
22
+
23
+
24
+ Plugin.register_plugin(ProtofacePlugin())
@@ -0,0 +1,199 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import os
5
+ from typing import Any
6
+
7
+ import aiohttp
8
+
9
+ from livekit.agents import (
10
+ DEFAULT_API_CONNECT_OPTIONS,
11
+ NOT_GIVEN,
12
+ APIConnectionError,
13
+ APIConnectOptions,
14
+ APIStatusError,
15
+ APITimeoutError,
16
+ NotGivenOr,
17
+ utils,
18
+ )
19
+
20
+ from .errors import ProtofaceException
21
+ from .log import logger
22
+ from .version import __version__
23
+
24
+ DEFAULT_API_URL = "https://api.protoface.com"
25
+ _USER_AGENT = f"livekit-plugins-protoface/{__version__}"
26
+
27
+
28
+ class ProtofaceAPI:
29
+ """Async client for the Protoface session API."""
30
+
31
+ def __init__(
32
+ self,
33
+ *,
34
+ api_key: NotGivenOr[str | None] = NOT_GIVEN,
35
+ api_url: NotGivenOr[str | None] = NOT_GIVEN,
36
+ conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS,
37
+ session: aiohttp.ClientSession | None = None,
38
+ ) -> None:
39
+ """Create a Protoface API client.
40
+
41
+ Args:
42
+ api_key: Protoface API key. Defaults to the `PROTOFACE_API_KEY`
43
+ environment variable.
44
+ api_url: Protoface API base URL. Defaults to `PROTOFACE_API_URL` or
45
+ `https://api.protoface.com`.
46
+ conn_options: Timeout and retry settings for API calls.
47
+ session: Optional caller-owned HTTP session. When omitted, the
48
+ client uses LiveKit's shared HTTP session.
49
+
50
+ Raises:
51
+ ProtofaceException: If no API key is passed and `PROTOFACE_API_KEY`
52
+ is not set.
53
+ """
54
+ self._api_key = _resolve_optional_string(api_key, "PROTOFACE_API_KEY")
55
+ if not self._api_key:
56
+ raise ProtofaceException(
57
+ "api_key must be set by passing it to ProtofaceAPI or "
58
+ "setting the PROTOFACE_API_KEY environment variable"
59
+ )
60
+
61
+ api_url_value = _resolve_optional_string(api_url, "PROTOFACE_API_URL")
62
+ self._api_url = (api_url_value or DEFAULT_API_URL).rstrip("/")
63
+ self._conn_options = conn_options
64
+ self._session = session
65
+
66
+ async def start_session(
67
+ self,
68
+ *,
69
+ avatar_id: str,
70
+ transport: dict[str, Any],
71
+ max_duration_seconds: NotGivenOr[int | None] = NOT_GIVEN,
72
+ ) -> dict[str, Any]:
73
+ """Create a hosted Protoface avatar session.
74
+
75
+ Args:
76
+ avatar_id: Protoface avatar ID to render.
77
+ transport: Protoface transport configuration. The LiveKit Agents
78
+ plugin uses `audio_source="data_stream"`.
79
+ max_duration_seconds: Optional maximum session duration. Protoface
80
+ applies the lower of this value and the account plan limit.
81
+
82
+ Returns:
83
+ The decoded Protoface session object.
84
+
85
+ Raises:
86
+ APIConnectionError: If a retryable API or network error persists
87
+ after all retry attempts.
88
+ APIStatusError: If Protoface returns a non-retryable error response.
89
+ """
90
+ body: dict[str, Any] = {"avatar_id": avatar_id, "transport": transport}
91
+ if utils.is_given(max_duration_seconds) and max_duration_seconds is not None:
92
+ body["max_duration_seconds"] = max_duration_seconds
93
+
94
+ return await self._json("POST", "/v1/sessions", json=body)
95
+
96
+ async def end_session(self, session_id: str) -> dict[str, Any]:
97
+ """Request a graceful end for a hosted Protoface session.
98
+
99
+ Args:
100
+ session_id: Protoface session ID returned by `start_session()`.
101
+
102
+ Returns:
103
+ The decoded Protoface response body.
104
+
105
+ Raises:
106
+ APIConnectionError: If a retryable API or network error persists
107
+ after all retry attempts.
108
+ APIStatusError: If Protoface returns a non-retryable error response.
109
+ """
110
+ return await self._json("POST", f"/v1/sessions/{session_id}/end")
111
+
112
+ def _ensure_http_session(self) -> aiohttp.ClientSession:
113
+ if self._session is None:
114
+ self._session = utils.http_context.http_session()
115
+ return self._session
116
+
117
+ async def _json(
118
+ self,
119
+ method: str,
120
+ path: str,
121
+ *,
122
+ json: dict[str, Any] | None = None,
123
+ headers: dict[str, str] | None = None,
124
+ ) -> dict[str, Any]:
125
+ request_headers = {
126
+ "Authorization": f"Bearer {self._api_key}",
127
+ "User-Agent": _USER_AGENT,
128
+ "Accept": "application/json",
129
+ **(headers or {}),
130
+ }
131
+ url = f"{self._api_url}{path}"
132
+ error: Exception | None = None
133
+
134
+ for attempt in range(self._conn_options.max_retry + 1):
135
+ try:
136
+ async with self._ensure_http_session().request(
137
+ method,
138
+ url,
139
+ json=json,
140
+ headers=request_headers,
141
+ timeout=aiohttp.ClientTimeout(total=self._conn_options.timeout),
142
+ ) as response:
143
+ payload = await _read_payload(response)
144
+ if response.ok:
145
+ if not isinstance(payload, dict):
146
+ raise APIStatusError(
147
+ "Protoface API returned a non-object JSON response",
148
+ status_code=response.status,
149
+ body=payload,
150
+ retryable=False,
151
+ )
152
+ return payload
153
+
154
+ raise APIStatusError(
155
+ "Protoface API returned an error",
156
+ status_code=response.status,
157
+ body=payload,
158
+ )
159
+ except asyncio.TimeoutError as exc:
160
+ error = APITimeoutError()
161
+ error.__cause__ = exc
162
+ except aiohttp.ClientError as exc:
163
+ error = APIConnectionError()
164
+ error.__cause__ = exc
165
+ except APIStatusError as exc:
166
+ if not exc.retryable:
167
+ raise
168
+ error = exc
169
+
170
+ if attempt == self._conn_options.max_retry:
171
+ break
172
+
173
+ logger.warning(
174
+ "protoface api request failed, retrying",
175
+ extra={"attempt": attempt + 1, "method": method, "path": path},
176
+ )
177
+ await asyncio.sleep(self._conn_options._interval_for_retry(attempt))
178
+
179
+ raise APIConnectionError("Failed to call Protoface API after all retries.") from error
180
+
181
+
182
+ def _resolve_optional_string(value: NotGivenOr[str | None], env_name: str) -> str | None:
183
+ if utils.is_given(value) and value is not None:
184
+ return value
185
+ return os.getenv(env_name)
186
+
187
+
188
+ async def _read_payload(response: aiohttp.ClientResponse) -> object:
189
+ text = await response.text()
190
+ if not text:
191
+ return {}
192
+
193
+ try:
194
+ return await response.json(content_type=None)
195
+ except ValueError:
196
+ return {"raw": text}
197
+
198
+
199
+ __all__ = ["DEFAULT_API_URL", "ProtofaceAPI"]
@@ -0,0 +1,238 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from datetime import timedelta
5
+
6
+ from livekit import api, rtc
7
+ from livekit.agents import (
8
+ DEFAULT_API_CONNECT_OPTIONS,
9
+ NOT_GIVEN,
10
+ AgentSession,
11
+ APIConnectOptions,
12
+ NotGivenOr,
13
+ get_job_context,
14
+ utils,
15
+ )
16
+ from livekit.agents.voice.avatar import AvatarSession as BaseAvatarSession, DataStreamAudioOutput
17
+ from livekit.agents.voice.room_io import ATTRIBUTE_PUBLISH_ON_BEHALF
18
+
19
+ from .api import ProtofaceAPI
20
+ from .errors import ProtofaceException
21
+ from .log import logger
22
+
23
+ DEFAULT_STOCK_AVATAR_ID = "av_stock_001"
24
+ SAMPLE_RATE = 16000
25
+ _AVATAR_AGENT_IDENTITY = "protoface-avatar-agent"
26
+ _AVATAR_AGENT_NAME = "protoface-avatar-agent"
27
+ _WORKER_TOKEN_TTL = timedelta(hours=1)
28
+
29
+
30
+ class AvatarSession(BaseAvatarSession):
31
+ """A Protoface avatar session for LiveKit Agents."""
32
+
33
+ def __init__(
34
+ self,
35
+ *,
36
+ avatar_id: str = DEFAULT_STOCK_AVATAR_ID,
37
+ api_url: NotGivenOr[str | None] = NOT_GIVEN,
38
+ api_key: NotGivenOr[str | None] = NOT_GIVEN,
39
+ max_duration_seconds: NotGivenOr[int | None] = NOT_GIVEN,
40
+ avatar_participant_identity: NotGivenOr[str | None] = NOT_GIVEN,
41
+ avatar_participant_name: NotGivenOr[str | None] = NOT_GIVEN,
42
+ conn_options: APIConnectOptions = DEFAULT_API_CONNECT_OPTIONS,
43
+ ) -> None:
44
+ """Create a Protoface avatar session.
45
+
46
+ Args:
47
+ avatar_id: Protoface avatar ID to render. Defaults to the stable
48
+ stock avatar ID `av_stock_001`.
49
+ api_url: Protoface API base URL. Defaults to `PROTOFACE_API_URL` or
50
+ the public Protoface API.
51
+ api_key: Protoface API key. Defaults to `PROTOFACE_API_KEY`.
52
+ max_duration_seconds: Optional maximum session duration. Protoface
53
+ applies the lower of this value and the account plan limit.
54
+ avatar_participant_identity: LiveKit participant identity for the
55
+ avatar worker.
56
+ avatar_participant_name: Display name for the avatar participant.
57
+ conn_options: Timeout and retry options for Protoface API requests.
58
+
59
+ Raises:
60
+ ProtofaceException: If no API key is provided.
61
+ """
62
+ super().__init__()
63
+ self._avatar_id = avatar_id
64
+ self._max_duration_seconds = max_duration_seconds
65
+ self._avatar_participant_identity = _resolve_optional_string(
66
+ avatar_participant_identity,
67
+ _AVATAR_AGENT_IDENTITY,
68
+ )
69
+ self._avatar_participant_name = _resolve_optional_string(
70
+ avatar_participant_name,
71
+ _AVATAR_AGENT_NAME,
72
+ )
73
+ self._api = ProtofaceAPI(
74
+ api_key=api_key,
75
+ api_url=api_url,
76
+ conn_options=conn_options,
77
+ )
78
+ self._session_id: str | None = None
79
+
80
+ @property
81
+ def avatar_identity(self) -> str:
82
+ return self._avatar_participant_identity
83
+
84
+ @property
85
+ def provider(self) -> str:
86
+ return "protoface"
87
+
88
+ @property
89
+ def session_id(self) -> str | None:
90
+ """Protoface session ID after `start()` succeeds, otherwise `None`."""
91
+ return self._session_id
92
+
93
+ async def start(
94
+ self,
95
+ agent_session: AgentSession,
96
+ room: rtc.Room,
97
+ *,
98
+ livekit_url: NotGivenOr[str | None] = NOT_GIVEN,
99
+ livekit_api_key: NotGivenOr[str | None] = NOT_GIVEN,
100
+ livekit_api_secret: NotGivenOr[str | None] = NOT_GIVEN,
101
+ ) -> None:
102
+ """Start the Protoface session and connect it to the LiveKit room.
103
+
104
+ Args:
105
+ agent_session: LiveKit agent session whose audio output should be
106
+ routed through the avatar.
107
+ room: Connected LiveKit room for the agent job.
108
+ livekit_url: LiveKit server URL. Defaults to `LIVEKIT_URL`.
109
+ livekit_api_key: LiveKit API key. Defaults to `LIVEKIT_API_KEY`.
110
+ livekit_api_secret: LiveKit API secret. Defaults to
111
+ `LIVEKIT_API_SECRET`.
112
+
113
+ Raises:
114
+ RuntimeError: If the same `AvatarSession` is started more than once.
115
+ ProtofaceException: If required LiveKit credentials are missing or
116
+ Protoface returns an invalid session response.
117
+ """
118
+ if self._session_id is not None:
119
+ raise RuntimeError("AvatarSession.start() called twice; create a new AvatarSession.")
120
+
121
+ await super().start(agent_session, room)
122
+
123
+ livekit_url_value = _resolve_env_or_value(livekit_url, "LIVEKIT_URL")
124
+ livekit_api_key_value = _resolve_env_or_value(livekit_api_key, "LIVEKIT_API_KEY")
125
+ livekit_api_secret_value = _resolve_env_or_value(
126
+ livekit_api_secret,
127
+ "LIVEKIT_API_SECRET",
128
+ )
129
+ if not livekit_url_value or not livekit_api_key_value or not livekit_api_secret_value:
130
+ raise ProtofaceException(
131
+ "livekit_url, livekit_api_key, and livekit_api_secret must be set "
132
+ "by arguments or environment variables"
133
+ )
134
+
135
+ worker_token = self._mint_worker_token(
136
+ room=room,
137
+ livekit_api_key=livekit_api_key_value,
138
+ livekit_api_secret=livekit_api_secret_value,
139
+ )
140
+ session = await self._api.start_session(
141
+ avatar_id=self._avatar_id,
142
+ transport={
143
+ "type": "livekit",
144
+ "url": livekit_url_value,
145
+ "room_name": room.name,
146
+ "worker_token": worker_token,
147
+ "worker_identity": self._avatar_participant_identity,
148
+ "audio_source": "data_stream",
149
+ },
150
+ max_duration_seconds=self._max_duration_seconds,
151
+ )
152
+ session_id = session.get("id")
153
+ if not isinstance(session_id, str):
154
+ raise ProtofaceException("Protoface API response missing session id")
155
+
156
+ self._session_id = session_id
157
+ logger.debug(
158
+ "protoface session started",
159
+ extra={"session_id": self._session_id, "avatar_id": self._avatar_id},
160
+ )
161
+
162
+ agent_session.output.replace_audio_tail(
163
+ DataStreamAudioOutput(
164
+ room=room,
165
+ destination_identity=self._avatar_participant_identity,
166
+ sample_rate=SAMPLE_RATE,
167
+ wait_remote_track=rtc.TrackKind.KIND_VIDEO,
168
+ clear_buffer_timeout=None,
169
+ ),
170
+ )
171
+
172
+ async def aclose(self) -> None:
173
+ """End the Protoface session and release LiveKit avatar resources."""
174
+ session_id = self._session_id
175
+ self._session_id = None
176
+ try:
177
+ if session_id is not None:
178
+ try:
179
+ await self._api.end_session(session_id)
180
+ except Exception:
181
+ logger.warning(
182
+ "failed to end protoface session",
183
+ extra={"session_id": session_id},
184
+ exc_info=True,
185
+ )
186
+ finally:
187
+ await super().aclose()
188
+
189
+ def _mint_worker_token(
190
+ self,
191
+ *,
192
+ room: rtc.Room,
193
+ livekit_api_key: str,
194
+ livekit_api_secret: str,
195
+ ) -> str:
196
+ job_ctx = get_job_context(required=False)
197
+ if job_ctx is not None:
198
+ local_participant_identity = job_ctx.local_participant_identity
199
+ elif room.isconnected():
200
+ local_participant_identity = room.local_participant.identity
201
+ else:
202
+ raise ProtofaceException("failed to get local participant identity")
203
+
204
+ if not local_participant_identity:
205
+ raise ProtofaceException("failed to get local participant identity")
206
+
207
+ grants = api.VideoGrants(
208
+ room_join=True,
209
+ room=room.name,
210
+ can_publish=True,
211
+ can_subscribe=True,
212
+ can_publish_data=True,
213
+ )
214
+ return (
215
+ api.AccessToken(api_key=livekit_api_key, api_secret=livekit_api_secret)
216
+ .with_kind("agent")
217
+ .with_identity(self._avatar_participant_identity)
218
+ .with_name(self._avatar_participant_name)
219
+ .with_grants(grants)
220
+ .with_attributes({ATTRIBUTE_PUBLISH_ON_BEHALF: local_participant_identity})
221
+ .with_ttl(_WORKER_TOKEN_TTL)
222
+ .to_jwt()
223
+ )
224
+
225
+
226
+ def _resolve_optional_string(value: NotGivenOr[str | None], default: str) -> str:
227
+ if utils.is_given(value) and value:
228
+ return value
229
+ return default
230
+
231
+
232
+ def _resolve_env_or_value(value: NotGivenOr[str | None], env_name: str) -> str | None:
233
+ if utils.is_given(value) and value is not None:
234
+ return value
235
+ return os.getenv(env_name)
236
+
237
+
238
+ __all__ = ["DEFAULT_STOCK_AVATAR_ID", "AvatarSession"]
@@ -0,0 +1,2 @@
1
+ class ProtofaceException(Exception):
2
+ """Raised for Protoface configuration or protocol errors."""
@@ -0,0 +1,3 @@
1
+ import logging
2
+
3
+ logger = logging.getLogger("livekit.plugins.protoface")
@@ -0,0 +1 @@
1
+ __version__ = "1.0.0"
@@ -0,0 +1,42 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "livekit-plugins-protoface"
7
+ dynamic = ["version"]
8
+ description = "Agent Framework plugin for Protoface avatar"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.10.0"
12
+ authors = [{ name = "Protoface Team", email = "info@protoface.com" }]
13
+ keywords = ["voice", "ai", "realtime", "audio", "video", "avatar", "livekit", "protoface"]
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.6.1"]
25
+
26
+ [project.urls]
27
+ Documentation = "https://docs.protoface.com"
28
+ Website = "https://protoface.com/"
29
+ Source = "https://github.com/protoface-ai/livekit-plugins-protoface"
30
+
31
+ [tool.hatch.version]
32
+ path = "livekit/plugins/protoface/version.py"
33
+
34
+ [tool.hatch.build.targets.wheel]
35
+ packages = ["livekit"]
36
+
37
+ [tool.hatch.build.targets.sdist]
38
+ include = ["/livekit"]
39
+
40
+ [tool.uv]
41
+ exclude-newer = "7 days"
42
+ exclude-newer-package = { livekit-agents = "0 days" }