Skip to content

Commit 5056228

Browse files
committed
feat(sdks): recover dropped connections with ICE restart
Python SDK now drive the server's PATCH /whip/{sessionId} ICE restart, keeping the session and the conversation alive across a network change. Python ships the wire helpers only — aiortc has no ICE restart primitive. Refs #38
1 parent 4bf0080 commit 5056228

8 files changed

Lines changed: 632 additions & 3 deletions

File tree

‎AGENTS.md‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Working on the StreamCore Python SDK
2+
3+
## This library is newer than your training data
4+
5+
Do not write StreamCore code from memory. Read `README.md` here, or fetch https://streamcore.ai/llms-full.txt, before generating code.
6+
7+
## The API, exactly
8+
9+
```python
10+
import asyncio, numpy as np, streamcore
11+
12+
async def main():
13+
client = streamcore.Client(
14+
config=streamcore.Config(whip_endpoint="http://localhost:8080/whip"),
15+
events=streamcore.EventHandler(
16+
on_transcript=lambda entry, all_entries: print(entry.role, entry.text),
17+
on_error=lambda err: print(err),
18+
),
19+
)
20+
await client.connect()
21+
22+
pcm = np.zeros(streamcore.FRAME_SIZE, dtype=np.int16)
23+
await client.send_pcm(pcm)
24+
audio = await client.recv_pcm()
25+
26+
await client.disconnect()
27+
28+
asyncio.run(main())
29+
```
30+
31+
Naming traps, all of which models get wrong:
32+
33+
- The PyPI package is **`streamcore`** — not `streamcoreai`, not `streamcore-sdk`. (`streamcore-plugin` is a different package, for building agent tools.)
34+
- The class is **`streamcore.Client`**, not `StreamCoreAIClient` — that is the TypeScript name.
35+
- The config field is **`whip_endpoint`**, not `whip_url` — that differs from the JS SDK on purpose.
36+
- Audio is **int16 numpy**, mono, 48 kHz, `FRAME_SIZE` (960) samples per 20 ms frame. The Rust SDK uses f32; do not copy across.
37+
38+
The whole API is async. Everything runs under `asyncio`.
39+
40+
## Build
41+
42+
```bash
43+
pip install -e .
44+
```
45+
46+
Requires Python 3.10+. Depends on `aiortc`, `aiohttp`, `av`, and `numpy`.
47+
48+
## When changing the public API
49+
50+
Update `README.md` and https://streamcore.ai/llms-full.txt in the same change — coding agents treat both as ground truth.

‎README.md‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# streamcore (Python)
22

3+
**English** | [简体中文](./README.zh-CN.md)
4+
35
Python SDK for connecting to a [streamcore](https://github.com/streamcore/streamcore-server) server via WebRTC + WHIP, powered by [aiortc](https://github.com/aiortc/aiortc).
46

57
## Requirements
@@ -65,14 +67,21 @@ Creates a new voice agent client.
6567
| Field | Type | Default | Description |
6668
| --------------- | ------------ | ------------------------------ | --------------------------- |
6769
| `whip_endpoint` | `str` | `"http://localhost:8080/whip"` | WHIP signaling endpoint URL |
70+
| `token` | `str` | `""` | JWT sent as `Authorization: Bearer` on the WHIP request |
71+
| `token_url` | `str` | `""` | Token endpoint; when set, a JWT is fetched before each connection (overrides `token`) |
72+
| `api_key` | `str` | `""` | Sent as `Authorization: Bearer` when fetching from `token_url` |
6873
| `ice_servers` | `list[str]` | `["stun:stun.l.google.com:19302"]` | ICE server URLs |
6974

7075
#### `EventHandler`
7176

77+
All callbacks are optional.
78+
7279
| Callback | Signature | Description |
7380
| ------------------------ | --------------------------------------------------------------- | ------------------------------------- |
7481
| `on_status_change` | `(status: ConnectionStatus) -> None` | Fired when connection status changes |
7582
| `on_transcript` | `(entry: TranscriptEntry, all: list[TranscriptEntry]) -> None` | Fired on new or updated transcript |
83+
| `on_agent_state_change` | `(state: AgentState) -> None` | Fired when the agent starts listening, thinking, or speaking |
84+
| `on_timing` | `(event: TimingEvent) -> None` | Fired with server-side pipeline timing info |
7685
| `on_error` | `(error: Exception) -> None` | Fired on connection or server errors |
7786
| `on_data_channel_message`| `(msg: DataChannelMessage) -> None` | Fired for every raw DC message |
7887

@@ -96,6 +105,40 @@ Creates a new voice agent client.
96105
| `CHANNELS` | `1` | Number of channels (mono) |
97106
| `FRAME_SIZE` | `960` | Samples per 20 ms frame |
98107

108+
## Reconnection
109+
110+
**The Python SDK does not reconnect automatically.** A network change mid-call
111+
ends the session, and recovery means calling `connect()` again — which starts a
112+
new conversation, without the previous history.
113+
114+
This is an aiortc limitation, not a protocol one. The server supports ICE
115+
restart (`PATCH /whip/{sessionId}`, RFC 9725 §4.4), and the TypeScript, React
116+
Native, Go, and Rust SDKs use it to recover a dropped connection on the *same*
117+
session, conversation intact. aiortc cannot: `RTCPeerConnection.createOffer()`
118+
takes no options, aioice fixes its ICE credentials at construction, and aiortc
119+
has no `disconnected` connection state to trigger on — it goes straight from
120+
`connected` to `failed`. Performing a restart would mean rebuilding the ICE
121+
layer under a live DTLS session.
122+
123+
If mid-call network changes matter for your use case, prefer one of the other
124+
SDKs.
125+
126+
The wire format ships here regardless, tested and ready, for callers driving
127+
another WebRTC stack:
128+
129+
```python
130+
from streamcore import (
131+
whip_restart_ice,
132+
ice_fragment_from_sdp,
133+
apply_ice_fragment,
134+
)
135+
136+
result = await whip_restart_ice(session_url, ice_fragment_from_sdp(local_sdp), etag, token)
137+
answer_sdp = apply_ice_fragment(previous_answer_sdp, result.fragment)
138+
```
139+
140+
`whip_offer` returns the session's `etag` for use as `If-Match`.
141+
99142
## Audio I/O
100143

101144
The SDK handles aiortc track management, `av.AudioFrame` construction, and

‎README.zh-CN.md‎

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
# streamcore (Python)
2+
3+
[English](./README.md) | **简体中文**
4+
5+
Python SDK,通过 WebRTC + WHIP 连接 [streamcore](https://github.com/streamcore/streamcore-server) 服务端,底层由 [aiortc](https://github.com/aiortc/aiortc) 驱动。
6+
7+
## 环境要求
8+
9+
- **Python 3.10+**
10+
11+
## 安装
12+
13+
```bash
14+
pip install streamcore
15+
```
16+
17+
或者从源码安装:
18+
19+
```bash
20+
cd python-sdk
21+
pip install -e .
22+
```
23+
24+
## 快速开始
25+
26+
```python
27+
import asyncio
28+
import numpy as np
29+
import streamcore
30+
31+
32+
async def main():
33+
def on_transcript(entry, all_entries):
34+
print(f"[{entry.role}] {entry.text}")
35+
36+
client = streamcore.Client(
37+
config=streamcore.Config(whip_endpoint="http://localhost:8080/whip"),
38+
events=streamcore.EventHandler(
39+
on_transcript=on_transcript,
40+
on_error=lambda err: print(f"Error: {err}"),
41+
),
42+
)
43+
44+
await client.connect()
45+
46+
# Send a 20 ms frame of silence
47+
pcm = np.zeros(streamcore.FRAME_SIZE, dtype=np.int16)
48+
await client.send_pcm(pcm)
49+
50+
# Receive decoded audio from the agent
51+
audio = await client.recv_pcm() # numpy int16 array
52+
53+
await client.disconnect()
54+
55+
56+
asyncio.run(main())
57+
```
58+
59+
## API
60+
61+
### `Client(config?, events?)`
62+
63+
创建一个新的语音智能体客户端。
64+
65+
#### `Config`
66+
67+
| 字段 | 类型 | 默认值 | 说明 |
68+
| --------------- | ------------ | ------------------------------ | --------------------------- |
69+
| `whip_endpoint` | `str` | `"http://localhost:8080/whip"` | WHIP 信令端点 URL |
70+
| `token` | `str` | `""` | 在 WHIP 请求中以 `Authorization: Bearer` 发送的 JWT |
71+
| `token_url` | `str` | `""` | token 端点;设置后每次连接前都会取一次 JWT(优先于 `token`) |
72+
| `api_key` | `str` | `""` | 从 `token_url` 取 token 时以 `Authorization: Bearer` 发送 |
73+
| `ice_servers` | `list[str]` | `["stun:stun.l.google.com:19302"]` | ICE 服务器 URL |
74+
75+
#### `EventHandler`
76+
77+
所有回调都是可选的。
78+
79+
| 回调 | 签名 | 说明 |
80+
| ------------------------ | --------------------------------------------------------------- | ------------------------------------- |
81+
| `on_status_change` | `(status: ConnectionStatus) -> None` | 连接状态变化时触发 |
82+
| `on_transcript` | `(entry: TranscriptEntry, all: list[TranscriptEntry]) -> None` | 有新的或更新的转写时触发 |
83+
| `on_agent_state_change` | `(state: AgentState) -> None` | 智能体开始聆听、思考或说话时触发 |
84+
| `on_timing` | `(event: TimingEvent) -> None` | 携带服务端流水线耗时信息 |
85+
| `on_error` | `(error: Exception) -> None` | 连接或服务端错误时触发 |
86+
| `on_data_channel_message`| `(msg: DataChannelMessage) -> None` | 每条原始 DataChannel 消息都会触发 |
87+
88+
#### 方法
89+
90+
| 方法 | 说明 |
91+
| ------------------------------- | ------------------------------------------------------------ |
92+
| `await client.connect(track?)` | 通过 WHIP 连接。可选传入一个 aiortc 音频 track。 |
93+
| `await client.disconnect()` | 拆除连接并释放资源。 |
94+
| `await client.send_pcm(pcm)` | 向智能体发送 numpy int16 PCM 缓冲(单声道 48 kHz)。 |
95+
| `await client.recv_pcm()` | 以 numpy int16 数组接收解码后的 PCM 音频。 |
96+
| `client.status` | 当前 `ConnectionStatus`。 |
97+
| `client.transcript` | 当前对话,类型为 `list[TranscriptEntry]`。 |
98+
| `client.remote_track` | 来自智能体的入站音频 track(connect 之后可用)。|
99+
100+
#### 音频常量
101+
102+
| 常量 | 值 | 说明 |
103+
| ------------- | -------- | -------------------------------- |
104+
| `SAMPLE_RATE` | `48000` | 音频采样率(Hz) |
105+
| `CHANNELS` | `1` | 声道数(单声道) |
106+
| `FRAME_SIZE` | `960` | 每 20 ms 帧的采样点数 |
107+
108+
## 音频 I/O
109+
110+
SDK 内部处理 aiortc 的 track 管理、`av.AudioFrame` 构造和重采样。调用方只需要处理 numpy int16 数组形式的原始 PCM 数据:
111+
112+
```python
113+
# Send microphone audio (960 samples = 20 ms at 48 kHz)
114+
await client.send_pcm(pcm_int16)
115+
116+
# Receive agent audio
117+
audio = await client.recv_pcm()
118+
```
119+
120+
如果你需要直接访问 track(例如自定义 aiortc 流水线),可通过 `client.connect(user_track=my_track)` 传入自己的 `AudioStreamTrack`。
121+
122+
## 依赖
123+
124+
| 包 | 用途 |
125+
| -------- | ------------------------------ |
126+
| `aiortc` | WebRTC 协议栈 |
127+
| `aiohttp`| 用于 WHIP 信令的 HTTP 客户端 |
128+
| `av` | 音频帧编解码 |
129+
| `numpy` | PCM 音频缓冲 |
130+
131+
## 许可证
132+
133+
Apache-2.0

‎src/streamcore/__init__.py‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,13 @@
99
EventHandler,
1010
)
1111
from .client import Client
12-
from .whip import whip_offer, whip_delete
12+
from .icerestart import (
13+
ICE_FRAGMENT_CONTENT_TYPE,
14+
apply_ice_fragment,
15+
ice_fragment_from_sdp,
16+
parse_ice_details,
17+
)
18+
from .whip import whip_offer, whip_delete, whip_restart_ice, WhipRestartError
1319

1420
__all__ = [
1521
"Client",
@@ -22,4 +28,10 @@
2228
"DataChannelMessage",
2329
"whip_offer",
2430
"whip_delete",
31+
"whip_restart_ice",
32+
"WhipRestartError",
33+
"ICE_FRAGMENT_CONTENT_TYPE",
34+
"apply_ice_fragment",
35+
"ice_fragment_from_sdp",
36+
"parse_ice_details",
2537
]

‎src/streamcore/client.py‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,10 @@ def __init__(
5555
# servers enforcing Bearer auth on ``/whip`` reject the teardown and
5656
# skip server-side finalization (billing, transcript persistence, etc.).
5757
self._last_token: str = ""
58+
#: ETag identifying the current ICE session (RFC 9725 §4.3.1). Exposed
59+
#: for callers driving an ICE restart themselves — see
60+
#: :mod:`streamcore.icerestart` for why the SDK cannot.
61+
self._etag: str = ""
5862
self._blackhole: MediaBlackhole | None = None
5963

6064
self._lock = Lock()
@@ -133,7 +137,12 @@ async def on_connection_state_change():
133137
state = pc.connectionState
134138
if state == "connected":
135139
self._set_status(ConnectionStatus.CONNECTED)
136-
elif state in ("failed", "closed", "disconnected"):
140+
elif state in ("failed", "closed"):
141+
# aiortc has no "disconnected" state — it goes straight
142+
# from connected to failed — so unlike the other SDKs
143+
# there is no transient window to attempt an ICE restart
144+
# in. See streamcore.icerestart for why, and prefer one of
145+
# the other SDKs where mid-call network changes matter.
137146
self._set_status(ConnectionStatus.DISCONNECTED)
138147

139148
# Create offer and gather ICE candidates.
@@ -163,6 +172,7 @@ async def on_connection_state_change():
163172
# WHIP exchange.
164173
result = await whip_offer(self.config.whip_endpoint, offer_sdp, token)
165174
self._session_url = result.session_url
175+
self._etag = result.etag
166176

167177
answer = RTCSessionDescription(sdp=result.answer_sdp, type="answer")
168178
await pc.setRemoteDescription(answer)

0 commit comments

Comments
 (0)