livekit-plugins-meshlite 0.2.0__tar.gz → 0.3.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.
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: livekit-plugins-meshlite
3
- Version: 0.2.0
4
- Summary: MeshLite avatar for LiveKit Agents: the agent voice drives a lip-synced avatar drawn on the user's own device
3
+ Version: 0.3.0
4
+ Summary: MeshLite avatar for LiveKit Agents: the agent starts a lip-synced avatar drawn on the user's own device
5
5
  Project-URL: Homepage, https://meshlite.io
6
6
  Project-URL: Documentation, https://github.com/meshlite-avatar/livekit-plugins-meshlite#readme
7
7
  Project-URL: Source, https://github.com/meshlite-avatar/livekit-plugins-meshlite
@@ -17,8 +17,9 @@ Classifier: Programming Language :: Python :: 3 :: Only
17
17
  Classifier: Topic :: Multimedia :: Sound/Audio
18
18
  Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
19
  Classifier: Typing :: Typed
20
- Requires-Python: >=3.9
21
- Requires-Dist: livekit-agents<2,>=1.0.0
20
+ Requires-Python: >=3.10
21
+ Requires-Dist: aiohttp>=3.9
22
+ Requires-Dist: livekit-agents<2,>=1.7.0
22
23
  Provides-Extra: test
23
24
  Requires-Dist: pytest-asyncio>=0.23; extra == 'test'
24
25
  Requires-Dist: pytest>=8; extra == 'test'
@@ -32,10 +33,16 @@ voice (or realtime model); MeshLite only renders the face, on the visitor's own
32
33
  or computer.
33
34
 
34
35
  ```
35
- your agent (Python) --lk.audio_stream--> visitor page (livekit-client) --> MeshLite avatar (face + lips)
36
+ your agent (Python) --POST /api/v1/client-sessions (secret key)--> MeshLite
37
+ --meshlite.session_token RPC (visitor only)--> visitor page (livekit-client)
38
+ --lk.audio_stream--> visitor page --> MeshLite avatar (face + lips)
36
39
  <--playback RPCs----
37
40
  ```
38
41
 
42
+ - The agent starts the avatar: `meshlite.AvatarSession(api_key=...)` creates the MeshLite
43
+ session with your secret key and hands its short, single-use token to the visitor page.
44
+ Your web server only issues the LiveKit participant token.
45
+
39
46
  - No video server, no GPU, no extra participant in the room: the agent sends its voice to
40
47
  the visitor page over the LiveKit data channel, using the LiveKit Agents avatar
41
48
  data-stream protocol, and the MeshLite web SDK animates the avatar locally.
@@ -50,7 +57,19 @@ your agent (Python) --lk.audio_stream--> visitor page (livekit-client) --> M
50
57
  pip install livekit-plugins-meshlite
51
58
  ```
52
59
 
53
- Requires Python 3.9+ and `livekit-agents` 1.x.
60
+ Requires Python 3.10+ and `livekit-agents` 1.7 or later.
61
+
62
+ ## Upgrading from 0.2.0
63
+
64
+ 0.2.0 keeps working: there your web server creates the MeshLite session. To stay on it, pin
65
+ `livekit-plugins-meshlite==0.2.0` and follow the [0.2.0 README](https://github.com/meshlite-avatar/livekit-plugins-meshlite/tree/v0.2.0#readme).
66
+ To move to 0.3.0, make three changes:
67
+
68
+ 1. Agent: pass `api_key`, `publishable_key`, `origin` and `avatar_id` to `meshlite.AvatarSession`
69
+ (or set the `MESHLITE_*` environment variables below).
70
+ 2. Server: stop creating the MeshLite session; only issue the LiveKit participant token.
71
+ 3. Page: pass `sessionToken: () => sessionTokenFromAgent(room)` instead of a token from your
72
+ server (see [Browser side](#browser-side)).
54
73
 
55
74
  ## Agent side
56
75
 
@@ -62,24 +81,55 @@ async def entrypoint(ctx: JobContext):
62
81
  await ctx.connect()
63
82
  session = AgentSession(stt=..., llm=..., tts=...) # or a realtime model
64
83
 
65
- avatar = meshlite.AvatarSession() # visitor_identity="..." if several visitors share the room
84
+ avatar = meshlite.AvatarSession(
85
+ api_key=os.environ["MESHLITE_API_KEY"], # secret key ml_sk_..., stays in the agent
86
+ publishable_key=os.environ["MESHLITE_PUBLISHABLE_KEY"],
87
+ origin="https://www.example.com", # the website that shows the face
88
+ avatar_id="your-avatar-id",
89
+ )
66
90
  await avatar.start(session, room=ctx.room) # after ctx.connect(), before session.start()
67
91
 
68
92
  await session.start(agent=Agent(instructions="..."), room=ctx.room)
69
93
  ```
70
94
 
95
+ Each argument can also come from the environment: `MESHLITE_API_KEY`,
96
+ `MESHLITE_PUBLISHABLE_KEY`, `MESHLITE_ORIGIN`, `MESHLITE_AVATAR_ID` (and `MESHLITE_API_URL`).
97
+
71
98
  `AvatarSession.start()` waits for the visitor participant (the first standard participant,
72
- or `visitor_identity`) and replaces the session audio output with LiveKit's
73
- `DataStreamAudioOutput`. The agent then publishes no audio track: its voice reaches the
74
- page as data and the MeshLite SDK plays it in sync with the face.
99
+ or `visitor_identity`), offers the MeshLite session to that participant with the RPC
100
+ `meshlite.session_token`, and installs LiveKit's `DataStreamAudioOutput` as the session
101
+ audio output. The agent then publishes no audio track: its voice reaches the page as data
102
+ and the MeshLite SDK plays it in sync with the face.
75
103
 
76
104
  | Argument | Default | Meaning |
77
105
  |---|---|---|
106
+ | `api_key` | `MESHLITE_API_KEY` | MeshLite secret key (`ml_sk_...`), never sent into the room |
107
+ | `publishable_key` | `MESHLITE_PUBLISHABLE_KEY` | publishable key of the same workspace and environment |
108
+ | `origin` | `MESHLITE_ORIGIN` | exact website origin, declared in the MeshLite console (`https://`, or `http://localhost` with test keys) |
109
+ | `avatar_id` | `MESHLITE_AVATAR_ID` | avatar to show; the workspace default when empty |
110
+ | `language` | none | start language of the lips: `"en"`, `"fr"` or `"zh-CN"` |
111
+ | `max_session_tokens` | `10` | sessions the agent hands out per conversation (page reloads, retries) |
78
112
  | `visitor_identity` | first standard participant | browser participant whose page shows the avatar |
79
113
  | `sample_rate` | `24000` | PCM rate sent to the page (8000 to 48000) |
80
114
  | `clear_buffer_timeout` | `2.0` | seconds to wait for the page to confirm an interruption |
81
115
  | `follow_language` | `True` | send the language of each agent reply to the page (see below) |
82
116
 
117
+ ### How the session reaches the page, safely
118
+
119
+ - The secret key stays in the agent process, on your servers, exactly where your backend
120
+ kept it before. Only the short session token (single use, 120 seconds) enters the room.
121
+ - The origin comes from the agent configuration, never from the room. MeshLite still checks,
122
+ when the page exchanges the token, that the browser's real `Origin` is that origin, that it
123
+ is still allowed, and that the publishable key matches.
124
+ - The token goes only to the visitor participant, by a point-to-point RPC whose caller
125
+ identity is set by the LiveKit server; anyone else gets error `2001`. It is never a
126
+ participant attribute or a broadcast message.
127
+ - The page cannot choose the origin, the avatar or the audio mode: the agent ignores the RPC
128
+ payload. One request at a time, at least one second apart (`2002`), and at most
129
+ `max_session_tokens` per conversation (`2003`).
130
+ - A refusal from MeshLite comes back as error `2001` with `{"code", "retryable"}` in the
131
+ error data; neither keys nor tokens are logged.
132
+
83
133
  ### Language of the lips
84
134
 
85
135
  MeshLite computes the lips with one small speech model per language (English, French,
@@ -117,21 +167,29 @@ You need a MeshLite account on a plan that can embed the SDK on a website, a dec
117
167
  domain, a publishable key and a secret key of the same environment, and an avatar id
118
168
  (all in the MeshLite console).
119
169
 
120
- **1. Your server creates the MeshLite session** with `audio: "livekit"`. The secret key
121
- stays on your server:
170
+ Your server only creates the LiveKit participant token.
171
+
172
+ **1. Ask the agent for the MeshLite session.** The SDK calls `sessionToken` whenever it
173
+ needs a session, so pass a function:
122
174
 
123
175
  ```js
124
- const upstream = await fetch("https://console.meshlite.io/api/v1/client-sessions", {
125
- method: "POST",
126
- headers: { Authorization: `Bearer ${process.env.MESHLITE_SECRET_KEY}`, "Content-Type": "application/json" },
127
- body: JSON.stringify({
128
- publishableKey: process.env.MESHLITE_PUBLISHABLE_KEY,
129
- origin: "https://www.example.com", // set by your server, never copied from the browser
130
- avatar: "your-avatar-id",
131
- audio: "livekit",
132
- }),
133
- });
134
- const { sessionToken } = await upstream.json();
176
+ async function sessionTokenFromAgent(room) {
177
+ for (let attempt = 0; attempt < 30; attempt++) {
178
+ const agent = [...room.remoteParticipants.values()].find((p) => p.isAgent);
179
+ if (agent) {
180
+ try {
181
+ const reply = await room.localParticipant.performRpc({
182
+ destinationIdentity: agent.identity, method: "meshlite.session_token", payload: "{}",
183
+ });
184
+ return JSON.parse(reply).sessionToken;
185
+ } catch (error) {
186
+ if (![1400, 1401, 2002].includes(error.code)) throw error; // agent not ready yet, or busy
187
+ }
188
+ }
189
+ await new Promise((resolve) => setTimeout(resolve, 500));
190
+ }
191
+ throw new Error("The agent did not hand over the MeshLite session.");
192
+ }
135
193
  ```
136
194
 
137
195
  **2. The visitor page mounts the avatar and attaches the room** before connecting:
@@ -142,15 +200,15 @@ const { sessionToken } = await upstream.json();
142
200
  <script type="module">
143
201
  import { Room } from "https://cdn.jsdelivr.net/npm/livekit-client@2.23.0/+esm";
144
202
 
203
+ const room = new Room();
145
204
  const avatar = MeshLite.mount({
146
205
  container: "#avatar",
147
206
  avatar: "your-avatar-id",
148
207
  publishableKey: "ml_pk_live_...",
149
- sessionToken, // from your server (step 1)
208
+ sessionToken: () => sessionTokenFromAgent(room), // from the agent (step 1)
150
209
  audio: "livekit",
151
210
  });
152
211
 
153
- const room = new Room();
154
212
  const link = avatar.attachLiveKit(room); // attach before connect so no speech is missed
155
213
  link.on("ready", ({ output }) => console.log("avatar ready, voice played by", output));
156
214
  link.on("fallback", ({ code }) => console.warn("avatar unavailable, the voice continues", code));
@@ -184,13 +242,15 @@ heard, the agent keeps receiving playback events and interruptions, and `link` e
184
242
  - Maximum session duration: 2 hours.
185
243
  - LiveKit recordings (egress) do not contain the agent voice, since no audio track is
186
244
  published.
187
- - The MeshLite avatar is not a room participant: `avatar.avatar_identity` on the agent side
188
- is the visitor identity.
245
+ - The MeshLite avatar is not a room participant: `avatar.avatar_identity` is the reserved
246
+ name `meshlite-avatar`, which no participant uses (never the visitor), and
247
+ `wait_for_join()` returns once the page has received its MeshLite session.
189
248
 
190
249
  ## Example app
191
250
 
192
251
  [`examples/browser-avatar`](examples/browser-avatar) is a complete local demo: a LiveKit
193
- agent, a small Python server that creates both session tokens, and a page with the avatar.
252
+ agent that starts the MeshLite session, a small Python server that creates the LiveKit
253
+ participant token, and a page with the avatar.
194
254
  Fill in its `.env` once, then one command does everything (virtual environment,
195
255
  dependencies, `.env` check, agent and server together, browser, clean stop on Ctrl+C), on
196
256
  Windows, macOS and Linux:
@@ -6,10 +6,16 @@ voice (or realtime model); MeshLite only renders the face, on the visitor's own
6
6
  or computer.
7
7
 
8
8
  ```
9
- your agent (Python) --lk.audio_stream--> visitor page (livekit-client) --> MeshLite avatar (face + lips)
9
+ your agent (Python) --POST /api/v1/client-sessions (secret key)--> MeshLite
10
+ --meshlite.session_token RPC (visitor only)--> visitor page (livekit-client)
11
+ --lk.audio_stream--> visitor page --> MeshLite avatar (face + lips)
10
12
  <--playback RPCs----
11
13
  ```
12
14
 
15
+ - The agent starts the avatar: `meshlite.AvatarSession(api_key=...)` creates the MeshLite
16
+ session with your secret key and hands its short, single-use token to the visitor page.
17
+ Your web server only issues the LiveKit participant token.
18
+
13
19
  - No video server, no GPU, no extra participant in the room: the agent sends its voice to
14
20
  the visitor page over the LiveKit data channel, using the LiveKit Agents avatar
15
21
  data-stream protocol, and the MeshLite web SDK animates the avatar locally.
@@ -24,7 +30,19 @@ your agent (Python) --lk.audio_stream--> visitor page (livekit-client) --> M
24
30
  pip install livekit-plugins-meshlite
25
31
  ```
26
32
 
27
- Requires Python 3.9+ and `livekit-agents` 1.x.
33
+ Requires Python 3.10+ and `livekit-agents` 1.7 or later.
34
+
35
+ ## Upgrading from 0.2.0
36
+
37
+ 0.2.0 keeps working: there your web server creates the MeshLite session. To stay on it, pin
38
+ `livekit-plugins-meshlite==0.2.0` and follow the [0.2.0 README](https://github.com/meshlite-avatar/livekit-plugins-meshlite/tree/v0.2.0#readme).
39
+ To move to 0.3.0, make three changes:
40
+
41
+ 1. Agent: pass `api_key`, `publishable_key`, `origin` and `avatar_id` to `meshlite.AvatarSession`
42
+ (or set the `MESHLITE_*` environment variables below).
43
+ 2. Server: stop creating the MeshLite session; only issue the LiveKit participant token.
44
+ 3. Page: pass `sessionToken: () => sessionTokenFromAgent(room)` instead of a token from your
45
+ server (see [Browser side](#browser-side)).
28
46
 
29
47
  ## Agent side
30
48
 
@@ -36,24 +54,55 @@ async def entrypoint(ctx: JobContext):
36
54
  await ctx.connect()
37
55
  session = AgentSession(stt=..., llm=..., tts=...) # or a realtime model
38
56
 
39
- avatar = meshlite.AvatarSession() # visitor_identity="..." if several visitors share the room
57
+ avatar = meshlite.AvatarSession(
58
+ api_key=os.environ["MESHLITE_API_KEY"], # secret key ml_sk_..., stays in the agent
59
+ publishable_key=os.environ["MESHLITE_PUBLISHABLE_KEY"],
60
+ origin="https://www.example.com", # the website that shows the face
61
+ avatar_id="your-avatar-id",
62
+ )
40
63
  await avatar.start(session, room=ctx.room) # after ctx.connect(), before session.start()
41
64
 
42
65
  await session.start(agent=Agent(instructions="..."), room=ctx.room)
43
66
  ```
44
67
 
68
+ Each argument can also come from the environment: `MESHLITE_API_KEY`,
69
+ `MESHLITE_PUBLISHABLE_KEY`, `MESHLITE_ORIGIN`, `MESHLITE_AVATAR_ID` (and `MESHLITE_API_URL`).
70
+
45
71
  `AvatarSession.start()` waits for the visitor participant (the first standard participant,
46
- or `visitor_identity`) and replaces the session audio output with LiveKit's
47
- `DataStreamAudioOutput`. The agent then publishes no audio track: its voice reaches the
48
- page as data and the MeshLite SDK plays it in sync with the face.
72
+ or `visitor_identity`), offers the MeshLite session to that participant with the RPC
73
+ `meshlite.session_token`, and installs LiveKit's `DataStreamAudioOutput` as the session
74
+ audio output. The agent then publishes no audio track: its voice reaches the page as data
75
+ and the MeshLite SDK plays it in sync with the face.
49
76
 
50
77
  | Argument | Default | Meaning |
51
78
  |---|---|---|
79
+ | `api_key` | `MESHLITE_API_KEY` | MeshLite secret key (`ml_sk_...`), never sent into the room |
80
+ | `publishable_key` | `MESHLITE_PUBLISHABLE_KEY` | publishable key of the same workspace and environment |
81
+ | `origin` | `MESHLITE_ORIGIN` | exact website origin, declared in the MeshLite console (`https://`, or `http://localhost` with test keys) |
82
+ | `avatar_id` | `MESHLITE_AVATAR_ID` | avatar to show; the workspace default when empty |
83
+ | `language` | none | start language of the lips: `"en"`, `"fr"` or `"zh-CN"` |
84
+ | `max_session_tokens` | `10` | sessions the agent hands out per conversation (page reloads, retries) |
52
85
  | `visitor_identity` | first standard participant | browser participant whose page shows the avatar |
53
86
  | `sample_rate` | `24000` | PCM rate sent to the page (8000 to 48000) |
54
87
  | `clear_buffer_timeout` | `2.0` | seconds to wait for the page to confirm an interruption |
55
88
  | `follow_language` | `True` | send the language of each agent reply to the page (see below) |
56
89
 
90
+ ### How the session reaches the page, safely
91
+
92
+ - The secret key stays in the agent process, on your servers, exactly where your backend
93
+ kept it before. Only the short session token (single use, 120 seconds) enters the room.
94
+ - The origin comes from the agent configuration, never from the room. MeshLite still checks,
95
+ when the page exchanges the token, that the browser's real `Origin` is that origin, that it
96
+ is still allowed, and that the publishable key matches.
97
+ - The token goes only to the visitor participant, by a point-to-point RPC whose caller
98
+ identity is set by the LiveKit server; anyone else gets error `2001`. It is never a
99
+ participant attribute or a broadcast message.
100
+ - The page cannot choose the origin, the avatar or the audio mode: the agent ignores the RPC
101
+ payload. One request at a time, at least one second apart (`2002`), and at most
102
+ `max_session_tokens` per conversation (`2003`).
103
+ - A refusal from MeshLite comes back as error `2001` with `{"code", "retryable"}` in the
104
+ error data; neither keys nor tokens are logged.
105
+
57
106
  ### Language of the lips
58
107
 
59
108
  MeshLite computes the lips with one small speech model per language (English, French,
@@ -91,21 +140,29 @@ You need a MeshLite account on a plan that can embed the SDK on a website, a dec
91
140
  domain, a publishable key and a secret key of the same environment, and an avatar id
92
141
  (all in the MeshLite console).
93
142
 
94
- **1. Your server creates the MeshLite session** with `audio: "livekit"`. The secret key
95
- stays on your server:
143
+ Your server only creates the LiveKit participant token.
144
+
145
+ **1. Ask the agent for the MeshLite session.** The SDK calls `sessionToken` whenever it
146
+ needs a session, so pass a function:
96
147
 
97
148
  ```js
98
- const upstream = await fetch("https://console.meshlite.io/api/v1/client-sessions", {
99
- method: "POST",
100
- headers: { Authorization: `Bearer ${process.env.MESHLITE_SECRET_KEY}`, "Content-Type": "application/json" },
101
- body: JSON.stringify({
102
- publishableKey: process.env.MESHLITE_PUBLISHABLE_KEY,
103
- origin: "https://www.example.com", // set by your server, never copied from the browser
104
- avatar: "your-avatar-id",
105
- audio: "livekit",
106
- }),
107
- });
108
- const { sessionToken } = await upstream.json();
149
+ async function sessionTokenFromAgent(room) {
150
+ for (let attempt = 0; attempt < 30; attempt++) {
151
+ const agent = [...room.remoteParticipants.values()].find((p) => p.isAgent);
152
+ if (agent) {
153
+ try {
154
+ const reply = await room.localParticipant.performRpc({
155
+ destinationIdentity: agent.identity, method: "meshlite.session_token", payload: "{}",
156
+ });
157
+ return JSON.parse(reply).sessionToken;
158
+ } catch (error) {
159
+ if (![1400, 1401, 2002].includes(error.code)) throw error; // agent not ready yet, or busy
160
+ }
161
+ }
162
+ await new Promise((resolve) => setTimeout(resolve, 500));
163
+ }
164
+ throw new Error("The agent did not hand over the MeshLite session.");
165
+ }
109
166
  ```
110
167
 
111
168
  **2. The visitor page mounts the avatar and attaches the room** before connecting:
@@ -116,15 +173,15 @@ const { sessionToken } = await upstream.json();
116
173
  <script type="module">
117
174
  import { Room } from "https://cdn.jsdelivr.net/npm/livekit-client@2.23.0/+esm";
118
175
 
176
+ const room = new Room();
119
177
  const avatar = MeshLite.mount({
120
178
  container: "#avatar",
121
179
  avatar: "your-avatar-id",
122
180
  publishableKey: "ml_pk_live_...",
123
- sessionToken, // from your server (step 1)
181
+ sessionToken: () => sessionTokenFromAgent(room), // from the agent (step 1)
124
182
  audio: "livekit",
125
183
  });
126
184
 
127
- const room = new Room();
128
185
  const link = avatar.attachLiveKit(room); // attach before connect so no speech is missed
129
186
  link.on("ready", ({ output }) => console.log("avatar ready, voice played by", output));
130
187
  link.on("fallback", ({ code }) => console.warn("avatar unavailable, the voice continues", code));
@@ -158,13 +215,15 @@ heard, the agent keeps receiving playback events and interruptions, and `link` e
158
215
  - Maximum session duration: 2 hours.
159
216
  - LiveKit recordings (egress) do not contain the agent voice, since no audio track is
160
217
  published.
161
- - The MeshLite avatar is not a room participant: `avatar.avatar_identity` on the agent side
162
- is the visitor identity.
218
+ - The MeshLite avatar is not a room participant: `avatar.avatar_identity` is the reserved
219
+ name `meshlite-avatar`, which no participant uses (never the visitor), and
220
+ `wait_for_join()` returns once the page has received its MeshLite session.
163
221
 
164
222
  ## Example app
165
223
 
166
224
  [`examples/browser-avatar`](examples/browser-avatar) is a complete local demo: a LiveKit
167
- agent, a small Python server that creates both session tokens, and a page with the avatar.
225
+ agent that starts the MeshLite session, a small Python server that creates the LiveKit
226
+ participant token, and a page with the avatar.
168
227
  Fill in its `.env` once, then one command does everything (virtual environment,
169
228
  dependencies, `.env` check, agent and server together, browser, clean stop on Ctrl+C), on
170
229
  Windows, macOS and Linux:
@@ -5,16 +5,31 @@ See https://console.meshlite.io for the web SDK that renders the avatar.
5
5
 
6
6
  from livekit.agents import Plugin
7
7
 
8
- from .avatar import DEFAULT_SAMPLE_RATE, SET_LANGUAGE_RPC, AvatarSession
8
+ from .api import DEFAULT_API_URL, MeshLiteError
9
+ from .avatar import (
10
+ DEFAULT_SAMPLE_RATE,
11
+ SESSION_BUSY_ERROR,
12
+ SESSION_FAILED_ERROR,
13
+ SESSION_LIMIT_ERROR,
14
+ SESSION_TOKEN_RPC,
15
+ SET_LANGUAGE_RPC,
16
+ AvatarSession,
17
+ )
9
18
  from .languages import MESHLITE_LANGUAGES, spoken_language_of
10
19
  from .log import logger
11
20
  from .version import __version__
12
21
 
13
22
  __all__ = [
23
+ "DEFAULT_API_URL",
14
24
  "DEFAULT_SAMPLE_RATE",
15
25
  "MESHLITE_LANGUAGES",
26
+ "SESSION_BUSY_ERROR",
27
+ "SESSION_FAILED_ERROR",
28
+ "SESSION_LIMIT_ERROR",
29
+ "SESSION_TOKEN_RPC",
16
30
  "SET_LANGUAGE_RPC",
17
31
  "AvatarSession",
32
+ "MeshLiteError",
18
33
  "__version__",
19
34
  "spoken_language_of",
20
35
  ]
@@ -0,0 +1,137 @@
1
+ """Minimal client of the MeshLite control plane used by the agent.
2
+
3
+ Only one call: ``POST /api/v1/client-sessions`` with ``audio: "livekit"``,
4
+ authenticated with the workspace secret key. The response carries a short,
5
+ single-use ``sessionToken`` bound to the website origin and to the
6
+ publishable key; the visitor page exchanges it, from that origin only, to
7
+ open the face.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import ipaddress
14
+ from dataclasses import dataclass
15
+ from urllib.parse import urlsplit
16
+
17
+ import aiohttp
18
+
19
+ DEFAULT_API_URL = "https://console.meshlite.io"
20
+ CLIENT_SESSIONS_PATH = "/api/v1/client-sessions"
21
+ _LOCAL_HOSTS = {"localhost", "127.0.0.1", "::1"}
22
+
23
+
24
+ class MeshLiteError(Exception):
25
+ """The MeshLite control plane refused or could not create a session."""
26
+
27
+ def __init__(
28
+ self, message: str, *, code: str = "UNKNOWN", status: int | None = None, retryable: bool = False
29
+ ) -> None:
30
+ super().__init__(message)
31
+ self.code = code
32
+ self.status = status
33
+ self.retryable = retryable
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class ClientSession:
38
+ session_token: str
39
+ expires_at: str | None
40
+
41
+
42
+ def _is_local(host: str | None) -> bool:
43
+ if not host:
44
+ return False
45
+ if host in _LOCAL_HOSTS:
46
+ return True
47
+ try:
48
+ return ipaddress.ip_address(host).is_loopback
49
+ except ValueError:
50
+ return False
51
+
52
+
53
+ def normalize_origin(value: str) -> str:
54
+ """Return ``scheme://host[:port]`` or raise ``ValueError``.
55
+
56
+ The origin is the website that embeds the face. It is chosen by the
57
+ developer in the agent configuration, never read from the room: the
58
+ visitor controls what its own participant says.
59
+ """
60
+ if not isinstance(value, str) or not value.strip():
61
+ raise ValueError("origin must be the website origin, for example https://www.example.com")
62
+ parts = urlsplit(value.strip())
63
+ if (
64
+ parts.scheme not in ("https", "http")
65
+ or not parts.hostname
66
+ or parts.username
67
+ or parts.password
68
+ or parts.path not in ("", "/")
69
+ or parts.query
70
+ or parts.fragment
71
+ ):
72
+ raise ValueError("origin must be an exact origin without a path, e.g. https://www.example.com")
73
+ if parts.scheme == "http" and not _is_local(parts.hostname):
74
+ raise ValueError("origin must use https (http is accepted for localhost only)")
75
+ return f"{parts.scheme}://{parts.netloc.lower()}"
76
+
77
+
78
+ def normalize_api_url(value: str) -> str:
79
+ parts = urlsplit(value.strip() if isinstance(value, str) else "")
80
+ if parts.scheme not in ("https", "http") or not parts.hostname:
81
+ raise ValueError("api_url must be an absolute URL, e.g. https://console.meshlite.io")
82
+ if parts.scheme == "http" and not _is_local(parts.hostname):
83
+ # The secret key travels in this request: never in clear text.
84
+ raise ValueError("api_url must use https (http is accepted for localhost only)")
85
+ return f"{parts.scheme}://{parts.netloc}{parts.path.rstrip('/')}"
86
+
87
+
88
+ async def create_client_session(
89
+ http: aiohttp.ClientSession,
90
+ *,
91
+ api_url: str,
92
+ api_key: str,
93
+ publishable_key: str,
94
+ origin: str,
95
+ avatar: str | None,
96
+ language: str | None,
97
+ timeout: float = 10.0,
98
+ ) -> ClientSession:
99
+ body: dict[str, object] = {
100
+ "publishableKey": publishable_key,
101
+ "origin": origin,
102
+ "audio": "livekit",
103
+ }
104
+ if avatar:
105
+ body["avatar"] = avatar
106
+ if language:
107
+ body["conversation"] = {"language": language}
108
+ try:
109
+ async with http.post(
110
+ api_url + CLIENT_SESSIONS_PATH,
111
+ json=body,
112
+ headers={"Authorization": f"Bearer {api_key}"},
113
+ timeout=aiohttp.ClientTimeout(total=timeout),
114
+ allow_redirects=False,
115
+ ) as response:
116
+ try:
117
+ data = await response.json(content_type=None)
118
+ except ValueError:
119
+ data = None
120
+ if response.status != 201 and response.status != 200:
121
+ error = data.get("error") if isinstance(data, dict) else None
122
+ error = error if isinstance(error, dict) else {}
123
+ raise MeshLiteError(
124
+ "MeshLite refused to create the avatar session",
125
+ code=str(error.get("code") or "HTTP_" + str(response.status)),
126
+ status=response.status,
127
+ retryable=bool(error.get("retryable")) or response.status >= 500,
128
+ )
129
+ except (aiohttp.ClientError, asyncio.TimeoutError) as error:
130
+ raise MeshLiteError(
131
+ "MeshLite could not be reached", code="NETWORK", retryable=True
132
+ ) from error
133
+ token = data.get("sessionToken") if isinstance(data, dict) else None
134
+ if not isinstance(token, str) or not token:
135
+ raise MeshLiteError("MeshLite answered without a session token", code="BAD_RESPONSE")
136
+ expires_at = data.get("expiresAt")
137
+ return ClientSession(session_token=token, expires_at=expires_at if isinstance(expires_at, str) else None)
@@ -0,0 +1,417 @@
1
+ """MeshLite avatar for LiveKit Agents.
2
+
3
+ The MeshLite face is drawn on the visitor's own device, by the MeshLite web
4
+ SDK in the visitor's page. There is no avatar participant and no video track.
5
+
6
+ What the agent does (:class:`AvatarSession`):
7
+
8
+ 1. **Starts the MeshLite session.** With the workspace secret key
9
+ (``MESHLITE_API_KEY``), the agent creates the face session on the MeshLite
10
+ control plane (``audio: "livekit"``). The session token is short-lived,
11
+ single-use and bound to the website origin set in the agent configuration
12
+ (``MESHLITE_ORIGIN``, authorized in the MeshLite console) and to the
13
+ publishable key; the page can only open it from that origin.
14
+ 2. **Hands it to the visitor page only.** The page asks for it with the RPC
15
+ ``meshlite.session_token``. The agent answers the visitor participant
16
+ only (caller identity set by the LiveKit server), one request at a time,
17
+ with a cap per session.
18
+ 3. **Routes its voice to the page** with the avatar data-stream protocol
19
+ (``lk.audio_stream`` + ``lk.clear_buffer`` / ``lk.playback_*`` RPCs), as
20
+ the other avatar plugins do between the agent and their avatar worker.
21
+ 4. **Keeps the lips in the agent's language.** After each reply whose
22
+ language is clear, RPC ``meshlite.set_language``
23
+ (``{"language": "en" | "fr" | "zh-CN"}``) so the page loads the lip model
24
+ of the language the agent really speaks.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import asyncio
30
+ import json
31
+ import os
32
+ import time
33
+
34
+ import aiohttp
35
+
36
+ from livekit import rtc
37
+ from livekit.agents import AgentSession, utils
38
+ from livekit.agents.metrics.base import AvatarMetrics, Metadata
39
+ from livekit.agents.voice.avatar import AvatarSession as BaseAvatarSession, DataStreamAudioOutput
40
+
41
+ from .api import (
42
+ DEFAULT_API_URL,
43
+ MeshLiteError,
44
+ create_client_session,
45
+ normalize_api_url,
46
+ normalize_origin,
47
+ )
48
+ from .languages import MESHLITE_LANGUAGES, spoken_language_of
49
+ from .log import logger
50
+
51
+ DEFAULT_SAMPLE_RATE = 24000
52
+ _MIN_SAMPLE_RATE = 8000
53
+ _MAX_SAMPLE_RATE = 48000
54
+
55
+ SESSION_TOKEN_RPC = "meshlite.session_token"
56
+ SET_LANGUAGE_RPC = "meshlite.set_language"
57
+ _SET_LANGUAGE_TIMEOUT = 5.0
58
+
59
+ # RPC error codes returned to the page (application range, outside 1xxx).
60
+ SESSION_FAILED_ERROR = 2001 # refused (not the visitor, or MeshLite said no)
61
+ SESSION_BUSY_ERROR = 2002 # retry in a moment
62
+ SESSION_LIMIT_ERROR = 2003 # no more sessions for this conversation
63
+
64
+ DEFAULT_MAX_SESSION_TOKENS = 10
65
+ _TOKEN_MIN_INTERVAL = 1.0
66
+ _HTTP_TIMEOUT = 8.0
67
+
68
+ # Reserved identity: MeshLite never joins the room. Reporting a name that no
69
+ # participant uses keeps the base cleanup from ever removing the visitor.
70
+ _AVATAR_IDENTITY = "meshlite-avatar"
71
+
72
+
73
+ class AvatarSession(BaseAvatarSession):
74
+ """A MeshLite avatar session, drawn on the visitor's device.
75
+
76
+ Call :meth:`start` after ``await ctx.connect()`` and **before**
77
+ ``await session.start(...)``.
78
+
79
+ Args:
80
+ api_key: MeshLite secret key (``ml_sk_...``). Defaults to
81
+ ``MESHLITE_API_KEY``. Stays in the agent; never sent to the room.
82
+ publishable_key: MeshLite publishable key (``ml_pk_...``), the one the
83
+ page mounts the face with. Defaults to ``MESHLITE_PUBLISHABLE_KEY``.
84
+ origin: origin of the website that shows the face, exactly as
85
+ authorized in the MeshLite console (``https://www.example.com``).
86
+ Defaults to ``MESHLITE_ORIGIN``. Set by you, never read from the
87
+ room.
88
+ avatar_id: MeshLite avatar to show. Defaults to ``MESHLITE_AVATAR_ID``,
89
+ else the workspace default avatar.
90
+ language: language the agent starts in (``"en"``, ``"fr"`` or
91
+ ``"zh-CN"``): it picks the first lip model.
92
+ visitor_identity: identity of the browser participant whose page shows
93
+ the face. When omitted, the first standard (non-agent, non-SIP)
94
+ remote participant, the one :class:`AgentSession` links to.
95
+ sample_rate: PCM rate sent to the page. 24 kHz matches the engine.
96
+ clear_buffer_timeout: seconds to wait for the page to confirm an
97
+ interruption before the speech is considered stopped.
98
+ follow_language: after each reply, tell the page the language the
99
+ agent spoke (when it is clear) so the lips follow a conversation
100
+ that changes language.
101
+ max_session_tokens: how many session tokens the visitor page may get
102
+ during this session (first start plus reloads and retries).
103
+ api_url: MeshLite control plane. Defaults to ``MESHLITE_API_URL``,
104
+ else ``https://console.meshlite.io``.
105
+ http_session: optional ``aiohttp.ClientSession``; by default the job's
106
+ shared session.
107
+ """
108
+
109
+ def __init__(
110
+ self,
111
+ *,
112
+ api_key: str | None = None,
113
+ publishable_key: str | None = None,
114
+ origin: str | None = None,
115
+ avatar_id: str | None = None,
116
+ language: str | None = None,
117
+ visitor_identity: str | None = None,
118
+ sample_rate: int = DEFAULT_SAMPLE_RATE,
119
+ clear_buffer_timeout: float | None = 2.0,
120
+ follow_language: bool = True,
121
+ max_session_tokens: int = DEFAULT_MAX_SESSION_TOKENS,
122
+ api_url: str | None = None,
123
+ http_session: aiohttp.ClientSession | None = None,
124
+ ) -> None:
125
+ super().__init__()
126
+ api_key = api_key or os.getenv("MESHLITE_API_KEY")
127
+ publishable_key = publishable_key or os.getenv("MESHLITE_PUBLISHABLE_KEY")
128
+ origin = origin or os.getenv("MESHLITE_ORIGIN")
129
+ avatar_id = avatar_id or os.getenv("MESHLITE_AVATAR_ID") or None
130
+ api_url = api_url or os.getenv("MESHLITE_API_URL") or DEFAULT_API_URL
131
+ if not api_key:
132
+ raise ValueError("MESHLITE_API_KEY must be set by argument or environment variable")
133
+ if not publishable_key:
134
+ raise ValueError(
135
+ "MESHLITE_PUBLISHABLE_KEY must be set by argument or environment variable"
136
+ )
137
+ if api_key == publishable_key:
138
+ raise ValueError("api_key must be the secret key, not the publishable key")
139
+ if not origin:
140
+ raise ValueError(
141
+ "MESHLITE_ORIGIN must be set: the website origin authorized in the MeshLite console"
142
+ )
143
+ if language is not None and language not in MESHLITE_LANGUAGES:
144
+ raise ValueError(f"language must be one of {', '.join(MESHLITE_LANGUAGES)}")
145
+ if visitor_identity is not None and (
146
+ not isinstance(visitor_identity, str) or not visitor_identity.strip()
147
+ ):
148
+ raise ValueError("visitor_identity must be a non-empty string")
149
+ if (
150
+ isinstance(sample_rate, bool)
151
+ or not isinstance(sample_rate, int)
152
+ or not _MIN_SAMPLE_RATE <= sample_rate <= _MAX_SAMPLE_RATE
153
+ ):
154
+ raise ValueError(
155
+ f"sample_rate must be an integer between {_MIN_SAMPLE_RATE} and {_MAX_SAMPLE_RATE}"
156
+ )
157
+ if clear_buffer_timeout is not None and not clear_buffer_timeout >= 0:
158
+ raise ValueError("clear_buffer_timeout must be >= 0 or None")
159
+ if isinstance(max_session_tokens, bool) or not isinstance(max_session_tokens, int) or max_session_tokens < 1:
160
+ raise ValueError("max_session_tokens must be a positive integer")
161
+
162
+ self._api_key = api_key
163
+ self._publishable_key = publishable_key
164
+ self._origin = normalize_origin(origin)
165
+ self._api_url = normalize_api_url(api_url)
166
+ self._avatar_id = avatar_id
167
+ self._start_language = language
168
+ self._visitor_identity = visitor_identity
169
+ self._sample_rate = sample_rate
170
+ self._clear_buffer_timeout = clear_buffer_timeout
171
+ self._follow_language = bool(follow_language)
172
+ self._max_session_tokens = max_session_tokens
173
+ self._http_session = http_session
174
+ self._own_http_session: aiohttp.ClientSession | None = None
175
+
176
+ self._audio_output: DataStreamAudioOutput | None = None
177
+ self._starting = False
178
+ self._started = False
179
+ self._closed = False
180
+ self._language: str | None = language
181
+ self._language_lock = asyncio.Lock()
182
+ self._tasks: set[asyncio.Task[None]] = set()
183
+ self._token_busy = False
184
+ self._tokens_issued = 0
185
+ self._last_token_at = 0.0
186
+ self._session_handed: asyncio.Event = asyncio.Event()
187
+
188
+ @property
189
+ def provider(self) -> str:
190
+ return "meshlite"
191
+
192
+ @property
193
+ def avatar_identity(self) -> str:
194
+ """Reserved identity, never used by a participant.
195
+
196
+ The face is drawn in the visitor's page: MeshLite adds no participant
197
+ to the room, so there is nothing to remove when the session closes.
198
+ """
199
+ return _AVATAR_IDENTITY
200
+
201
+ @property
202
+ def visitor_identity(self) -> str | None:
203
+ """Identity of the participant whose page shows the face (known after start)."""
204
+ return self._visitor_identity
205
+
206
+ @property
207
+ def audio_output(self) -> DataStreamAudioOutput | None:
208
+ return self._audio_output
209
+
210
+ @property
211
+ def origin(self) -> str:
212
+ """Website origin the MeshLite sessions are bound to."""
213
+ return self._origin
214
+
215
+ @property
216
+ def language(self) -> str | None:
217
+ """Language of the current lip model, as far as the agent knows."""
218
+ return self._language
219
+
220
+ async def start(self, agent_session: AgentSession, room: rtc.Room) -> None:
221
+ if self._closed:
222
+ raise RuntimeError("this MeshLite AvatarSession is closed")
223
+ if self._starting or self._started:
224
+ raise RuntimeError("MeshLite AvatarSession.start() can only be called once")
225
+ self._starting = True
226
+ try:
227
+ identity = self._visitor_identity
228
+ if identity is None:
229
+ if not room.isconnected():
230
+ raise RuntimeError(
231
+ "connect to the room (await ctx.connect()) before starting the MeshLite "
232
+ "avatar, or pass visitor_identity"
233
+ )
234
+ logger.debug("waiting for the visitor participant")
235
+ participant = await utils.wait_for_participant(
236
+ room, kind=rtc.ParticipantKind.PARTICIPANT_KIND_STANDARD
237
+ )
238
+ identity = participant.identity
239
+ if self._closed:
240
+ raise RuntimeError("this MeshLite AvatarSession was closed while starting")
241
+ self._visitor_identity = identity
242
+
243
+ await super().start(agent_session, room)
244
+
245
+ room.local_participant.register_rpc_method(SESSION_TOKEN_RPC, self._on_session_token)
246
+
247
+ output = DataStreamAudioOutput(
248
+ room,
249
+ destination_identity=identity,
250
+ sample_rate=self._sample_rate,
251
+ clear_buffer_timeout=self._clear_buffer_timeout,
252
+ # the page reports when the face really starts speaking
253
+ wait_playback_start=True,
254
+ )
255
+ agent_session.output.replace_audio_tail(output)
256
+ self._audio_output = output
257
+
258
+ if self._follow_language:
259
+ agent_session.on("conversation_item_added", self._on_reply_language)
260
+ self._started = True
261
+ logger.debug(
262
+ "MeshLite avatar ready for the visitor page",
263
+ extra={"visitor_identity": identity, "origin": self._origin},
264
+ )
265
+ finally:
266
+ self._starting = False
267
+
268
+ async def aclose(self) -> None:
269
+ if self._closed:
270
+ return
271
+ self._closed = True
272
+ room, session = self._room, self._agent_session
273
+ if room is not None and self._started:
274
+ room.local_participant.unregister_rpc_method(SESSION_TOKEN_RPC)
275
+ if session is not None and self._follow_language and self._started:
276
+ session.off("conversation_item_added", self._on_reply_language)
277
+ for task in list(self._tasks):
278
+ task.cancel()
279
+ await super().aclose()
280
+ if self._own_http_session is not None:
281
+ await self._own_http_session.close()
282
+ self._own_http_session = None
283
+
284
+ # -- session token -----------------------------------------------------
285
+
286
+ def _http(self) -> aiohttp.ClientSession:
287
+ if self._http_session is not None:
288
+ return self._http_session
289
+ try:
290
+ return utils.http_context.http_session()
291
+ except RuntimeError:
292
+ if self._own_http_session is None:
293
+ self._own_http_session = aiohttp.ClientSession()
294
+ return self._own_http_session
295
+
296
+ async def _on_session_token(self, data: rtc.RpcInvocationData) -> str:
297
+ # Only the visitor whose page shows the face gets a session. The caller
298
+ # identity is set by the LiveKit server, not by the caller.
299
+ if data.caller_identity != self._visitor_identity or self._closed:
300
+ raise rtc.RpcError(SESSION_FAILED_ERROR, "not the visitor of this avatar")
301
+ if self._token_busy:
302
+ raise rtc.RpcError(SESSION_BUSY_ERROR, "a session is already being created")
303
+ if self._tokens_issued >= self._max_session_tokens:
304
+ raise rtc.RpcError(SESSION_LIMIT_ERROR, "session limit reached for this conversation")
305
+ now = time.monotonic()
306
+ if self._tokens_issued and now - self._last_token_at < _TOKEN_MIN_INTERVAL:
307
+ raise rtc.RpcError(SESSION_BUSY_ERROR, "too many session requests, retry in a moment")
308
+ self._token_busy = True
309
+ try:
310
+ session = await create_client_session(
311
+ self._http(),
312
+ api_url=self._api_url,
313
+ api_key=self._api_key,
314
+ publishable_key=self._publishable_key,
315
+ origin=self._origin,
316
+ avatar=self._avatar_id,
317
+ language=self._language or self._start_language,
318
+ timeout=_HTTP_TIMEOUT,
319
+ )
320
+ except MeshLiteError as error:
321
+ logger.warning(
322
+ "MeshLite could not create the avatar session",
323
+ extra={"code": error.code, "status": error.status},
324
+ )
325
+ raise rtc.RpcError(
326
+ SESSION_FAILED_ERROR,
327
+ "MeshLite session unavailable",
328
+ json.dumps({"code": error.code, "retryable": error.retryable}),
329
+ ) from None
330
+ finally:
331
+ self._token_busy = False
332
+ self._tokens_issued += 1
333
+ self._last_token_at = time.monotonic()
334
+ self._session_handed.set()
335
+ logger.debug("MeshLite session handed to the visitor page")
336
+ return json.dumps({"sessionToken": session.session_token, "expiresAt": session.expires_at})
337
+
338
+ async def _wait_avatar_join(self) -> None:
339
+ # No avatar participant: the face has started once the visitor page
340
+ # received its MeshLite session.
341
+ started_time = time.time()
342
+ await self._session_handed.wait()
343
+ joined_time = time.time()
344
+ self._emit_metrics(
345
+ AvatarMetrics(
346
+ timestamp=joined_time,
347
+ session_started_time=started_time,
348
+ avatar_joined_time=joined_time,
349
+ metadata=Metadata(model_provider=self.provider),
350
+ )
351
+ )
352
+
353
+ # -- language ----------------------------------------------------------
354
+
355
+ async def set_language(self, language: str) -> bool:
356
+ """Ask the page to load the lip model of ``language``.
357
+
358
+ Use it when your agent switches language on its own terms; with
359
+ ``follow_language=True`` the plugin already does it after each reply.
360
+
361
+ Args:
362
+ language: ``"en"``, ``"fr"`` or ``"zh-CN"``.
363
+
364
+ Returns:
365
+ ``True`` when the page applied it, ``False`` when it could not
366
+ (older SDK, page not attached yet).
367
+ """
368
+ if language not in MESHLITE_LANGUAGES:
369
+ raise ValueError(f"language must be one of {', '.join(MESHLITE_LANGUAGES)}")
370
+ room, identity = self._room, self._visitor_identity
371
+ if self._closed or not self._started or room is None or identity is None:
372
+ raise RuntimeError("start the MeshLite AvatarSession before setting its language")
373
+ async with self._language_lock:
374
+ if language == self._language:
375
+ return True
376
+ try:
377
+ await room.local_participant.perform_rpc(
378
+ destination_identity=identity,
379
+ method=SET_LANGUAGE_RPC,
380
+ payload=json.dumps({"language": language}),
381
+ response_timeout=_SET_LANGUAGE_TIMEOUT,
382
+ )
383
+ except rtc.RpcError as error:
384
+ if error.code == rtc.RpcError.ErrorCode.UNSUPPORTED_METHOD:
385
+ logger.info(
386
+ "the visitor page does not follow the agent language yet "
387
+ "(MeshLite web SDK 1.11.62 or later, attachLiveKit(room))",
388
+ extra={"language": language},
389
+ )
390
+ else:
391
+ logger.warning(
392
+ "the visitor page did not change the avatar language",
393
+ extra={"language": language, "error": error.message},
394
+ )
395
+ return False
396
+ self._language = language
397
+ return True
398
+
399
+ def _on_reply_language(self, event: object) -> None:
400
+ item = getattr(event, "item", None)
401
+ if getattr(item, "role", None) != "assistant":
402
+ return
403
+ text = getattr(item, "text_content", None)
404
+ language = spoken_language_of(text) if isinstance(text, str) else None
405
+ if language is None or language == self._language or self._closed:
406
+ return
407
+ task = asyncio.ensure_future(self._follow(language))
408
+ self._tasks.add(task)
409
+ task.add_done_callback(self._tasks.discard)
410
+
411
+ async def _follow(self, language: str) -> None:
412
+ try:
413
+ await self.set_language(language)
414
+ except asyncio.CancelledError:
415
+ raise
416
+ except Exception: # noqa: BLE001 - never break the agent for a lip model
417
+ logger.exception("could not send the avatar language")
@@ -0,0 +1 @@
1
+ __version__ = "0.3.0"
@@ -5,11 +5,11 @@ build-backend = "hatchling.build"
5
5
  [project]
6
6
  name = "livekit-plugins-meshlite"
7
7
  dynamic = ["version"]
8
- description = "MeshLite avatar for LiveKit Agents: the agent voice drives a lip-synced avatar drawn on the user's own device"
8
+ description = "MeshLite avatar for LiveKit Agents: the agent starts a lip-synced avatar drawn on the user's own device"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
11
11
  license-files = ["LICENSE"]
12
- requires-python = ">=3.9"
12
+ requires-python = ">=3.10"
13
13
  authors = [{ name = "MeshLite" }]
14
14
  keywords = ["livekit", "agents", "avatar", "meshlite", "webrtc", "realtime", "lip-sync"]
15
15
  classifiers = [
@@ -21,7 +21,7 @@ classifiers = [
21
21
  "Programming Language :: Python :: 3 :: Only",
22
22
  "Typing :: Typed",
23
23
  ]
24
- dependencies = ["livekit-agents>=1.0.0,<2"]
24
+ dependencies = ["livekit-agents>=1.7.0,<2", "aiohttp>=3.9"]
25
25
 
26
26
  [project.optional-dependencies]
27
27
  test = ["pytest>=8", "pytest-asyncio>=0.23"]
@@ -1,278 +0,0 @@
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
- MeshLite addition: after each agent reply whose language is clear, RPC
17
- ``meshlite.set_language`` (``{"language": "en" | "fr" | "zh-CN"}``) so the page
18
- loads the lip model of the language the agent really speaks. The web SDK
19
- (1.11.62 and later) answers it inside ``attachLiveKit(room)``; older pages
20
- answer "unsupported method" and keep their language.
21
- """
22
-
23
- from __future__ import annotations
24
-
25
- import asyncio
26
- import inspect
27
- import json
28
-
29
- from livekit import rtc
30
- from livekit.agents import AgentSession, utils
31
- from livekit.agents.voice.avatar import DataStreamAudioOutput
32
-
33
- from .languages import MESHLITE_LANGUAGES, spoken_language_of
34
- from .log import logger
35
-
36
- DEFAULT_SAMPLE_RATE = 24000
37
- _MIN_SAMPLE_RATE = 8000
38
- _MAX_SAMPLE_RATE = 48000
39
- SET_LANGUAGE_RPC = "meshlite.set_language"
40
- _SET_LANGUAGE_TIMEOUT = 5.0
41
-
42
- try:
43
- _OUTPUT_PARAMS = inspect.signature(DataStreamAudioOutput.__init__).parameters
44
- except (TypeError, ValueError): # pragma: no cover - exotic builds
45
- _OUTPUT_PARAMS = {}
46
-
47
-
48
- class AvatarSession:
49
- """Route an :class:`~livekit.agents.AgentSession` voice to a MeshLite avatar.
50
-
51
- Call :meth:`start` after ``await ctx.connect()`` and **before**
52
- ``await session.start(...)``: the agent then sends its voice to the
53
- visitor's page instead of publishing an audio track, and the page plays
54
- it in sync with the avatar's face.
55
-
56
- Args:
57
- visitor_identity: identity of the browser participant whose page
58
- shows the avatar. When omitted, the first standard (non-agent,
59
- non-SIP) remote participant of the room is used, which is the
60
- participant :class:`AgentSession` links to by default.
61
- sample_rate: PCM rate sent to the page. The page converts any rate;
62
- 24 kHz matches the MeshLite engine and keeps the stream small.
63
- clear_buffer_timeout: seconds the agent waits for the page to confirm
64
- an interruption before it considers the speech stopped.
65
- follow_language: after each reply, tell the page the language the
66
- agent spoke (English, French or Mandarin Chinese, when it is
67
- clear) so the lips follow a conversation that changes language.
68
- The new lip model takes over from the next reply.
69
- """
70
-
71
- def __init__(
72
- self,
73
- *,
74
- visitor_identity: str | None = None,
75
- sample_rate: int = DEFAULT_SAMPLE_RATE,
76
- clear_buffer_timeout: float | None = 2.0,
77
- follow_language: bool = True,
78
- ) -> None:
79
- if visitor_identity is not None and (
80
- not isinstance(visitor_identity, str) or not visitor_identity.strip()
81
- ):
82
- raise ValueError("visitor_identity must be a non-empty string")
83
- if (
84
- isinstance(sample_rate, bool)
85
- or not isinstance(sample_rate, int)
86
- or not _MIN_SAMPLE_RATE <= sample_rate <= _MAX_SAMPLE_RATE
87
- ):
88
- raise ValueError(
89
- f"sample_rate must be an integer between {_MIN_SAMPLE_RATE} and {_MAX_SAMPLE_RATE}"
90
- )
91
- if clear_buffer_timeout is not None and not clear_buffer_timeout >= 0:
92
- raise ValueError("clear_buffer_timeout must be >= 0 or None")
93
-
94
- self._visitor_identity = visitor_identity
95
- self._sample_rate = sample_rate
96
- self._clear_buffer_timeout = clear_buffer_timeout
97
- self._audio_output: DataStreamAudioOutput | None = None
98
- self._agent_session: AgentSession | None = None
99
- self._starting = False
100
- self._closed = False
101
- self._follow_language = bool(follow_language)
102
- self._language: str | None = None
103
- self._language_lock = asyncio.Lock()
104
- self._tasks: set[asyncio.Task[None]] = set()
105
- self._room: rtc.Room | None = None
106
-
107
- @property
108
- def provider(self) -> str:
109
- return "meshlite"
110
-
111
- @property
112
- def visitor_identity(self) -> str | None:
113
- """Identity of the participant that renders the avatar (known after start)."""
114
- return self._visitor_identity
115
-
116
- @property
117
- def avatar_identity(self) -> str:
118
- """The participant whose page renders the avatar.
119
-
120
- MeshLite has no avatar participant: the avatar lives in the visitor's
121
- page, so this is the visitor identity.
122
- """
123
- if self._visitor_identity is None:
124
- raise RuntimeError("the visitor identity is known once start() has returned")
125
- return self._visitor_identity
126
-
127
- @property
128
- def audio_output(self) -> DataStreamAudioOutput | None:
129
- return self._audio_output
130
-
131
- async def start(self, agent_session: AgentSession, room: rtc.Room) -> None:
132
- if self._closed:
133
- raise RuntimeError("this MeshLite AvatarSession is closed")
134
- if self._starting or self._audio_output is not None:
135
- raise RuntimeError("MeshLite AvatarSession.start() can only be called once")
136
- self._starting = True
137
- try:
138
- identity = self._visitor_identity
139
- if identity is None:
140
- if not room.isconnected():
141
- raise RuntimeError(
142
- "connect to the room (await ctx.connect()) before starting the MeshLite "
143
- "avatar, or pass visitor_identity"
144
- )
145
- logger.debug("waiting for the visitor participant")
146
- participant = await utils.wait_for_participant(
147
- room, kind=rtc.ParticipantKind.PARTICIPANT_KIND_STANDARD
148
- )
149
- identity = participant.identity
150
- if self._closed:
151
- raise RuntimeError("this MeshLite AvatarSession was closed while starting")
152
-
153
- previous = agent_session.output.audio
154
- if previous is not None:
155
- logger.warning(
156
- "replacing the session audio output with the MeshLite avatar output; "
157
- "call AvatarSession.start() before AgentSession.start() so the agent "
158
- "does not publish its own audio track",
159
- extra={"previous_output": getattr(previous, "label", type(previous).__name__)},
160
- )
161
-
162
- options: dict[str, object] = {}
163
- if "clear_buffer_timeout" in _OUTPUT_PARAMS:
164
- options["clear_buffer_timeout"] = self._clear_buffer_timeout
165
- if "wait_playback_start" in _OUTPUT_PARAMS:
166
- # The page reports when the avatar really starts speaking.
167
- options["wait_playback_start"] = True
168
- output = DataStreamAudioOutput(
169
- room,
170
- destination_identity=identity,
171
- sample_rate=self._sample_rate,
172
- **options, # type: ignore[arg-type]
173
- )
174
- agent_session.output.audio = output
175
-
176
- self._visitor_identity = identity
177
- self._audio_output = output
178
- self._agent_session = agent_session
179
- self._room = room
180
- if self._follow_language:
181
- agent_session.on("conversation_item_added", self._on_conversation_item)
182
- logger.info(
183
- "MeshLite avatar voice routed to the visitor page",
184
- extra={"visitor_identity": identity, "sample_rate": self._sample_rate},
185
- )
186
- finally:
187
- self._starting = False
188
-
189
- async def aclose(self) -> None:
190
- """Stop routing the voice to the avatar.
191
-
192
- Unlike video avatar plugins this never removes a participant from the
193
- room: the only participant involved is the visitor.
194
- """
195
- if self._closed:
196
- return
197
- self._closed = True
198
- session, output = self._agent_session, self._audio_output
199
- self._agent_session = None
200
- if session is not None and self._follow_language:
201
- try:
202
- session.off("conversation_item_added", self._on_conversation_item)
203
- except (KeyError, ValueError):
204
- pass
205
- for task in list(self._tasks):
206
- task.cancel()
207
- if session is not None and output is not None and session.output.audio is output:
208
- session.output.audio = None
209
-
210
- @property
211
- def language(self) -> str | None:
212
- """Last language the page accepted (``None`` until one was sent)."""
213
- return self._language
214
-
215
- async def set_language(self, language: str) -> bool:
216
- """Ask the page to load the lip model of ``language``.
217
-
218
- Use it when your agent switches language on its own terms; with
219
- ``follow_language=True`` the plugin already does it after each reply.
220
-
221
- Args:
222
- language: ``"en"``, ``"fr"`` or ``"zh-CN"``.
223
-
224
- Returns:
225
- ``True`` when the page applied it, ``False`` when the page could
226
- not (older SDK, page not attached yet, unknown language there).
227
- """
228
- if language not in MESHLITE_LANGUAGES:
229
- raise ValueError(f"language must be one of {', '.join(MESHLITE_LANGUAGES)}")
230
- room, identity = self._room, self._visitor_identity
231
- if self._closed or room is None or identity is None:
232
- raise RuntimeError("start the MeshLite AvatarSession before setting its language")
233
- async with self._language_lock:
234
- if language == self._language:
235
- return True
236
- try:
237
- await room.local_participant.perform_rpc(
238
- destination_identity=identity,
239
- method=SET_LANGUAGE_RPC,
240
- payload=json.dumps({"language": language}),
241
- response_timeout=_SET_LANGUAGE_TIMEOUT,
242
- )
243
- except rtc.RpcError as error:
244
- if error.code == rtc.RpcError.ErrorCode.UNSUPPORTED_METHOD:
245
- logger.info(
246
- "the visitor page does not follow the agent language yet "
247
- "(MeshLite web SDK 1.11.62 or later, attachLiveKit(room))",
248
- extra={"language": language},
249
- )
250
- else:
251
- logger.warning(
252
- "the visitor page did not change the avatar language",
253
- extra={"language": language, "error": error.message},
254
- )
255
- return False
256
- self._language = language
257
- logger.debug("avatar language changed", extra={"language": language})
258
- return True
259
-
260
- def _on_conversation_item(self, event: object) -> None:
261
- item = getattr(event, "item", None)
262
- if getattr(item, "role", None) != "assistant":
263
- return
264
- text = getattr(item, "text_content", None)
265
- language = spoken_language_of(text) if isinstance(text, str) else None
266
- if language is None or language == self._language or self._closed:
267
- return
268
- task = asyncio.ensure_future(self._follow(language))
269
- self._tasks.add(task)
270
- task.add_done_callback(self._tasks.discard)
271
-
272
- async def _follow(self, language: str) -> None:
273
- try:
274
- await self.set_language(language)
275
- except asyncio.CancelledError:
276
- raise
277
- except Exception: # noqa: BLE001 - never break the agent for a lip model
278
- logger.exception("could not send the avatar language")
@@ -1 +0,0 @@
1
- __version__ = "0.2.0"