livekit-plugins-meshlite 0.1.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,9 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ venv/
5
+ build/
6
+ dist/
7
+ *.egg-info/
8
+ .pytest_cache/
9
+ .env
@@ -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,185 @@
1
+ Metadata-Version: 2.5
2
+ Name: livekit-plugins-meshlite
3
+ Version: 0.1.0
4
+ Summary: MeshLite avatar for LiveKit Agents: the agent voice drives a lip-synced avatar rendered in the visitor's browser
5
+ Project-URL: Homepage, https://meshlite.io
6
+ Project-URL: Documentation, https://github.com/meshlite-avatar/livekit-plugins-meshlite#readme
7
+ Project-URL: Source, https://github.com/meshlite-avatar/livekit-plugins-meshlite
8
+ Project-URL: Issues, https://github.com/meshlite-avatar/livekit-plugins-meshlite/issues
9
+ Author: MeshLite
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: agents,avatar,lip-sync,livekit,meshlite,realtime,webrtc
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Topic :: Multimedia :: Sound/Audio
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Classifier: Typing :: Typed
20
+ Requires-Python: >=3.9
21
+ Requires-Dist: livekit-agents<2,>=1.0.0
22
+ Provides-Extra: test
23
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'test'
24
+ Requires-Dist: pytest>=8; extra == 'test'
25
+ Description-Content-Type: text/markdown
26
+
27
+ # livekit-plugins-meshlite
28
+
29
+ Give your [LiveKit Agents](https://docs.livekit.io/agents/) voice agent a lip-synced
30
+ [MeshLite](https://meshlite.io) face. Your agent keeps its own speech-to-text, LLM and
31
+ voice (or realtime model); MeshLite only renders the face, in the visitor's browser.
32
+
33
+ ```
34
+ your agent (Python) --lk.audio_stream--> visitor page (livekit-client) --> MeshLite avatar (face + lips)
35
+ <--playback RPCs----
36
+ ```
37
+
38
+ - No video server, no GPU, no extra participant in the room: the agent sends its voice to
39
+ the visitor page over the LiveKit data channel, using the LiveKit Agents avatar
40
+ data-stream protocol, and the MeshLite web SDK animates the avatar locally.
41
+ - Interruptions work as usual: the face stops at once and reports the position really
42
+ heard, so the chat context keeps only what the visitor heard.
43
+ - No MeshLite voice minutes are used. The session still counts as a conversation
44
+ (concurrent conversations, seats, statistics) and lasts at most 2 hours.
45
+
46
+ ## Install
47
+
48
+ ```bash
49
+ pip install livekit-plugins-meshlite
50
+ ```
51
+
52
+ Requires Python 3.9+ and `livekit-agents` 1.x.
53
+
54
+ ## Agent side
55
+
56
+ ```python
57
+ from livekit.agents import Agent, AgentSession, JobContext
58
+ from livekit.plugins import meshlite
59
+
60
+ async def entrypoint(ctx: JobContext):
61
+ await ctx.connect()
62
+ session = AgentSession(stt=..., llm=..., tts=...) # or a realtime model
63
+
64
+ avatar = meshlite.AvatarSession() # visitor_identity="..." if several visitors share the room
65
+ await avatar.start(session, room=ctx.room) # after ctx.connect(), before session.start()
66
+
67
+ await session.start(agent=Agent(instructions="..."), room=ctx.room)
68
+ ```
69
+
70
+ `AvatarSession.start()` waits for the visitor participant (the first standard participant,
71
+ or `visitor_identity`) and replaces the session audio output with LiveKit's
72
+ `DataStreamAudioOutput`. The agent then publishes no audio track: its voice reaches the
73
+ page as data and the MeshLite SDK plays it in sync with the face.
74
+
75
+ | Argument | Default | Meaning |
76
+ |---|---|---|
77
+ | `visitor_identity` | first standard participant | browser participant whose page shows the avatar |
78
+ | `sample_rate` | `24000` | PCM rate sent to the page (8000 to 48000) |
79
+ | `clear_buffer_timeout` | `2.0` | seconds to wait for the page to confirm an interruption |
80
+
81
+ ### Audio format
82
+
83
+ One `lk.audio_stream` byte stream per speech segment: raw 16-bit signed little-endian PCM
84
+ (usually mono), 24 kHz by default, with `sample_rate` and `num_channels` stream attributes. The
85
+ agent sends the `lk.clear_buffer` RPC on interruption; the page answers with the
86
+ `lk.playback_started` and `lk.playback_finished` RPCs
87
+ (`{"playback_position": float, "interrupted": bool}`).
88
+
89
+ The data-stream protocol cannot pause and resume a segment. If your agent version offers
90
+ false-interruption resume, disable it: `AgentSession(..., resume_false_interruption=False)`.
91
+
92
+ ## Browser side
93
+
94
+ You need a MeshLite account on a plan that can embed the SDK on a website, a declared
95
+ domain, a publishable key and a secret key of the same environment, and an avatar id
96
+ (all in the MeshLite console).
97
+
98
+ **1. Your server creates the MeshLite session** with `audio: "livekit"`. The secret key
99
+ stays on your server:
100
+
101
+ ```js
102
+ const upstream = await fetch("https://console.meshlite.io/api/v1/client-sessions", {
103
+ method: "POST",
104
+ headers: { Authorization: `Bearer ${process.env.MESHLITE_SECRET_KEY}`, "Content-Type": "application/json" },
105
+ body: JSON.stringify({
106
+ publishableKey: process.env.MESHLITE_PUBLISHABLE_KEY,
107
+ origin: "https://www.example.com", // set by your server, never copied from the browser
108
+ avatar: "your-avatar-id",
109
+ audio: "livekit",
110
+ }),
111
+ });
112
+ const { sessionToken } = await upstream.json();
113
+ ```
114
+
115
+ **2. The visitor page mounts the avatar and attaches the room** before connecting:
116
+
117
+ ```html
118
+ <div id="avatar" style="width:340px;height:510px"></div>
119
+ <script src="https://console.meshlite.io/sdk/1.11.46/meshlite.js" crossorigin="anonymous"></script>
120
+ <script type="module">
121
+ import { Room } from "https://cdn.jsdelivr.net/npm/livekit-client@2.23.0/+esm";
122
+
123
+ const avatar = MeshLite.mount({
124
+ container: "#avatar",
125
+ avatar: "your-avatar-id",
126
+ publishableKey: "ml_pk_live_...",
127
+ sessionToken, // from your server (step 1)
128
+ audio: "livekit",
129
+ });
130
+
131
+ const room = new Room();
132
+ const link = avatar.attachLiveKit(room); // attach before connect so no speech is missed
133
+ link.on("ready", ({ output }) => console.log("avatar ready, voice played by", output));
134
+ link.on("fallback", ({ code }) => console.warn("avatar unavailable, the voice continues", code));
135
+ link.on("audio-blocked", () => showClickToEnableSound(() => link.resumeAudio()));
136
+
137
+ await room.connect(LIVEKIT_URL, participantToken); // your LiveKit token (data publishing allowed)
138
+ await room.localParticipant.setMicrophoneEnabled(true);
139
+ </script>
140
+ ```
141
+
142
+ Requirements: `livekit-client` 2.9 or later (tested with 2.23.0), MeshLite web SDK 1.11.45
143
+ or later, HTTPS (or `http://localhost` with test keys). Do not subscribe the agent audio
144
+ yourself: the SDK plays the voice.
145
+
146
+ `attachLiveKit(room, options)` accepts `agentIdentity` (accept audio only from this
147
+ participant), `output` (`"auto"`, `"frame"` or `"page"`) and `fallback` (default `true`).
148
+ With `output: "auto"`, Firefox plays the voice in your page while the avatar animates the
149
+ lips in silence, so Firefox's echo cancellation hears it; other browsers play it in the
150
+ avatar frame.
151
+
152
+ ### Fallback: the avatar never blocks the conversation
153
+
154
+ When the face cannot start (refused session, network, timeout), fails, or is stopped
155
+ (maximum duration, quota), the page plays the agent voice itself from the position already
156
+ heard, the agent keeps receiving playback events and interruptions, and `link` emits
157
+ `fallback` with an error `code`. Use `fallback: false` to stop instead (`failed` /
158
+ `stopped` events).
159
+
160
+ ## Limits
161
+
162
+ - Maximum session duration: 2 hours.
163
+ - LiveKit recordings (egress) do not contain the agent voice, since no audio track is
164
+ published.
165
+ - The MeshLite avatar is not a room participant: `avatar.avatar_identity` on the agent side
166
+ is the visitor identity.
167
+
168
+ ## Example app
169
+
170
+ [`examples/browser-avatar`](examples/browser-avatar) is a complete local demo: a LiveKit
171
+ agent, a small Python server that creates both session tokens, and a page with the avatar.
172
+
173
+ ## Development
174
+
175
+ ```bash
176
+ pip install -e ".[test]"
177
+ pytest
178
+ ```
179
+
180
+ The tests run offline with a fake room and check the exact protocol the MeshLite web SDK
181
+ implements.
182
+
183
+ ## License
184
+
185
+ [Apache-2.0](LICENSE)
@@ -0,0 +1,159 @@
1
+ # livekit-plugins-meshlite
2
+
3
+ Give your [LiveKit Agents](https://docs.livekit.io/agents/) voice agent a lip-synced
4
+ [MeshLite](https://meshlite.io) face. Your agent keeps its own speech-to-text, LLM and
5
+ voice (or realtime model); MeshLite only renders the face, in the visitor's browser.
6
+
7
+ ```
8
+ your agent (Python) --lk.audio_stream--> visitor page (livekit-client) --> MeshLite avatar (face + lips)
9
+ <--playback RPCs----
10
+ ```
11
+
12
+ - No video server, no GPU, no extra participant in the room: the agent sends its voice to
13
+ the visitor page over the LiveKit data channel, using the LiveKit Agents avatar
14
+ data-stream protocol, and the MeshLite web SDK animates the avatar locally.
15
+ - Interruptions work as usual: the face stops at once and reports the position really
16
+ heard, so the chat context keeps only what the visitor heard.
17
+ - No MeshLite voice minutes are used. The session still counts as a conversation
18
+ (concurrent conversations, seats, statistics) and lasts at most 2 hours.
19
+
20
+ ## Install
21
+
22
+ ```bash
23
+ pip install livekit-plugins-meshlite
24
+ ```
25
+
26
+ Requires Python 3.9+ and `livekit-agents` 1.x.
27
+
28
+ ## Agent side
29
+
30
+ ```python
31
+ from livekit.agents import Agent, AgentSession, JobContext
32
+ from livekit.plugins import meshlite
33
+
34
+ async def entrypoint(ctx: JobContext):
35
+ await ctx.connect()
36
+ session = AgentSession(stt=..., llm=..., tts=...) # or a realtime model
37
+
38
+ avatar = meshlite.AvatarSession() # visitor_identity="..." if several visitors share the room
39
+ await avatar.start(session, room=ctx.room) # after ctx.connect(), before session.start()
40
+
41
+ await session.start(agent=Agent(instructions="..."), room=ctx.room)
42
+ ```
43
+
44
+ `AvatarSession.start()` waits for the visitor participant (the first standard participant,
45
+ or `visitor_identity`) and replaces the session audio output with LiveKit's
46
+ `DataStreamAudioOutput`. The agent then publishes no audio track: its voice reaches the
47
+ page as data and the MeshLite SDK plays it in sync with the face.
48
+
49
+ | Argument | Default | Meaning |
50
+ |---|---|---|
51
+ | `visitor_identity` | first standard participant | browser participant whose page shows the avatar |
52
+ | `sample_rate` | `24000` | PCM rate sent to the page (8000 to 48000) |
53
+ | `clear_buffer_timeout` | `2.0` | seconds to wait for the page to confirm an interruption |
54
+
55
+ ### Audio format
56
+
57
+ One `lk.audio_stream` byte stream per speech segment: raw 16-bit signed little-endian PCM
58
+ (usually mono), 24 kHz by default, with `sample_rate` and `num_channels` stream attributes. The
59
+ agent sends the `lk.clear_buffer` RPC on interruption; the page answers with the
60
+ `lk.playback_started` and `lk.playback_finished` RPCs
61
+ (`{"playback_position": float, "interrupted": bool}`).
62
+
63
+ The data-stream protocol cannot pause and resume a segment. If your agent version offers
64
+ false-interruption resume, disable it: `AgentSession(..., resume_false_interruption=False)`.
65
+
66
+ ## Browser side
67
+
68
+ You need a MeshLite account on a plan that can embed the SDK on a website, a declared
69
+ domain, a publishable key and a secret key of the same environment, and an avatar id
70
+ (all in the MeshLite console).
71
+
72
+ **1. Your server creates the MeshLite session** with `audio: "livekit"`. The secret key
73
+ stays on your server:
74
+
75
+ ```js
76
+ const upstream = await fetch("https://console.meshlite.io/api/v1/client-sessions", {
77
+ method: "POST",
78
+ headers: { Authorization: `Bearer ${process.env.MESHLITE_SECRET_KEY}`, "Content-Type": "application/json" },
79
+ body: JSON.stringify({
80
+ publishableKey: process.env.MESHLITE_PUBLISHABLE_KEY,
81
+ origin: "https://www.example.com", // set by your server, never copied from the browser
82
+ avatar: "your-avatar-id",
83
+ audio: "livekit",
84
+ }),
85
+ });
86
+ const { sessionToken } = await upstream.json();
87
+ ```
88
+
89
+ **2. The visitor page mounts the avatar and attaches the room** before connecting:
90
+
91
+ ```html
92
+ <div id="avatar" style="width:340px;height:510px"></div>
93
+ <script src="https://console.meshlite.io/sdk/1.11.46/meshlite.js" crossorigin="anonymous"></script>
94
+ <script type="module">
95
+ import { Room } from "https://cdn.jsdelivr.net/npm/livekit-client@2.23.0/+esm";
96
+
97
+ const avatar = MeshLite.mount({
98
+ container: "#avatar",
99
+ avatar: "your-avatar-id",
100
+ publishableKey: "ml_pk_live_...",
101
+ sessionToken, // from your server (step 1)
102
+ audio: "livekit",
103
+ });
104
+
105
+ const room = new Room();
106
+ const link = avatar.attachLiveKit(room); // attach before connect so no speech is missed
107
+ link.on("ready", ({ output }) => console.log("avatar ready, voice played by", output));
108
+ link.on("fallback", ({ code }) => console.warn("avatar unavailable, the voice continues", code));
109
+ link.on("audio-blocked", () => showClickToEnableSound(() => link.resumeAudio()));
110
+
111
+ await room.connect(LIVEKIT_URL, participantToken); // your LiveKit token (data publishing allowed)
112
+ await room.localParticipant.setMicrophoneEnabled(true);
113
+ </script>
114
+ ```
115
+
116
+ Requirements: `livekit-client` 2.9 or later (tested with 2.23.0), MeshLite web SDK 1.11.45
117
+ or later, HTTPS (or `http://localhost` with test keys). Do not subscribe the agent audio
118
+ yourself: the SDK plays the voice.
119
+
120
+ `attachLiveKit(room, options)` accepts `agentIdentity` (accept audio only from this
121
+ participant), `output` (`"auto"`, `"frame"` or `"page"`) and `fallback` (default `true`).
122
+ With `output: "auto"`, Firefox plays the voice in your page while the avatar animates the
123
+ lips in silence, so Firefox's echo cancellation hears it; other browsers play it in the
124
+ avatar frame.
125
+
126
+ ### Fallback: the avatar never blocks the conversation
127
+
128
+ When the face cannot start (refused session, network, timeout), fails, or is stopped
129
+ (maximum duration, quota), the page plays the agent voice itself from the position already
130
+ heard, the agent keeps receiving playback events and interruptions, and `link` emits
131
+ `fallback` with an error `code`. Use `fallback: false` to stop instead (`failed` /
132
+ `stopped` events).
133
+
134
+ ## Limits
135
+
136
+ - Maximum session duration: 2 hours.
137
+ - LiveKit recordings (egress) do not contain the agent voice, since no audio track is
138
+ published.
139
+ - The MeshLite avatar is not a room participant: `avatar.avatar_identity` on the agent side
140
+ is the visitor identity.
141
+
142
+ ## Example app
143
+
144
+ [`examples/browser-avatar`](examples/browser-avatar) is a complete local demo: a LiveKit
145
+ agent, a small Python server that creates both session tokens, and a page with the avatar.
146
+
147
+ ## Development
148
+
149
+ ```bash
150
+ pip install -e ".[test]"
151
+ pytest
152
+ ```
153
+
154
+ The tests run offline with a fake room and check the exact protocol the MeshLite web SDK
155
+ implements.
156
+
157
+ ## License
158
+
159
+ [Apache-2.0](LICENSE)
@@ -0,0 +1,20 @@
1
+ """MeshLite avatar plugin for LiveKit Agents.
2
+
3
+ See https://console.meshlite.io for the web SDK that renders the avatar.
4
+ """
5
+
6
+ from livekit.agents import Plugin
7
+
8
+ from .avatar import DEFAULT_SAMPLE_RATE, AvatarSession
9
+ from .log import logger
10
+ from .version import __version__
11
+
12
+ __all__ = ["AvatarSession", "DEFAULT_SAMPLE_RATE", "__version__"]
13
+
14
+
15
+ class MeshLitePlugin(Plugin):
16
+ def __init__(self) -> None:
17
+ super().__init__(__name__, __version__, __package__, logger)
18
+
19
+
20
+ Plugin.register_plugin(MeshLitePlugin())
@@ -0,0 +1,177 @@
1
+ """MeshLite avatar for LiveKit Agents.
2
+
3
+ The MeshLite avatar is not a participant of the room and the agent never
4
+ renders or publishes video. The visitor's web page shows the avatar with the
5
+ MeshLite web SDK (``audio: "livekit"`` + ``controller.attachLiveKit(room)``);
6
+ this module only routes the agent voice to that page.
7
+
8
+ Wire protocol (the LiveKit Agents avatar data-stream protocol):
9
+
10
+ * agent -> visitor: one ``lk.audio_stream`` byte stream per speech segment,
11
+ 16-bit PCM, ``sample_rate`` and ``num_channels`` stream attributes;
12
+ * agent -> visitor: RPC ``lk.clear_buffer`` on interruption;
13
+ * visitor -> agent: RPC ``lk.playback_started`` and ``lk.playback_finished``
14
+ (``{"playback_position": float, "interrupted": bool}``).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import inspect
20
+
21
+ from livekit import rtc
22
+ from livekit.agents import AgentSession, utils
23
+ from livekit.agents.voice.avatar import DataStreamAudioOutput
24
+
25
+ from .log import logger
26
+
27
+ DEFAULT_SAMPLE_RATE = 24000
28
+ _MIN_SAMPLE_RATE = 8000
29
+ _MAX_SAMPLE_RATE = 48000
30
+
31
+ try:
32
+ _OUTPUT_PARAMS = inspect.signature(DataStreamAudioOutput.__init__).parameters
33
+ except (TypeError, ValueError): # pragma: no cover - exotic builds
34
+ _OUTPUT_PARAMS = {}
35
+
36
+
37
+ class AvatarSession:
38
+ """Route an :class:`~livekit.agents.AgentSession` voice to a MeshLite avatar.
39
+
40
+ Call :meth:`start` after ``await ctx.connect()`` and **before**
41
+ ``await session.start(...)``: the agent then sends its voice to the
42
+ visitor's page instead of publishing an audio track, and the page plays
43
+ it in sync with the avatar's face.
44
+
45
+ Args:
46
+ visitor_identity: identity of the browser participant whose page
47
+ shows the avatar. When omitted, the first standard (non-agent,
48
+ non-SIP) remote participant of the room is used, which is the
49
+ participant :class:`AgentSession` links to by default.
50
+ sample_rate: PCM rate sent to the page. The page converts any rate;
51
+ 24 kHz matches the MeshLite engine and keeps the stream small.
52
+ clear_buffer_timeout: seconds the agent waits for the page to confirm
53
+ an interruption before it considers the speech stopped.
54
+ """
55
+
56
+ def __init__(
57
+ self,
58
+ *,
59
+ visitor_identity: str | None = None,
60
+ sample_rate: int = DEFAULT_SAMPLE_RATE,
61
+ clear_buffer_timeout: float | None = 2.0,
62
+ ) -> None:
63
+ if visitor_identity is not None and (
64
+ not isinstance(visitor_identity, str) or not visitor_identity.strip()
65
+ ):
66
+ raise ValueError("visitor_identity must be a non-empty string")
67
+ if (
68
+ isinstance(sample_rate, bool)
69
+ or not isinstance(sample_rate, int)
70
+ or not _MIN_SAMPLE_RATE <= sample_rate <= _MAX_SAMPLE_RATE
71
+ ):
72
+ raise ValueError(
73
+ f"sample_rate must be an integer between {_MIN_SAMPLE_RATE} and {_MAX_SAMPLE_RATE}"
74
+ )
75
+ if clear_buffer_timeout is not None and not clear_buffer_timeout >= 0:
76
+ raise ValueError("clear_buffer_timeout must be >= 0 or None")
77
+
78
+ self._visitor_identity = visitor_identity
79
+ self._sample_rate = sample_rate
80
+ self._clear_buffer_timeout = clear_buffer_timeout
81
+ self._audio_output: DataStreamAudioOutput | None = None
82
+ self._agent_session: AgentSession | None = None
83
+ self._starting = False
84
+ self._closed = False
85
+
86
+ @property
87
+ def provider(self) -> str:
88
+ return "meshlite"
89
+
90
+ @property
91
+ def visitor_identity(self) -> str | None:
92
+ """Identity of the participant that renders the avatar (known after start)."""
93
+ return self._visitor_identity
94
+
95
+ @property
96
+ def avatar_identity(self) -> str:
97
+ """The participant whose page renders the avatar.
98
+
99
+ MeshLite has no avatar participant: the avatar lives in the visitor's
100
+ page, so this is the visitor identity.
101
+ """
102
+ if self._visitor_identity is None:
103
+ raise RuntimeError("the visitor identity is known once start() has returned")
104
+ return self._visitor_identity
105
+
106
+ @property
107
+ def audio_output(self) -> DataStreamAudioOutput | None:
108
+ return self._audio_output
109
+
110
+ async def start(self, agent_session: AgentSession, room: rtc.Room) -> None:
111
+ if self._closed:
112
+ raise RuntimeError("this MeshLite AvatarSession is closed")
113
+ if self._starting or self._audio_output is not None:
114
+ raise RuntimeError("MeshLite AvatarSession.start() can only be called once")
115
+ self._starting = True
116
+ try:
117
+ identity = self._visitor_identity
118
+ if identity is None:
119
+ if not room.isconnected():
120
+ raise RuntimeError(
121
+ "connect to the room (await ctx.connect()) before starting the MeshLite "
122
+ "avatar, or pass visitor_identity"
123
+ )
124
+ logger.debug("waiting for the visitor participant")
125
+ participant = await utils.wait_for_participant(
126
+ room, kind=rtc.ParticipantKind.PARTICIPANT_KIND_STANDARD
127
+ )
128
+ identity = participant.identity
129
+ if self._closed:
130
+ raise RuntimeError("this MeshLite AvatarSession was closed while starting")
131
+
132
+ previous = agent_session.output.audio
133
+ if previous is not None:
134
+ logger.warning(
135
+ "replacing the session audio output with the MeshLite avatar output; "
136
+ "call AvatarSession.start() before AgentSession.start() so the agent "
137
+ "does not publish its own audio track",
138
+ extra={"previous_output": getattr(previous, "label", type(previous).__name__)},
139
+ )
140
+
141
+ options: dict[str, object] = {}
142
+ if "clear_buffer_timeout" in _OUTPUT_PARAMS:
143
+ options["clear_buffer_timeout"] = self._clear_buffer_timeout
144
+ if "wait_playback_start" in _OUTPUT_PARAMS:
145
+ # The page reports when the avatar really starts speaking.
146
+ options["wait_playback_start"] = True
147
+ output = DataStreamAudioOutput(
148
+ room,
149
+ destination_identity=identity,
150
+ sample_rate=self._sample_rate,
151
+ **options, # type: ignore[arg-type]
152
+ )
153
+ agent_session.output.audio = output
154
+
155
+ self._visitor_identity = identity
156
+ self._audio_output = output
157
+ self._agent_session = agent_session
158
+ logger.info(
159
+ "MeshLite avatar voice routed to the visitor page",
160
+ extra={"visitor_identity": identity, "sample_rate": self._sample_rate},
161
+ )
162
+ finally:
163
+ self._starting = False
164
+
165
+ async def aclose(self) -> None:
166
+ """Stop routing the voice to the avatar.
167
+
168
+ Unlike video avatar plugins this never removes a participant from the
169
+ room: the only participant involved is the visitor.
170
+ """
171
+ if self._closed:
172
+ return
173
+ self._closed = True
174
+ session, output = self._agent_session, self._audio_output
175
+ self._agent_session = None
176
+ if session is not None and output is not None and session.output.audio is output:
177
+ session.output.audio = None
@@ -0,0 +1,3 @@
1
+ import logging
2
+
3
+ logger = logging.getLogger("livekit.plugins.meshlite")
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,47 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "livekit-plugins-meshlite"
7
+ dynamic = ["version"]
8
+ description = "MeshLite avatar for LiveKit Agents: the agent voice drives a lip-synced avatar rendered in the visitor's browser"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.9"
13
+ authors = [{ name = "MeshLite" }]
14
+ keywords = ["livekit", "agents", "avatar", "meshlite", "webrtc", "realtime", "lip-sync"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Developers",
18
+ "Topic :: Multimedia :: Sound/Audio",
19
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3 :: Only",
22
+ "Typing :: Typed",
23
+ ]
24
+ dependencies = ["livekit-agents>=1.0.0,<2"]
25
+
26
+ [project.optional-dependencies]
27
+ test = ["pytest>=8", "pytest-asyncio>=0.23"]
28
+
29
+ [project.urls]
30
+ Homepage = "https://meshlite.io"
31
+ Documentation = "https://github.com/meshlite-avatar/livekit-plugins-meshlite#readme"
32
+ Source = "https://github.com/meshlite-avatar/livekit-plugins-meshlite"
33
+ Issues = "https://github.com/meshlite-avatar/livekit-plugins-meshlite/issues"
34
+
35
+ [tool.hatch.version]
36
+ path = "livekit/plugins/meshlite/version.py"
37
+
38
+ [tool.hatch.build.targets.wheel]
39
+ packages = ["livekit"]
40
+
41
+ [tool.hatch.build.targets.sdist]
42
+ include = ["/livekit", "/README.md", "/LICENSE"]
43
+
44
+ [tool.pytest.ini_options]
45
+ asyncio_mode = "auto"
46
+ asyncio_default_fixture_loop_scope = "function"
47
+ testpaths = ["tests"]