liveavatar-platform-rtc 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,170 @@
1
+ Metadata-Version: 2.4
2
+ Name: liveavatar-platform-rtc
3
+ Version: 1.0.0
4
+ Summary: Live Avatar Platform RTC Python SDK — agent SDK for LiveKit-based real-time digital human
5
+ Author: Live Avatar Team
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ Keywords: asr,avatar,digital-human,live-avatar,livekit,rtc,tts
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Requires-Python: >=3.10
21
+ Requires-Dist: httpx>=0.25
22
+ Requires-Dist: livekit>=1.0
23
+ Requires-Dist: numpy>=1.24
24
+ Provides-Extra: dev
25
+ Requires-Dist: black; extra == 'dev'
26
+ Requires-Dist: build; extra == 'dev'
27
+ Requires-Dist: pytest; extra == 'dev'
28
+ Requires-Dist: pytest-asyncio; extra == 'dev'
29
+ Requires-Dist: ruff; extra == 'dev'
30
+ Requires-Dist: twine; extra == 'dev'
31
+ Description-Content-Type: text/markdown
32
+
33
+ # Live Avatar Platform RTC Python SDK
34
+
35
+ [中文文档](README.zh.md)
36
+
37
+ Backend agent SDK for Live Avatar **Platform RTC** mode. Your application owns
38
+ ASR, LLM, and TTS. The SDK connects that pipeline to the platform LiveKit room:
39
+ user audio arrives as PCM frames, and your TTS PCM frames drive avatar speech.
40
+ There is no platform-TTS or text-input compatibility API in this package.
41
+
42
+ **Version 1.0.0** — breaking Platform RTC Agent API for developer-owned
43
+ ASR/LLM/TTS pipelines.
44
+
45
+ ## Install
46
+
47
+ ```bash
48
+ pip install liveavatar-platform-rtc
49
+ ```
50
+
51
+ Python 3.10 or newer is required.
52
+
53
+ ## Development install
54
+
55
+ ```bash
56
+ pip install -e ".[dev]"
57
+ ```
58
+
59
+ ## Minimal agent
60
+
61
+ ```python
62
+ import asyncio
63
+ import os
64
+ from liveavatar_rtc import AudioFrame, PlatformRTCClient
65
+
66
+ client = PlatformRTCClient(
67
+ api_key=os.environ["LIVEAVATAR_API_KEY"],
68
+ avatar_id=os.environ["LIVEAVATAR_AVATAR_ID"],
69
+ input_sample_rate=16000,
70
+ output_sample_rate=24000,
71
+ )
72
+
73
+ async with client as session:
74
+ print(session.frontend_connection) # distribute to your frontend
75
+ pipeline_input: asyncio.Queue[AudioFrame] = asyncio.Queue()
76
+
77
+ @session.on("user_audio_frame")
78
+ async def on_user_audio(frame: AudioFrame) -> None:
79
+ # Feed your ASR/Omni model, then publish your own TTS frames.
80
+ await pipeline_input.put(frame)
81
+
82
+ await session.wait_for_user(timeout=30)
83
+ await session.wait_for_scene_ready(timeout=30)
84
+ await asyncio.Event().wait()
85
+ ```
86
+
87
+ See [`examples/basic_agent.py`](examples/basic_agent.py) for a syntactically
88
+ runnable, provider-free pipeline skeleton. It connects and consumes user audio,
89
+ but intentionally produces no avatar speech until real developer ASR, LLM, and
90
+ TTS are integrated; it prints this warning at startup.
91
+
92
+ For the full Platform RTC protocol model, see [`PROTOCOL.md`](PROTOCOL.md).
93
+
94
+ ## Connection and readiness stages
95
+
96
+ 1. `await client.connect()` (or enter the context manager) starts the platform
97
+ session and connects the backend agent to LiveKit.
98
+ 2. Send `session.frontend_connection` to the frontend. It contains only the
99
+ user's `user_token` and `sfu_url`; never send the API key or agent token.
100
+ 3. `await session.wait_for_user()` waits for that frontend user to join.
101
+ 4. `await session.wait_for_scene_ready()` waits for the coordinator's
102
+ `scene.ready` event. Start avatar output after this stage.
103
+
104
+ The observable flags are `is_agent_connected`, `is_user_joined`,
105
+ `is_user_audio_subscribed`, `is_scene_ready`, `is_closing`, and `is_closed`.
106
+ Wait methods raise `SessionWaitTimeoutError` on timeout and
107
+ `SessionClosedError` if the session closes first.
108
+
109
+ ## Developer-owned audio pipeline
110
+
111
+ The SDK emits `user_audio_frame` with mono PCM16 resampled to
112
+ `input_sample_rate` (16 kHz by default), ready for developer-owned ASR or an
113
+ omni model. Your LLM and TTS remain entirely in your backend.
114
+
115
+ Publish TTS with `await session.publish_audio(frame)` or stream an async
116
+ iterable with `await session.publish_audio_stream(frames)`. Output must be mono
117
+ PCM16 at the negotiated output rate. The recommended and client default rate is
118
+ 24 kHz. A session-start response may override `output_sample_rate`; the SDK
119
+ validates against that server-selected rate. LiveKit, not application code,
120
+ owns real-time playout buffering and Opus encoding.
121
+
122
+ ```python
123
+ async def tts_frames():
124
+ async for pcm in my_streaming_tts():
125
+ yield AudioFrame.from_pcm(pcm, sample_rate=24000)
126
+
127
+ await session.publish_audio_stream(tts_frames())
128
+ ```
129
+
130
+ Only one output stream may be active. `await session.interrupt(request_id)`
131
+ cancels it, clears queued playout, sends `control.interrupt`, and emits the
132
+ local `interrupted` hook. Use that hook to cancel your LLM/TTS provider too.
133
+
134
+ ## Events and protocol hooks
135
+
136
+ Register handlers with `@session.on(event_name)`. Common SDK events are
137
+ `USER_AUDIO_FRAME`, `USER_JOINED`, `USER_LEFT`, `SCENE_READY`,
138
+ `SESSION_STATE`, `SESSION_CLOSING`, `DISCONNECTED`, `ERROR`, and
139
+ `CUSTOM_EVENT`. Unknown data-channel envelopes are delivered as
140
+ `CUSTOM_EVENT` without discarding their metadata.
141
+
142
+ RTC Agent protocol packets are reliable LiveKit Data Channel messages without a
143
+ required topic. The SDK dispatches by the JSON `event` field and does not filter
144
+ incoming packets by topic. `DataChannelEvent.topic` is retained only for
145
+ diagnostics when a participant supplies one.
146
+
147
+ Developer ASR/VAD and application-specific observability integrations can use:
148
+
149
+ ```python
150
+ await session.send_voice_start(request_id)
151
+ await session.send_asr_partial(request_id, text, seq)
152
+ await session.send_voice_finish(request_id)
153
+ await session.send_asr_final(request_id, text)
154
+ await session.send_custom_event("vendor.event", {"value": 1})
155
+ ```
156
+
157
+ The RTC SDK does not provide `response.chunk` / `response.done` helpers. Avatar
158
+ speech is driven by the developer-published LiveKit audio track, not by platform
159
+ text TTS. If your application needs subtitles or diagnostics, send an explicit
160
+ custom event that your own frontend or backend understands.
161
+
162
+ Close with `await session.close()` or leave the client context manager. The
163
+ context manager also stops the remote platform session.
164
+
165
+ ## Scope
166
+
167
+ This package is only for Platform RTC agent backends. It transports PCM audio
168
+ over LiveKit audio tracks and structured control events over the LiveKit data
169
+ channel. Its public surface contains only the v2 Platform RTC agent API, without
170
+ legacy compatibility aliases.
@@ -0,0 +1,13 @@
1
+ liveavatar_rtc/__init__.py,sha256=yUNsjRkcWim0zYOraXK_KaKyi8IDk9lZP1uf40h3ygE,1523
2
+ liveavatar_rtc/api_client.py,sha256=PMFQoWCQM6Ao40Qe4rW5Ho_Rq_vRapljnDiKZsFzAIc,2419
3
+ liveavatar_rtc/client.py,sha256=jjZhRTUzKKnRykWm-kj73tBPitIS8R1JTxhU5ui65eU,6649
4
+ liveavatar_rtc/errors.py,sha256=wJ8aBRlE1dwfEflG-0lS8ieEyGJAbsNecK_nRqdP6GE,649
5
+ liveavatar_rtc/event_dispatcher.py,sha256=J_R3zZoYu_hsfZAf5EQC1tnvAw7SVH6m2KghPvFAHO8,1527
6
+ liveavatar_rtc/livekit_manager.py,sha256=Vas9_IxBO4V7sWxwkD-R3vcEdcrVhSDfvMzLFCvTDHA,17465
7
+ liveavatar_rtc/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ liveavatar_rtc/session.py,sha256=8sVbLnOdWugaaYhQ0-MYHt0I3fU-8AHRWJ-DWOlMnNE,11283
9
+ liveavatar_rtc/types.py,sha256=mljBFetXZrBN0Jt_wWbq9qQ7t5gt3ERhf-c7Yaq-Vos,2491
10
+ liveavatar_platform_rtc-1.0.0.dist-info/METADATA,sha256=jEfC5JC9-0czuGBax7HrU_uNKM22Q9BWm1yZ9AbkoRU,6634
11
+ liveavatar_platform_rtc-1.0.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
12
+ liveavatar_platform_rtc-1.0.0.dist-info/licenses/LICENSE,sha256=UOZ1F5fFDe3XXvG4oNnkL1-Ecun7zpHzRxjp-XsMeAo,11324
13
+ liveavatar_platform_rtc-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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,73 @@
1
+ from importlib.metadata import PackageNotFoundError, version
2
+
3
+ from .errors import (
4
+ APIError,
5
+ AudioFormatError,
6
+ AudioPublishError,
7
+ DataChannelProtocolError,
8
+ RTCConnectionError,
9
+ RTCSDKError,
10
+ SessionClosedError,
11
+ SessionStartError,
12
+ SessionWaitTimeoutError,
13
+ )
14
+ from .client import PlatformRTCClient
15
+ from .session import (
16
+ CUSTOM_EVENT,
17
+ DISCONNECTED,
18
+ ERROR,
19
+ IDLE_TRIGGER,
20
+ SCENE_READY,
21
+ SESSION_CLOSING,
22
+ SESSION_STATE,
23
+ USER_AUDIO_FRAME,
24
+ USER_AUDIO_TRACK_SUBSCRIBED,
25
+ USER_AUDIO_TRACK_UNSUBSCRIBED,
26
+ USER_JOINED,
27
+ USER_LEFT,
28
+ Session,
29
+ )
30
+ from .types import (
31
+ AudioFrame,
32
+ AudioTrackInfo,
33
+ DataChannelEvent,
34
+ FrontendConnection,
35
+ SessionInfo,
36
+ )
37
+
38
+ try:
39
+ __version__ = version("liveavatar-platform-rtc")
40
+ except PackageNotFoundError:
41
+ __version__ = "0.0.0"
42
+
43
+ __all__ = [
44
+ "__version__",
45
+ "RTCSDKError",
46
+ "APIError",
47
+ "SessionStartError",
48
+ "RTCConnectionError",
49
+ "SessionClosedError",
50
+ "SessionWaitTimeoutError",
51
+ "AudioFormatError",
52
+ "AudioPublishError",
53
+ "DataChannelProtocolError",
54
+ "FrontendConnection",
55
+ "SessionInfo",
56
+ "DataChannelEvent",
57
+ "AudioFrame",
58
+ "AudioTrackInfo",
59
+ "PlatformRTCClient",
60
+ "Session",
61
+ "SCENE_READY",
62
+ "SESSION_STATE",
63
+ "SESSION_CLOSING",
64
+ "IDLE_TRIGGER",
65
+ "ERROR",
66
+ "CUSTOM_EVENT",
67
+ "USER_AUDIO_FRAME",
68
+ "USER_AUDIO_TRACK_SUBSCRIBED",
69
+ "USER_AUDIO_TRACK_UNSUBSCRIBED",
70
+ "USER_JOINED",
71
+ "USER_LEFT",
72
+ "DISCONNECTED",
73
+ ]
@@ -0,0 +1,75 @@
1
+ import httpx
2
+
3
+ from .errors import APIError, SessionStartError
4
+ from .types import SessionInfo
5
+
6
+
7
+ class ApiClient:
8
+ """REST client for Live Avatar platform session management."""
9
+
10
+ def __init__(
11
+ self,
12
+ api_key: str,
13
+ base_url: str = "https://facemarket.ai/vih/dispatcher",
14
+ sandbox: bool = False,
15
+ ) -> None:
16
+ self._api_key = api_key
17
+ self._base_url = base_url.rstrip("/")
18
+ self._sandbox = sandbox
19
+ self._client = httpx.AsyncClient(timeout=httpx.Timeout(30.0))
20
+
21
+ async def aclose(self) -> None:
22
+ await self._client.aclose()
23
+
24
+ def _headers(self) -> dict[str, str]:
25
+ h = {
26
+ "Authorization": f"Bearer {self._api_key}",
27
+ "Content-Type": "application/json",
28
+ }
29
+ if self._sandbox:
30
+ h["X-Env-Sandbox"] = "true"
31
+ return h
32
+
33
+ async def start_session(self, avatar_id: str) -> SessionInfo:
34
+ resp = await self._client.post(
35
+ f"{self._base_url}/v1/session/start",
36
+ headers=self._headers(),
37
+ json={"avatarId": avatar_id, "mode": "rtcAgent"},
38
+ )
39
+ resp.raise_for_status()
40
+ payload: dict = resp.json()
41
+
42
+ if payload.get("code") != 0:
43
+ raise APIError(
44
+ payload.get("code"), payload.get("message", "unknown error")
45
+ )
46
+
47
+ data = payload.get("data") or {}
48
+ session_id = data.get("sessionId", "")
49
+ sfu_url = data.get("sfuUrl", "")
50
+ agent_token = data.get("agentToken", "")
51
+ if not session_id or not sfu_url or not agent_token:
52
+ raise SessionStartError(
53
+ "session response is missing sessionId, sfuUrl, or agentToken"
54
+ )
55
+
56
+ return SessionInfo(
57
+ session_id=session_id,
58
+ agent_token=agent_token,
59
+ user_token=data.get("userToken", ""),
60
+ sfu_url=sfu_url,
61
+ output_sample_rate=data.get("outputSampleRate"),
62
+ )
63
+
64
+ async def stop_session(self, session_id: str) -> None:
65
+ resp = await self._client.post(
66
+ f"{self._base_url}/v1/session/stop",
67
+ headers=self._headers(),
68
+ json={"sessionId": session_id},
69
+ )
70
+ resp.raise_for_status()
71
+ data: dict = resp.json()
72
+ if data.get("code") != 0:
73
+ raise APIError(
74
+ data.get("code", -1), data.get("message", "unknown error")
75
+ )