Open full-duplex voice models that hear your tone and speak with one. One GPU with vLLM-Omni, or fully offline on a Mac with MLX. Zero-shot voice cloning, OpenAI Realtime / GPT-Live compatible, free hosted API trial. Apache-2.0.
Python apple-siliconfull-duplexlivekitmacosmlxofflineopen-sourceopenai-realtimeparalinguisticspipecatrealtimespeechspeech-to-speechttsvllmvllm-omnivoice-assistantvoice-cloningzero-shot
LiveKit and Pipecat guide (Realtime + GPT-Live), livekit-plugins-sophon, framework measurements
BKtensor8dfc36b27f3b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f785384..0b1969b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,13 @@ One version number for the whole Sophon-Realtime v1 family: the code in this repModelScope (git tags with the same name) and the `sophon-realtime` package on PyPI. Each entry says which builds changed.Second digit: new features or new weights; third digit: fixes only.+## Unreleased (2026-11-30)++- LiveKit and Pipecat guide with measurements, both protocols (Realtime and GPT-Live): `docs/frameworks.md`, `docs/frameworks_CN.md`.+- New `integrations/livekit-plugins-sophon` (PyPI `livekit-plugins-sophon` 0.1.0): `sophon.RealtimeModel` and `sophon.LiveModel`.+- `live/bench/frameworks/`: the latency and function-call scripts behind the guide.+- `live/examples/livekit_agent.py` uses the plugin; examples tested with livekit-agents 1.9.0 and pipecat-ai 1.17.0.+## Unreleased- **Fine-tuning the 4B builds** ([#25](https://github.com/adventists-ai/sophon-realtime/issues/25)). The 4B tag LoRA is now published in Sophon-Realtime-4B-Tag under `adapters/tag` (Hugging Face and ModelScope). New `finetune/sophon_swift/merge.py` merges a fine-tuned LoRA into the 4B base on CPU, since the 4B servers do not attach a LoRA at run time. See section 7 of the [fine-tuning guide](finetune/README.md).diff --git a/README.md b/README.mdindex 57b6404..ddec138 100644--- a/README.md+++ b/README.md@@ -71,6 +71,7 @@ https://github.com/user-attachments/assets/1d9442ef-84b0-45a3-acd4-2d05a9562397## News+- **2026-11-30 · LiveKit and Pipecat, both protocols:** use your own Sophon-Realtime server as the voice of a LiveKit or Pipecat agent, through the OpenAI Realtime protocol (function calling) or the GPT-Live protocol (client delegation); new `livekit-plugins-sophon`, and the frameworks add about 0.05 s. [Guide and measurements](docs/frameworks.md)- **2026-11-29 · Fine-tune the 4B:** adapt Sophon-Realtime-4B to your persona or domain with ms-swift on one GPU (~12 GB), merge on CPU and serve it with the same builds; the 4B tag LoRA is now published. [Guide](finetune/README.md#7-4b-builds-sophon-realtime-4b-tag---flash---e2e)- **2026-11-24 · Try it on Hugging Face:** talk to Sophon-Realtime in your browser, no GPU and no sign-up: interrupt it, laugh with it, turn on your camera. [Hugging Face Space](https://huggingface.co/spaces/adventists-ai/Sophon-Realtime)- **2026-11-19 · SillyTavern plugin:** call your character in real time from SillyTavern, with interruptions, a cloned voice per character and the call written back into the chat; your own GPU (4B on one 24 GB card) or the API. [sophon-sillytavern](https://github.com/adventists-ai/sophon-sillytavern) · [demo](https://x.com/BKJinAI/status/2123275865257807933)@@ -78,10 +79,10 @@ https://github.com/user-attachments/assets/1d9442ef-84b0-45a3-acd4-2d05a9562397- **2026-11-16 · v1.4: Sophon-Realtime 4B** — Tag, Flash and E2E with a 4B brain, on one consumer GPU (Flash 24 GB; Tag and E2E 32 GB). Full-duplex turn-taking and sound tags carry over (Full-Duplex-Bench v1.0, official scoring: Tag 98.2, E2E 98.6, Flash 96.3); much less knowledge than 32B (VoiceBench 62.4). [Details](#4b-builds-new-in-14) · [Tag](https://huggingface.co/adventists-ai/Sophon-Realtime-4B-Tag) · [Flash](https://huggingface.co/adventists-ai/Sophon-Realtime-4B-Flash) · [E2E](https://huggingface.co/adventists-ai/Sophon-Realtime-4B-E2E)- **2026-11-14 · Try it without a GPU:** hosted API, OpenAI Realtime-compatible, with all three builds; sign up and get 3 hours of free voice chat. [Console](https://api.adventists.ai/console/) · [API docs](https://api.adventists.ai/console/docs)- **2026-11-13 · Sophon-Realtime on Mac:** Flash-4bit runs locally on Apple silicon (MLX, 36 GB+ recommended), full duplex with turn-taking, barge-in and echo cancellation; it starts speaking about 1 s after you stop. [mac/](mac/README.md) · [weights](https://huggingface.co/adventists-ai/Sophon-Realtime-32B-Flash-4bit-MLX)-- **2026-11-13 · v1.2: long replies are spoken to the end** in Tag, Flash and E2E, however long they are; plus **Flash-4bit** for one 32 GB GPU. [Release notes](https://github.com/adventists-ai/sophon-realtime/releases/tag/v1.2.0) · [Flash-4bit](flash/README.md#flash-4bit-one-32-gb-gpu)<details><summary>Older news</summary>+- **2026-11-13 · v1.2: long replies are spoken to the end** in Tag, Flash and E2E, however long they are; plus **Flash-4bit** for one 32 GB GPU. [Release notes](https://github.com/adventists-ai/sophon-realtime/releases/tag/v1.2.0) · [Flash-4bit](flash/README.md#flash-4bit-one-32-gb-gpu)- **2026-11-11 · v1.1: zero-shot voice cloning** in Tag and Flash: a few seconds of audio and it talks to you in that voice, in real time. [Watch the demo](#zero-shot-voice-cloning-new-in-v11)- **2026-11-11 · E2E becomes a full build on one GPU**, with first audio in about 0.25 s; it can also be served by vLLM-Omni like Tag and Flash. [Details](#e2e)- **2026-11-09 · Try it online** on [ModelScope Studio](https://www.modelscope.ai/studios/AdventistsAI/Sophon-Realtime), and **Live mode** (OpenAI GPT-Live compatible: hands lookups to your own backend while it keeps talking) is open source. [Live mode](live/README.md)@@ -249,6 +250,7 @@ Adapt the brain (persona, tone, domain knowledge, tool use) with LoRA in [ms-swi## Integrations+- **[LiveKit Agents and Pipecat](docs/frameworks.md)**: Sophon-Realtime as the realtime model of your agent, in Realtime mode (`livekit-plugins-sophon`, or Pipecat's OpenAI Realtime service) or Live mode (GPT-Live with client delegation). Measured: the frameworks add about 0.05 s.- **[SillyTavern](https://github.com/adventists-ai/sophon-sillytavern)**: full-duplex voice calls with your character. Install from SillyTavern → Extensions → Install extension; point it at your own Sophon-Realtime server or the API.## From the same teamdiff --git a/README_CN.md b/README_CN.mdindex 5363fbd..24f618a 100644--- a/README_CN.md+++ b/README_CN.md@@ -70,6 +70,7 @@ https://github.com/user-attachments/assets/4d6c74f5-3bbf-4dc2-8b11-f90ff85de4a2## 最新进展+- **2026-11-30 · LiveKit、Pipecat 两种协议都支持**:把你自己的 Sophon-Realtime 服务器接成 LiveKit 或 Pipecat 智能体的语音,可以走 OpenAI Realtime 协议(函数调用),也可以走 GPT-Live 协议(客户端委派);新增 `livekit-plugins-sophon`,框架只多约 0.05 秒。[教程和实测](docs/frameworks_CN.md)- **2026-11-29 · 4B 可以微调了**:用 ms-swift 单卡(约 12 GB)把 Sophon-Realtime-4B 调成你的人设或业务,CPU 上合并,用原来的版本直接部署;4B 写标签 LoRA 已公开。[微调指南](finetune/README_CN.md#7-4b-版sophon-realtime-4b-tag---flash---e2e)- **2026-11-24 · Hugging Face 在线体验上线**:浏览器里直接和智子对话,不用显卡、不用注册;可以随时打断、逗她笑、打开摄像头。[Hugging Face Space](https://huggingface.co/spaces/adventists-ai/Sophon-Realtime)- **2026-11-19 · 酒馆(SillyTavern)插件**:在酒馆里和角色实时通话,可以随时打断,每个角色一个(可克隆的)声音,通话内容写回聊天;用自己的显卡(4B 一张 24 GB 卡)或 API。[sophon-sillytavern](https://github.com/adventists-ai/sophon-sillytavern) · [演示](https://x.com/BKJinAI/status/2123275865257807933)@@ -77,10 +78,10 @@ https://github.com/user-attachments/assets/4d6c74f5-3bbf-4dc2-8b11-f90ff85de4a2- **2026-11-16 · v1.4:Sophon-Realtime 4B 版**——Tag、Flash、E2E 换上 4B 大脑,一张消费级显卡就能跑(Flash 24 GB;Tag、E2E 32 GB)。全双工接话和声音标签保留(Full-Duplex-Bench v1.0 官方计分:Tag 98.2、E2E 98.6、Flash 96.3);知识比 32B 少很多(VoiceBench 62.4)。[详情](#4b-版14-新增) · [Tag](https://www.modelscope.cn/models/AdventistsAI/Sophon-Realtime-4B-Tag) · [Flash](https://www.modelscope.cn/models/AdventistsAI/Sophon-Realtime-4B-Flash) · [E2E](https://www.modelscope.cn/models/AdventistsAI/Sophon-Realtime-4B-E2E)- **2026-11-14 · 没有显卡也能用**:在线 API 开放试用,兼容 OpenAI Realtime,三个版本都能调用;注册就送 3 小时免费对话。[控制台](https://api.adventists.cn/console/) · [接口文档](https://api.adventists.cn/console/docs)- **2026-11-13 · Mac 版上线**:Flash-4bit 可以在 Apple 芯片的 Mac 上本地运行(MLX,推荐 36 GB 及以上内存),全双工,支持话轮判断、打断和回音消除;你说完约 1 秒开口。[mac/](mac/README_CN.md) · [权重](https://modelscope.cn/models/AdventistsAI/Sophon-Realtime-32B-Flash-4bit-MLX)-- **2026-11-13 · v1.2:长回复完整说完**,Tag、Flash、E2E 三个版本都不再限制语音时长;同时发布 **Flash-4bit**,一张 32 GB 显卡就能跑。[发布说明](https://github.com/adventists-ai/sophon-realtime/releases/tag/v1.2.0) · [Flash-4bit](flash/README_CN.md#flash-4bit一张-32-gb-显卡)<details><summary>更早的进展</summary>+- **2026-11-13 · v1.2:长回复完整说完**,Tag、Flash、E2E 三个版本都不再限制语音时长;同时发布 **Flash-4bit**,一张 32 GB 显卡就能跑。[发布说明](https://github.com/adventists-ai/sophon-realtime/releases/tag/v1.2.0) · [Flash-4bit](flash/README_CN.md#flash-4bit一张-32-gb-显卡)- **2026-11-11 · v1.1:零样本声音克隆**,Tag 版和 Flash 版均已支持。几秒钟的录音,就能用这个声音和你实时对话。[看演示视频](#零样本声音克隆v11-新增)- **2026-11-11 · E2E 成为正式版本,单卡即可运行**,单路首包约 0.25 秒;也能像 Tag、Flash 一样用 vLLM-Omni 部署。[详情](#e2e)- **2026-11-09 · 在线体验上线**:[魔搭创空间](https://www.modelscope.cn/studios/AdventistsAI/Sophon-Realtime);**Live 模式**同步开源(兼容 OpenAI GPT-Live,查询类任务交给你自己的后端,边说边等结果)。[Live 模式](live/README_CN.md)@@ -248,6 +249,7 @@ E2E 版有两种部署方式,权重相同、声音相同:自研引擎([doc## 生态集成+- **[LiveKit Agents 和 Pipecat](docs/frameworks_CN.md)**:把 Sophon-Realtime 作为智能体的实时模型,Realtime 模式(`livekit-plugins-sophon`,或 Pipecat 的 OpenAI Realtime 服务)和 Live 模式(GPT-Live 客户端委派)都可以。实测框架只多约 0.05 秒。- **[酒馆 SillyTavern](https://github.com/adventists-ai/sophon-sillytavern)**:和角色全双工语音通话。在酒馆 → 扩展 → 安装扩展里安装,连接自己的 Sophon-Realtime 服务器或 API。## 同一团队的其他项目diff --git a/docs/frameworks.md b/docs/frameworks.mdnew file mode 100644index 0000000..f24fc89--- /dev/null+++ b/docs/frameworks.md@@ -0,0 +1,148 @@+# Sophon-Realtime with LiveKit and Pipecat++Run Sophon-Realtime on your own GPU and use it as the voice of a [LiveKit Agents](https://github.com/livekit/agents) or [Pipecat](https://github.com/pipecat-ai/pipecat) agent. Both frameworks work in **two modes**:++| Mode | Protocol | Use it when | LiveKit | Pipecat |+|---|---|---|---|---|+| **Realtime** | OpenAI Realtime (`/v1/realtime`) | You want a speech-to-speech model with function calling, like `gpt-realtime` | `sophon.RealtimeModel` ([plugin](https://pypi.org/project/livekit-plugins-sophon/)) | `OpenAIRealtimeLLMService(base_url=...)` |+| **Live** | OpenAI GPT-Live (`/v1/live/sessions`) | You already wrote a GPT-Live agent with **client delegation** (the voice talks, your backend does the work) | `sophon.LiveModel` | `OpenAILiveLLMService(base_url=...)` |++Your agent code stays the same; only the address changes. Turn-taking runs on the server (the model listens while it talks and decides when you have finished), so you do not add a VAD or a turn detector.++```+LiveKit / Pipecat agent ──Realtime or GPT-Live──▶ Sophon Live gateway (:8780) ──▶ Sophon engine (:8000, one GPU)+```++## 1. Start the model and the gateway (your GPU server)++```bash+# engine: one 80 GB GPU for the 32B builds+pip install "sophon-realtime[trt]" && sophon-realtime serve --port 8000++# gateway: both protocols on one port+git clone https://github.com/adventists-ai/sophon-realtime && cd sophon-realtime/live+BUILD=tag PORT=8000 LIVE_PORT=8780 bash start_live.sh+```++The gateway loads a small ASR model for user transcripts (about 2 GB of GPU memory). Other builds (Flash, the 4B builds) start the same way; see the [model list](../README.md). Open port 8780 to the machine that runs your agent. To require a key, set `SOPHON_LIVE_REALTIME_KEYS_FILE` (Realtime) and `SOPHON_LIVE_API_KEYS` (Live) on the gateway.++## 2a. LiveKit Agents++```bash+pip install livekit-plugins-sophon # pulls livekit-agents and the OpenAI plugin+```++**Realtime mode**++```python+from livekit import agents+from livekit.agents import Agent, AgentSession, function_tool+from livekit.plugins import sophon+++class Assistant(Agent):+ def __init__(self):+ super().__init__(instructions="You are Nova, a friendly voice assistant. Keep replies short.")++ @function_tool+ async def get_weather(self, city: str) -> str:+ """Get the current weather for a city."""+ return f"{city}: 18 degrees, light rain"+++async def entrypoint(ctx: agents.JobContext):+ await ctx.connect()+ session = AgentSession(llm=sophon.RealtimeModel(base_url="http://YOUR_SERVER:8780/v1"))+ await session.start(room=ctx.room, agent=Assistant())+++if __name__ == "__main__":+ agents.cli.run_app(agents.WorkerOptions(entrypoint_fnc=entrypoint))+```++**Live mode** (client delegation)++```python+import asyncio+++class Receptionist(Agent):+ def __init__(self):+ super().__init__(instructions="You are Nova, a friendly receptionist. Keep replies short.")++ async def on_enter(self):+ self.duplex_session.on("delegation_created", self._on_delegation)++ def _on_delegation(self, delegation):+ async def work():+ # the ask is what the caller just said; run your own backend (LLM, tools, database...)+ answer = await my_backend(delegation.pending_transcript)+ self.duplex_session.append_commentary(answer, delegation_id=delegation.id)+ asyncio.create_task(work())+++async def entrypoint(ctx: agents.JobContext):+ await ctx.connect()+ session = AgentSession(llm=sophon.LiveModel(base_url="http://YOUR_SERVER:8780/v1"))+ await session.start(room=ctx.room, agent=Receptionist())+```++The model says a short line ("Let me check that"), hands the turn to your code, and speaks your answer in its own words.++Coming from OpenAI GPT-Live? `openai.realtime.GPTLiveModel(base_url="http://YOUR_SERVER:8780/v1", delegation="client")` works too; `sophon.LiveModel` only fills in the defaults.++## 2b. Pipecat++```bash+pip install "pipecat-ai[openai]"+```++**Realtime mode**++```python+from pipecat.services.openai.realtime.llm import OpenAIRealtimeLLMService++llm = OpenAIRealtimeLLMService(+ api_key="any", # a gateway key if you set one+ base_url="ws://YOUR_SERVER:8780/v1/realtime",+ settings=OpenAIRealtimeLLMService.Settings(+ model="sophon-realtime",+ system_instruction="You are Nova, a friendly voice assistant. Keep replies short.",+ ),+)+pipeline = Pipeline([transport.input(), llm, transport.output()]) # no VAD, no turn analyzer+```++**Live mode**++```python+from pipecat.services.openai.live.llm import OpenAILiveLLMService++llm = OpenAILiveLLMService(api_key="any", base_url="ws://YOUR_SERVER:8780/v1/live/sessions")+# the session starts on the first LLMContextFrame (your system prompt), as with OpenAI GPT-Live+```++A complete runnable bot (browser WebRTC) is in [live/examples/pipecat_bot.py](../live/examples/pipecat_bot.py); the LiveKit example is [live/examples/livekit_agent.py](../live/examples/livekit_agent.py).++## 3. Measurements++Time from the end of the user's speech to the first audible reply, measured at the client. One H100 per model, one conversation at a time, the gateway on the same machine; 3 recorded questions (English and Chinese) × 3 runs per cell; livekit-agents 1.9.0, pipecat-ai 1.17.0. Median (P90), seconds.++| Model | Direct WebSocket | LiveKit, Realtime | Pipecat, Realtime | LiveKit, Live | Pipecat, Live |+|---|---|---|---|---|---|+| 32B Tag | 0.47 (0.56) | 0.55 (0.63) | 0.50 (0.52) | 0.54 (0.61) | 0.51 (0.52) |+| 4B Flash | 0.46 (0.59) | 0.47 (0.74) | 0.47 (0.67) | 0.48 (0.64) | 0.50 (1.52) |++- The frameworks add little: LiveKit about 0.05 s, Pipecat about nothing.+- A fourth recording, an English sentence that ends in laughter, took about 2.4 s on the 32B Tag build in every client (the model waits to be sure you have finished) and about 0.55–0.8 s on 4B Flash. It is left out of the table above.+- Also checked: barge-in (32B Tag stops talking about 0.26 s after you start, and answers about 0.13 s after you finish), function calling through `@function_tool` (32B; the call goes out about 0.9 s after you finish), and Live-mode delegation answered with `append_commentary`.+- Measurement scripts: [`live/bench/frameworks/`](../live/bench/frameworks/).++## 4. Tips and known limits++- **Give the agent a name and a persona** in the instructions. Without one, the model may invent a name.+- **Reply language follows the instructions** in Live mode: write them in the language your users speak, or say "reply in the user's language".+- **Function calling** works with the 32B builds (Tag, Flash, E2E). The 4B builds do not call tools; use Live mode with your own backend, or a 32B build.+- Transcripts can contain sound tags such as `[laughter]`; they are performed, not read out. Strip them before showing text if you prefer.+- A sentence that ends in laughter can take about 2.4 s to be answered by the 32B Tag build (it waits to be sure you have finished). We are working on it.+- One gateway serves one engine; run several gateways behind your load balancer for more capacity.diff --git a/docs/frameworks_CN.md b/docs/frameworks_CN.mdnew file mode 100644index 0000000..66e40ba--- /dev/null+++ b/docs/frameworks_CN.md@@ -0,0 +1,148 @@+# 在 LiveKit / Pipecat 中使用 Sophon-Realtime++把 Sophon-Realtime 跑在你自己的 GPU 上,作为 [LiveKit Agents](https://github.com/livekit/agents) 或 [Pipecat](https://github.com/pipecat-ai/pipecat) 智能体的"嗓子"。两个框架都支持**两种模式**:++| 模式 | 协议 | 适合 | LiveKit | Pipecat |+|---|---|---|---|---|+| **Realtime** | OpenAI Realtime(`/v1/realtime`) | 想要一个像 `gpt-realtime` 那样能调函数的语音对语音模型 | `sophon.RealtimeModel`([插件](https://pypi.org/project/livekit-plugins-sophon/)) | `OpenAIRealtimeLLMService(base_url=...)` |+| **Live** | OpenAI GPT-Live(`/v1/live/sessions`) | 已经按 GPT-Live **客户端委派**写好了智能体(前台说话,后台办事) | `sophon.LiveModel` | `OpenAILiveLLMService(base_url=...)` |++智能体代码不用改,只换地址。话轮判断在服务端完成(模型边说边听,自己判断你说完没有),所以不用再加 VAD 或话轮检测。++```+LiveKit / Pipecat 智能体 ──Realtime 或 GPT-Live──▶ Sophon Live 网关(:8780)──▶ Sophon 引擎(:8000,一张卡)+```++## 1. 启动模型和网关(你的 GPU 服务器)++```bash+# 引擎:32B 版本一张 80 GB 卡+pip install "sophon-realtime[trt]" && sophon-realtime serve --port 8000++# 网关:两种协议在同一个端口+git clone https://github.com/adventists-ai/sophon-realtime && cd sophon-realtime/live+BUILD=tag PORT=8000 LIVE_PORT=8780 bash start_live.sh+```++网关会加载一个小的语音识别模型用于用户转写(约 2 GB 显存;国内请先从魔搭下载,见 [live/README_CN.md](../live/README_CN.md))。其他版本(Flash、4B)启动方式相同,见[模型列表](../README_CN.md)。把 8780 端口开放给运行智能体的机器。需要鉴权时,在网关上设置 `SOPHON_LIVE_REALTIME_KEYS_FILE`(Realtime)和 `SOPHON_LIVE_API_KEYS`(Live)。++## 2a. LiveKit Agents++```bash+pip install livekit-plugins-sophon # 会一起装上 livekit-agents 和 OpenAI 插件+```++**Realtime 模式**++```python+from livekit import agents+from livekit.agents import Agent, AgentSession, function_tool+from livekit.plugins import sophon+++class Assistant(Agent):+ def __init__(self):+ super().__init__(instructions="你是小诺,一个友好的语音助手,回答简短。")++ @function_tool+ async def get_weather(self, city: str) -> str:+ """查询某个城市现在的天气。"""+ return f"{city}:18 度,小雨"+++async def entrypoint(ctx: agents.JobContext):+ await ctx.connect()+ session = AgentSession(llm=sophon.RealtimeModel(base_url="http://你的服务器:8780/v1"))+ await session.start(room=ctx.room, agent=Assistant())+++if __name__ == "__main__":+ agents.cli.run_app(agents.WorkerOptions(entrypoint_fnc=entrypoint))+```++**Live 模式**(客户端委派)++```python+import asyncio+++class Receptionist(Agent):+ def __init__(self):+ super().__init__(instructions="你是小诺,一个友好的前台,回答简短。")++ async def on_enter(self):+ self.duplex_session.on("delegation_created", self._on_delegation)++ def _on_delegation(self, delegation):+ async def work():+ # 要办的事就是用户刚说的话;交给你自己的后台(大模型、工具、数据库……)+ answer = await my_backend(delegation.pending_transcript)+ self.duplex_session.append_commentary(answer, delegation_id=delegation.id)+ asyncio.create_task(work())+++async def entrypoint(ctx: agents.JobContext):+ await ctx.connect()+ session = AgentSession(llm=sophon.LiveModel(base_url="http://你的服务器:8780/v1"))+ await session.start(room=ctx.room, agent=Receptionist())+```++模型先说一句短话("我查一下"),把这一轮交给你的代码,再用自己的话把你的结果说出来。++原来用 OpenAI GPT-Live?`openai.realtime.GPTLiveModel(base_url="http://你的服务器:8780/v1", delegation="client")` 也可以直接用,`sophon.LiveModel` 只是把默认值填好了。++## 2b. Pipecat++```bash+pip install "pipecat-ai[openai]"+```++**Realtime 模式**++```python+from pipecat.services.openai.realtime.llm import OpenAIRealtimeLLMService++llm = OpenAIRealtimeLLMService(+ api_key="any", # 网关设了 key 就填 key+ base_url="ws://你的服务器:8780/v1/realtime",+ settings=OpenAIRealtimeLLMService.Settings(+ model="sophon-realtime",+ system_instruction="你是小诺,一个友好的语音助手,回答简短。",+ ),+)+pipeline = Pipeline([transport.input(), llm, transport.output()]) # 不要 VAD,不要话轮检测+```++**Live 模式**++```python+from pipecat.services.openai.live.llm import OpenAILiveLLMService++llm = OpenAILiveLLMService(api_key="any", base_url="ws://你的服务器:8780/v1/live/sessions")+# 和 OpenAI GPT-Live 一样,会话在第一个 LLMContextFrame(你的系统提示)到达时开始+```++完整可运行的 Pipecat 机器人(浏览器 WebRTC)见 [live/examples/pipecat_bot.py](../live/examples/pipecat_bot.py),LiveKit 示例见 [live/examples/livekit_agent.py](../live/examples/livekit_agent.py)。++## 3. 实测++从用户说完到客户端听到第一声回复的时间。每个模型一张 H100,一次一个对话,网关和引擎在同一台机器;每格是 3 条录音问题(中英文)× 3 次;livekit-agents 1.9.0、pipecat-ai 1.17.0。中位数(P90),单位秒。++| 模型 | 直连 WebSocket | LiveKit · Realtime | Pipecat · Realtime | LiveKit · Live | Pipecat · Live |+|---|---|---|---|---|---|+| 32B Tag | 0.47(0.56) | 0.55(0.63) | 0.50(0.52) | 0.54(0.61) | 0.51(0.52) |+| 4B Flash | 0.46(0.59) | 0.47(0.74) | 0.47(0.67) | 0.48(0.64) | 0.50(1.52) |++- 框架几乎不增加延迟:LiveKit 约多 0.05 秒,Pipecat 基本持平。+- 第 4 条录音(结尾带笑声的英文句子)在 32B Tag 上所有客户端都约 2.4 秒(模型在等确认你说完了),4B Flash 约 0.55–0.8 秒,没有计入上表。+- 另外测了:打断(32B Tag 在你开口约 0.26 秒后停声,你说完约 0.13 秒后接话)、通过 `@function_tool` 调函数(32B;你说完约 0.9 秒发出调用)、Live 模式下用 `append_commentary` 回答委派。+- 测试脚本:[`live/bench/frameworks/`](../live/bench/frameworks/)。++## 4. 建议和已知限制++- **在指令里给智能体起名字、写人设。**不写的话,模型可能自己编一个名字。+- **Live 模式下回复语言跟着指令走**:指令用用户说的语言写,或者写上"用用户的语言回答"。+- **函数调用**:32B 版本(Tag、Flash、E2E)支持;4B 版本不调工具,需要工具请用 Live 模式接你自己的后台,或者用 32B。+- 转写里可能出现 `[laughter]` 这类声音标签,它们是被"演"出来的,不会被念出来;要展示文字时可以过滤掉。+- 结尾带笑声的句子,32B Tag 版可能要约 2.4 秒才回答(它在等确认你说完了),我们在改。+- 一个网关对应一台引擎;要更大并发,在负载均衡后面放多个网关。diff --git a/integrations/livekit-plugins-sophon/README.md b/integrations/livekit-plugins-sophon/README.mdnew file mode 100644index 0000000..4b84857--- /dev/null+++ b/integrations/livekit-plugins-sophon/README.md@@ -0,0 +1,63 @@+# Sophon-Realtime plugin for LiveKit Agents++[Sophon-Realtime](https://github.com/adventists-ai/sophon-realtime) is an open-weights, **self-hosted, full-duplex** speech-to-speech model family (Apache-2.0): it listens while it talks, decides on its own when you have finished, and answers in an expressive voice. This plugin makes it the realtime model of a LiveKit agent.++You run the model on your own GPU; nothing is sent to a third-party API.++## Install++```bash+pip install livekit-plugins-sophon+```++## Run the model (your server)++```bash+pip install "sophon-realtime[trt]" && sophon-realtime serve --port 8000 # one 80 GB GPU+git clone https://github.com/adventists-ai/sophon-realtime && cd sophon-realtime/live+BUILD=tag PORT=8000 LIVE_PORT=8780 bash start_live.sh # the gateway LiveKit talks to+```++Smaller GPUs: see the 4B builds in the [model list](https://github.com/adventists-ai/sophon-realtime#models).++## Use it++```python+from livekit import agents+from livekit.agents import Agent, AgentSession+from livekit.plugins import sophon+++async def entrypoint(ctx: agents.JobContext):+ await ctx.connect()+ session = AgentSession(llm=sophon.RealtimeModel(base_url="http://YOUR_SERVER:8780/v1"))+ await session.start(room=ctx.room, agent=Agent(instructions="You are Nova, a friendly voice assistant. Keep replies short."))+++if __name__ == "__main__":+ agents.cli.run_app(agents.WorkerOptions(entrypoint_fnc=entrypoint))+```++`base_url` can also come from `SOPHON_BASE_URL`, and the key from `SOPHON_API_KEY` (only needed if you set `SOPHON_LIVE_REALTIME_KEYS_FILE` on the gateway).++| Parameter | Default | Notes |+|---|---|---|+| `base_url` | `SOPHON_BASE_URL` | The Live gateway (`http://HOST:LIVE_PORT/v1`), not the engine port |+| `api_key` | `SOPHON_API_KEY` or any value | |+| `model` | `sophon-realtime` | |+| `voice` | `chelsie` | Or a voice you cloned on the server |++Everything else (`http_session`, `conn_options`, `max_session_duration`, tools via `@function_tool`) works as with LiveKit's OpenAI realtime plugin.++## Notes++- **Turn-taking is server-side.** Do not add a VAD or turn detector; the model hears you while it speaks, so you can interrupt it.+- **Function calling** works with the 32B builds. The 4B builds do not call tools.+- Give the agent a name and persona in `instructions`; without one the model may invent a name.+- Replies can contain sound tags such as `[laughter]` in the transcript; they are performed, not read out.++## Links++- Model and server: https://github.com/adventists-ai/sophon-realtime+- Weights: https://huggingface.co/adventists-ai+- Framework guide and measurements: https://github.com/adventists-ai/sophon-realtime/blob/main/docs/frameworks.mddiff --git a/integrations/livekit-plugins-sophon/livekit/plugins/sophon/__init__.py b/integrations/livekit-plugins-sophon/livekit/plugins/sophon/__init__.pynew file mode 100644index 0000000..0208683--- /dev/null+++ b/integrations/livekit-plugins-sophon/livekit/plugins/sophon/__init__.py@@ -0,0 +1,21 @@+"""Sophon-Realtime plugin for LiveKit Agents.++Self-hosted, full-duplex speech-to-speech: run the model on your own GPU and use it as the+realtime model of a LiveKit agent. See https://github.com/adventists-ai/sophon-realtime.+"""++from livekit.agents import Plugin++from .log import logger+from .realtime import DEFAULT_MODEL, DEFAULT_VOICE, LiveModel, RealtimeModel+from .version import __version__++__all__ = ["RealtimeModel", "LiveModel", "DEFAULT_MODEL", "DEFAULT_VOICE", "__version__"]+++class SophonPlugin(Plugin):+ def __init__(self) -> None:+ super().__init__(__name__, __version__, __package__, logger)+++Plugin.register_plugin(SophonPlugin())diff --git a/integrations/livekit-plugins-sophon/livekit/plugins/sophon/log.py b/integrations/livekit-plugins-sophon/livekit/plugins/sophon/log.pynew file mode 100644index 0000000..9444fbf--- /dev/null+++ b/integrations/livekit-plugins-sophon/livekit/plugins/sophon/log.py@@ -0,0 +1,3 @@+import logging++logger = logging.getLogger("livekit.plugins.sophon")diff --git a/integrations/livekit-plugins-sophon/livekit/plugins/sophon/py.typed b/integrations/livekit-plugins-sophon/livekit/plugins/sophon/py.typednew file mode 100644index 0000000..e69de29diff --git a/integrations/livekit-plugins-sophon/livekit/plugins/sophon/realtime.py b/integrations/livekit-plugins-sophon/livekit/plugins/sophon/realtime.pynew file mode 100644index 0000000..49df23c--- /dev/null+++ b/integrations/livekit-plugins-sophon/livekit/plugins/sophon/realtime.py@@ -0,0 +1,91 @@+"""Sophon-Realtime as a LiveKit realtime model.++Sophon-Realtime is a self-hosted, full-duplex speech-to-speech model. Its Live gateway speaks the+OpenAI Realtime protocol, so this plugin reuses the OpenAI realtime client and only fills in the+right defaults (your server's address, the model name and a Sophon voice). Turn-taking runs on the+server: the model listens while it talks and decides when to answer, so no local VAD or turn+detector is needed.+"""++from __future__ import annotations++import os+from typing import Any++from livekit.agents.types import NOT_GIVEN, NotGivenOr+from livekit.agents.utils import is_given+from livekit.plugins import openai++DEFAULT_MODEL = "sophon-realtime"+DEFAULT_VOICE = "chelsie"+++class RealtimeModel(openai.realtime.RealtimeModel):+ """Self-hosted Sophon-Realtime model, ready to pass to ``AgentSession(llm=)``.++ Args:+ base_url: HTTP base URL of your Sophon Live gateway, for example ``http://HOST:8780/v1``.+ Falls back to ``SOPHON_BASE_URL``.+ api_key: A key from the gateway's ``SOPHON_LIVE_REALTIME_KEYS_FILE``, if you set one.+ Falls back to ``SOPHON_API_KEY``; a gateway without keys accepts any value.+ model: Model name the gateway serves. Defaults to ``sophon-realtime``.+ voice: A built-in voice (``chelsie``) or the name of a voice you cloned on the server.+ **kwargs: Passed to :class:`livekit.plugins.openai.realtime.RealtimeModel`+ (``http_session``, ``conn_options``, ``max_session_duration``, ...).+ """++ def __init__(+ self,+ *,+ base_url: NotGivenOr[str] = NOT_GIVEN,+ api_key: str | None = None,+ model: str = DEFAULT_MODEL,+ voice: str = DEFAULT_VOICE,+ **kwargs: Any,+ ) -> None:+ url = base_url if is_given(base_url) else os.environ.get("SOPHON_BASE_URL")+ if not url:+ raise ValueError(+ "Sophon-Realtime is self-hosted: pass base_url='http://YOUR_SERVER:8780/v1' "+ "or set SOPHON_BASE_URL (the Live gateway, not the engine port)."+ )+ key = api_key or os.environ.get("SOPHON_API_KEY") or "sophon"+ super().__init__(model=model, voice=voice, base_url=url, api_key=key, **kwargs)+++class LiveModel(openai.realtime.GPTLiveModel):+ """Self-hosted Sophon-Realtime behind the GPT-Live protocol (``/v1/live/sessions``).++ Code written for OpenAI GPT-Live with client delegation runs unchanged against your own server:+ the model talks, and hands work it cannot do itself to your application as+ ``delegation_created`` events, which you answer with ``session.append_commentary``.++ Args:+ base_url: HTTP base URL of your Sophon Live gateway (``http://HOST:8780/v1``).+ Falls back to ``SOPHON_BASE_URL``.+ api_key: Gateway key if you set one; falls back to ``SOPHON_API_KEY``.+ voice: A built-in voice or the name of a voice you cloned on the server.+ delegation: ``client`` (default). Sophon's gateway does not host a backend model, so+ ``responses`` delegation is not available.+ **kwargs: Passed to :class:`livekit.plugins.openai.realtime.GPTLiveModel`.+ """++ def __init__(+ self,+ *,+ base_url: NotGivenOr[str] = NOT_GIVEN,+ api_key: str | None = None,+ voice: str = DEFAULT_VOICE,+ delegation: str = "client",+ **kwargs: Any,+ ) -> None:+ url = base_url if is_given(base_url) else os.environ.get("SOPHON_BASE_URL")+ if not url:+ raise ValueError(+ "Sophon-Realtime is self-hosted: pass base_url='http://YOUR_SERVER:8780/v1' "+ "or set SOPHON_BASE_URL (the Live gateway, not the engine port)."+ )+ if delegation != "client":+ raise ValueError("Sophon's Live gateway supports delegation='client' only")+ key = api_key or os.environ.get("SOPHON_API_KEY") or "sophon"+ super().__init__(voice=voice, delegation="client", base_url=url, api_key=key, **kwargs)diff --git a/integrations/livekit-plugins-sophon/livekit/plugins/sophon/version.py b/integrations/livekit-plugins-sophon/livekit/plugins/sophon/version.pynew file mode 100644index 0000000..3dc1f76--- /dev/null+++ b/integrations/livekit-plugins-sophon/livekit/plugins/sophon/version.py@@ -0,0 +1 @@+__version__ = "0.1.0"diff --git a/integrations/livekit-plugins-sophon/pyproject.toml b/integrations/livekit-plugins-sophon/pyproject.tomlnew file mode 100644index 0000000..4ec556c--- /dev/null+++ b/integrations/livekit-plugins-sophon/pyproject.toml@@ -0,0 +1,35 @@+[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++[project]+name = "livekit-plugins-sophon"+dynamic = ["version"]+description = "Agent Framework plugin for Sophon-Realtime, a self-hosted full-duplex speech-to-speech model"+readme = "README.md"+license = "Apache-2.0"+requires-python = ">=3.10.0"+authors = [{ name = "Adventists AI" }]+keywords = ["voice", "ai", "realtime", "audio", "livekit", "speech-to-speech", "self-hosted", "full-duplex"]+classifiers = [+ "Intended Audience :: Developers",+ "License :: OSI Approved :: Apache Software License",+ "Topic :: Multimedia :: Sound/Audio",+ "Topic :: Scientific/Engineering :: Artificial Intelligence",+ "Programming Language :: Python :: 3",+ "Programming Language :: Python :: 3 :: Only",+]+dependencies = ["livekit-agents>=1.9.0", "livekit-plugins-openai>=1.9.0"]++[project.urls]+Documentation = "https://github.com/adventists-ai/sophon-realtime/blob/main/docs/frameworks.md"+Source = "https://github.com/adventists-ai/sophon-realtime"++[tool.hatch.version]+path = "livekit/plugins/sophon/version.py"++[tool.hatch.build.targets.wheel]+packages = ["livekit"]++[tool.hatch.build.targets.sdist]+include = ["/livekit"]diff --git a/integrations/livekit-plugins-sophon/pytest.ini b/integrations/livekit-plugins-sophon/pytest.ininew file mode 100644index 0000000..2f4c80e--- /dev/null+++ b/integrations/livekit-plugins-sophon/pytest.ini@@ -0,0 +1,2 @@+[pytest]+asyncio_mode = autodiff --git a/integrations/livekit-plugins-sophon/tests/test_realtime.py b/integrations/livekit-plugins-sophon/tests/test_realtime.pynew file mode 100644index 0000000..512c0b3--- /dev/null+++ b/integrations/livekit-plugins-sophon/tests/test_realtime.py@@ -0,0 +1,54 @@+import os++import aiohttp+import pytest++from livekit.plugins import sophon+++async def test_requires_base_url(monkeypatch):+ monkeypatch.delenv("SOPHON_BASE_URL", raising=False)+ with pytest.raises(ValueError):+ sophon.RealtimeModel()+++async def test_defaults_and_env(monkeypatch):+ monkeypatch.setenv("SOPHON_BASE_URL", "http://example:8780/v1")+ monkeypatch.delenv("SOPHON_API_KEY", raising=False)+ async with aiohttp.ClientSession() as http:+ m = sophon.RealtimeModel(http_session=http)+ assert m.model == "sophon-realtime"+ assert m._opts.voice == "chelsie"+ assert m._opts.base_url.startswith("http://example:8780/v1")+ assert m._opts.api_key == "sophon"+++async def test_explicit_args_win(monkeypatch):+ monkeypatch.setenv("SOPHON_BASE_URL", "http://env:1/v1")+ monkeypatch.setenv("SOPHON_API_KEY", "envkey")+ async with aiohttp.ClientSession() as http:+ m = sophon.RealtimeModel(base_url="http://arg:2/v1", api_key="argkey", voice="my_clone", http_session=http)+ assert m._opts.base_url.startswith("http://arg:2/v1")+ assert m._opts.api_key == "argkey"+ assert m._opts.voice == "my_clone"++[email protected](not os.environ.get("SOPHON_TEST_URL"), reason="set SOPHON_TEST_URL to a running gateway")+async def test_live_gateway_session():+ async with aiohttp.ClientSession() as http:+ m = sophon.RealtimeModel(base_url=os.environ["SOPHON_TEST_URL"], http_session=http)+ s = m.session()+ await s.aclose()+++async def test_live_model_defaults(monkeypatch):+ monkeypatch.setenv("SOPHON_BASE_URL", "http://example:8780/v1")+ async with aiohttp.ClientSession() as http:+ m = sophon.LiveModel(http_session=http)+ assert m._opts.delegation == "client"+++async def test_live_model_rejects_responses(monkeypatch):+ monkeypatch.setenv("SOPHON_BASE_URL", "http://example:8780/v1")+ with pytest.raises(ValueError):+ sophon.LiveModel(delegation="responses")diff --git a/live/README.md b/live/README.mdindex ccb4241..4a5d051 100644--- a/live/README.md+++ b/live/README.md@@ -39,10 +39,10 @@ The same gateway also serves an **OpenAI Realtime** compatible endpoint at `ws:/| Framework | What to change | Example | Tested ||---|---|---|---|-| LiveKit Agents | `openai.realtime.RealtimeModel(base_url="http://HOST:8780/v1", ...)` | [examples/livekit_agent.py](examples/livekit_agent.py) | livekit-agents 1.8.11 |-| Pipecat | `OpenAIRealtimeLLMService(base_url="ws://HOST:8780/v1/realtime", ...)` | [examples/pipecat_bot.py](examples/pipecat_bot.py) | pipecat-ai 1.15.0 |+| LiveKit Agents | `sophon.RealtimeModel(base_url="http://HOST:8780/v1")` ([livekit-plugins-sophon](../integrations/livekit-plugins-sophon/README.md)), or `openai.realtime.RealtimeModel(base_url=...)` | [examples/livekit_agent.py](examples/livekit_agent.py) | livekit-agents 1.9.0 |+| Pipecat | `OpenAIRealtimeLLMService(base_url="ws://HOST:8780/v1/realtime", ...)` | [examples/pipecat_bot.py](examples/pipecat_bot.py) | pipecat-ai 1.17.0 |-Both frameworks add no noticeable latency: Pipecat measured the same as a direct WebSocket client, LiveKit within about 0.1 s.+The GPT-Live clients of both frameworks work too (`sophon.LiveModel` / `openai.realtime.GPTLiveModel(base_url=..., delegation="client")` in LiveKit, `OpenAILiveLLMService(base_url="ws://HOST:8780/v1/live/sessions")` in Pipecat). Both frameworks add little latency (LiveKit about 0.05 s, Pipecat about nothing). Full guide and measurements: [docs/frameworks.md](../docs/frameworks.md).Set `SOPHON_LIVE_REALTIME_KEYS_FILE` (one key per line) to require a bearer key on `/v1/realtime`.diff --git a/live/README_CN.md b/live/README_CN.mdindex 3d8a7d5..321f24f 100644--- a/live/README_CN.md+++ b/live/README_CN.md@@ -30,10 +30,10 @@ GPT-Live 客户端连 `ws://HOST:8780/v1/live/sessions` 即可;浏览器打开| 框架 | 要改的地方 | 示例 | 实测 ||---|---|---|---|-| LiveKit Agents | `openai.realtime.RealtimeModel(base_url="http://HOST:8780/v1", ...)` | [examples/livekit_agent.py](examples/livekit_agent.py) | livekit-agents 1.8.11 |-| Pipecat | `OpenAIRealtimeLLMService(base_url="ws://HOST:8780/v1/realtime", ...)` | [examples/pipecat_bot.py](examples/pipecat_bot.py) | pipecat-ai 1.15.0 |+| LiveKit Agents | `sophon.RealtimeModel(base_url="http://HOST:8780/v1")`([livekit-plugins-sophon](../integrations/livekit-plugins-sophon/README.md)),或 `openai.realtime.RealtimeModel(base_url=...)` | [examples/livekit_agent.py](examples/livekit_agent.py) | livekit-agents 1.9.0 |+| Pipecat | `OpenAIRealtimeLLMService(base_url="ws://HOST:8780/v1/realtime", ...)` | [examples/pipecat_bot.py](examples/pipecat_bot.py) | pipecat-ai 1.17.0 |-两个框架都几乎不增加延迟:Pipecat 与直连 WebSocket 客户端相同,LiveKit 多约 0.1 秒以内。+两个框架的 GPT-Live 客户端也能直接用(LiveKit 用 `sophon.LiveModel` 或 `openai.realtime.GPTLiveModel(base_url=..., delegation="client")`,Pipecat 用 `OpenAILiveLLMService(base_url="ws://HOST:8780/v1/live/sessions")`)。两个框架几乎不增加延迟(LiveKit 约多 0.05 秒,Pipecat 基本持平)。完整教程和实测:[docs/frameworks_CN.md](../docs/frameworks_CN.md)。需要鉴权时设置 `SOPHON_LIVE_REALTIME_KEYS_FILE`(每行一个 key),`/v1/realtime` 就会要求 bearer key。diff --git a/live/bench/frameworks/README.md b/live/bench/frameworks/README.mdnew file mode 100644index 0000000..5d38573--- /dev/null+++ b/live/bench/frameworks/README.md@@ -0,0 +1,18 @@+# Framework measurements++Scripts behind the numbers in [docs/frameworks.md](../../../docs/frameworks.md). Each one plays a recorded question from `live/cases/` into a running gateway in real time (24 kHz, 20 ms chunks, then silence like an open microphone) and prints one JSON line with `lat` = seconds from the last voiced chunk sent to the first loud audio chunk received.++| Script | Client |+|---|---|+| `direct_realtime.py` | plain WebSocket, OpenAI Realtime protocol |+| `livekit_realtime.py` | LiveKit Agents, `livekit-plugins-sophon` `RealtimeModel` |+| `pipecat_realtime.py` | Pipecat `OpenAIRealtimeLLMService` |+| `livekit_live.py` | LiveKit Agents, `sophon.LiveModel` (GPT-Live protocol, client delegation) |+| `pipecat_live.py` | Pipecat `OpenAILiveLLMService` (GPT-Live protocol) |+| `realtime_functions.py` | function call, barge-in and multi-turn checks over the Realtime protocol |+| `livekit_tools.py` | a `@function_tool` round trip through LiveKit |++```bash+pip install livekit-plugins-sophon "pipecat-ai[openai]" websockets numpy+bash run.sh 127.0.0.1:8780 3 > results.jsonl && python summarize.py results.jsonl+```diff --git a/live/bench/frameworks/common.py b/live/bench/frameworks/common.pynew file mode 100644index 0000000..8111ea7--- /dev/null+++ b/live/bench/frameworks/common.py@@ -0,0 +1,14 @@+"""Shared timing rules for all clients.+- input: a WAV resampled to 24 kHz PCM16, sent in real time in 20 ms chunks, followed by real-time silence (like an open mic)+- speech end: wall-clock time when the chunk containing the last voiced sample (|x| > 500 in the file) was sent+- first audio: wall-clock time when the client first receives an output audio chunk with |x| > 500+- latency = first audio - speech end"""+import time, wave, numpy as np+SR = 24000; STEP = SR // 50; THR = 500+def load(p):+ w = wave.open(p); a = np.frombuffer(w.readframes(w.getnframes()), "<i2").astype(np.float32); sr = w.getframerate()+ n = int(len(a) * SR / sr); a = np.interp(np.linspace(0, len(a) - 1, n), np.arange(len(a)), a).astype(np.int16)+ voiced = np.nonzero(np.abs(a) > THR)[0]; last = int(voiced[-1]) if len(voiced) else len(a) - 1+ return a, last // STEP # index of the chunk holding the last voiced sample+def loud(b):+ x = np.frombuffer(b, "<i2"); return len(x) > 0 and int(np.abs(x).max()) > THRdiff --git a/live/bench/frameworks/direct_realtime.py b/live/bench/frameworks/direct_realtime.pynew file mode 100644index 0000000..83fc13f--- /dev/null+++ b/live/bench/frameworks/direct_realtime.py@@ -0,0 +1,27 @@+import asyncio, base64, json, sys, time, websockets, numpy as np+from common import *+URL, WAV = sys.argv[1], sys.argv[2]+async def main():+ a, last = load(WAV); R = {"client": "direct-realtime", "wav": WAV.split("/")[-1], "lat": None, "text": ""}; t_end = [None]; got = asyncio.Event()+ async with websockets.connect(URL + "?model=sophon-realtime", max_size=None, additional_headers={"Authorization": "Bearer any"}) as ws:+ await ws.send(json.dumps({"type": "session.update", "session": {"type": "realtime", "audio": {"input": {"format": {"type": "audio/pcm", "rate": SR}, "turn_detection": {"type": "server_vad"}}, "output": {"format": {"type": "audio/pcm", "rate": SR}, "voice": "chelsie"}}}}))+ async def rx():+ async for m in ws:+ e = json.loads(m); t = e.get("type", "")+ if t in ("response.output_audio.delta", "response.audio.delta"):+ if R["lat"] is None and t_end[0] and loud(base64.b64decode(e["delta"])): R["lat"] = time.monotonic() - t_end[0]+ elif t in ("response.output_audio_transcript.delta", "response.audio_transcript.delta"): R["text"] += e.get("delta", "")+ elif t == "response.done" and R["lat"] is not None: got.set()+ task = asyncio.create_task(rx()); await asyncio.sleep(1.0)+ t0 = time.monotonic(); sil = np.zeros(STEP, np.int16)+ for k, i in enumerate(range(0, len(a), STEP)):+ await ws.send(json.dumps({"type": "input_audio_buffer.append", "audio": base64.b64encode(a[i:i + STEP].tobytes()).decode()}))+ if k == last: t_end[0] = time.monotonic()+ await asyncio.sleep(max(0, t0 + (k + 1) * 0.02 - time.monotonic()))+ k0 = k+ while not got.is_set() and time.monotonic() - t_end[0] < 15:+ k0 += 1; await ws.send(json.dumps({"type": "input_audio_buffer.append", "audio": base64.b64encode(sil.tobytes()).decode()}))+ await asyncio.sleep(max(0, t0 + (k0 + 1) * 0.02 - time.monotonic()))+ task.cancel()+ print(json.dumps(R, ensure_ascii=False))+asyncio.run(main())diff --git a/live/bench/frameworks/livekit_live.py b/live/bench/frameworks/livekit_live.pynew file mode 100644index 0000000..ab1f52d--- /dev/null+++ b/live/bench/frameworks/livekit_live.py@@ -0,0 +1,44 @@+"""11-29 Claude: LiveKit GPTLiveModel (client delegation) against a Sophon Live gateway's /v1/live/sessions.+Measures speech end -> first loud audio; answers delegations with append_commentary."""+import asyncio, json, sys, time, aiohttp, numpy as np+from livekit import rtc+from livekit.plugins import sophon+from common import *+URL, WAV = sys.argv[1], sys.argv[2]+ANS = {"weather": "Shanghai tomorrow: light rain, 14 to 19 degrees.", "time": "It is 3:20 pm."}+async def main():+ a, last = load(WAV); R = {"client": "livekit-live", "wav": WAV.split("/")[-1], "lat": None, "deleg": [], "user": "", "text": ""}; t_end = [None]; got = asyncio.Event()+ async with aiohttp.ClientSession() as http:+ s = sophon.LiveModel(base_url=URL, http_session=http).session()+ def on_deleg(ev):+ R["deleg"].append(getattr(ev, "task", None) or str(ev)[:80])+ async def answer():+ await asyncio.sleep(1.0)+ did = getattr(ev, "delegation_id", None) or getattr(ev, "id", None)+ s.append_commentary(ANS["weather"] if "weather" in WAV else ANS["time"], delegation_id=did)+ asyncio.create_task(answer())+ s.on("delegation_created", on_deleg)+ def on_ev(e):+ t = e.get("type", "")+ if t == "session.output_transcript.delta": R["text"] += e.get("delta", "")+ elif t == "session.input_transcript.delta": R["user"] += e.get("delta", "")+ s.on("openai_server_event_received", on_ev)+ async def aud():+ async for f in s.audio_stream:+ if R["lat"] is None and t_end[0] and loud(bytes(f.frame.data)): R["lat"] = time.monotonic() - t_end[0]; got.set()+ at = asyncio.create_task(aud())+ await s._update_session(instructions="You are Nova, a friendly voice assistant. Keep replies short.")+ await asyncio.sleep(1.5)+ t0 = time.monotonic(); sil = np.zeros(STEP, np.int16)+ for k, i in enumerate(range(0, len(a), STEP)):+ c = a[i:i + STEP]; s.push_audio(rtc.AudioFrame(c.tobytes(), SR, 1, len(c)))+ if k == last: t_end[0] = time.monotonic()+ await asyncio.sleep(max(0, t0 + (k + 1) * 0.02 - time.monotonic()))+ k0 = k; tl = time.monotonic() + (10 if R["deleg"] or "weather" in WAV or "time" in WAV else 6)+ while time.monotonic() < tl:+ k0 += 1; s.push_audio(rtc.AudioFrame(sil.tobytes(), SR, 1, STEP))+ await asyncio.sleep(max(0, t0 + (k0 + 1) * 0.02 - time.monotonic()))+ await s.aclose(); at.cancel()+ R["lat"] = R["lat"] and round(R["lat"], 3); R["text"] = R["text"][:160]+ print(json.dumps(R, ensure_ascii=False))+asyncio.run(main())diff --git a/live/bench/frameworks/livekit_realtime.py b/live/bench/frameworks/livekit_realtime.pynew file mode 100644index 0000000..a49184f--- /dev/null+++ b/live/bench/frameworks/livekit_realtime.py@@ -0,0 +1,31 @@+import asyncio, json, sys, time, aiohttp, numpy as np+from livekit import rtc+from livekit.plugins import sophon+from common import *+URL, WAV = sys.argv[1], sys.argv[2]+async def main():+ a, last = load(WAV); R = {"client": "livekit-realtime", "wav": WAV.split("/")[-1], "lat": None, "text": ""}; t_end = [None]; got = asyncio.Event()+ async with aiohttp.ClientSession() as http:+ s = sophon.RealtimeModel(base_url=URL, http_session=http).session()+ async def consume(ev):+ async for msg in ev.message_stream:+ async def txt():+ async for t in msg.text_stream: R["text"] += t+ async def aud():+ async for f in msg.audio_stream:+ if R["lat"] is None and t_end[0] and loud(bytes(f.data)): R["lat"] = time.monotonic() - t_end[0]; got.set()+ await asyncio.gather(txt(), aud())+ s.on("generation_created", lambda ev: asyncio.create_task(consume(ev)))+ await asyncio.sleep(1.0)+ t0 = time.monotonic(); sil = np.zeros(STEP, np.int16)+ for k, i in enumerate(range(0, len(a), STEP)):+ c = a[i:i + STEP]; s.push_audio(rtc.AudioFrame(c.tobytes(), SR, 1, len(c)))+ if k == last: t_end[0] = time.monotonic()+ await asyncio.sleep(max(0, t0 + (k + 1) * 0.02 - time.monotonic()))+ k0 = k+ while not got.is_set() and time.monotonic() - t_end[0] < 15:+ k0 += 1; s.push_audio(rtc.AudioFrame(sil.tobytes(), SR, 1, STEP))+ await asyncio.sleep(max(0, t0 + (k0 + 1) * 0.02 - time.monotonic()))+ await asyncio.sleep(3); await s.aclose()+ print(json.dumps(R, ensure_ascii=False))+asyncio.run(main())diff --git a/live/bench/frameworks/livekit_tools.py b/live/bench/frameworks/livekit_tools.pynew file mode 100644index 0000000..f0d86ce--- /dev/null+++ b/live/bench/frameworks/livekit_tools.py@@ -0,0 +1,42 @@+"""11-29 Claude: LiveKit Realtime (sophon plugin) framework-level function call: update_tools + function_stream."""+import asyncio, json, sys, time, aiohttp, numpy as np+from livekit import rtc+from livekit.agents import llm+from livekit.plugins import sophon+from common import *+URL, WAV = sys.argv[1], sys.argv[2][email protected]_tool+async def get_weather(city: str) -> str:+ """Get the current weather for a city."""+ return f"{city}: 18 degrees, light rain"+async def main():+ a, last = load(WAV); R = {"client": "lk-plugin-tool", "wav": WAV.split("/")[-1], "calls": [], "after_call_text": ""}; t_end = [None]+ async with aiohttp.ClientSession() as http:+ s = sophon.RealtimeModel(base_url=URL, http_session=http).session()+ await s.update_instructions("You are Nova, a friendly voice assistant. Keep replies short. Use get_weather for any weather question.")+ await s.update_tools([get_weather])+ async def consume(ev):+ async def fns():+ async for fc in ev.function_stream:+ R["calls"].append({"name": fc.name, "args": fc.arguments, "t_after_speech_end": round(time.monotonic() - t_end[0], 2) if t_end[0] else None})+ out = await get_weather(**json.loads(fc.arguments))+ ctx = s.chat_ctx.copy(); ctx.items.append(llm.FunctionCallOutput(call_id=fc.call_id, name=fc.name, output=out, is_error=False))+ await s.update_chat_ctx(ctx); s.generate_reply()+ async def msgs():+ async for m in ev.message_stream:+ async for t in m.text_stream:+ if R["calls"]: R["after_call_text"] += t+ await asyncio.gather(fns(), msgs())+ s.on("generation_created", lambda ev: asyncio.create_task(consume(ev)))+ await asyncio.sleep(1.0); t0 = time.monotonic(); sil = np.zeros(STEP, np.int16)+ for k, i in enumerate(range(0, len(a), STEP)):+ c = a[i:i + STEP]; s.push_audio(rtc.AudioFrame(c.tobytes(), SR, 1, len(c)))+ if k == last: t_end[0] = time.monotonic()+ await asyncio.sleep(max(0, t0 + (k + 1) * 0.02 - time.monotonic()))+ k0 = k+ while time.monotonic() - t_end[0] < 10:+ k0 += 1; s.push_audio(rtc.AudioFrame(sil.tobytes(), SR, 1, STEP))+ await asyncio.sleep(max(0, t0 + (k0 + 1) * 0.02 - time.monotonic()))+ await s.aclose()+ print(json.dumps(R, ensure_ascii=False))+asyncio.run(main())diff --git a/live/bench/frameworks/pipecat_live.py b/live/bench/frameworks/pipecat_live.pynew file mode 100644index 0000000..17636ff--- /dev/null+++ b/live/bench/frameworks/pipecat_live.py@@ -0,0 +1,38 @@+import asyncio, json, sys, time, numpy as np+from loguru import logger; logger.remove()+from pipecat.frames.frames import LLMContextFrame, InputAudioRawFrame, TTSAudioRawFrame, LLMTextFrame, EndFrame+from pipecat.pipeline.pipeline import Pipeline+from pipecat.pipeline.runner import PipelineRunner+from pipecat.pipeline.task import PipelineTask, PipelineParams+from pipecat.processors.frame_processor import FrameProcessor+from pipecat.services.openai.live.llm import OpenAILiveLLMService+from pipecat.processors.aggregators.llm_context import LLMContext+from common import *+URL, WAV = sys.argv[1], sys.argv[2]+R = {"client": "pipecat-live", "wav": WAV.split("/")[-1], "lat": None, "text": ""}; T_END = [None]+class Sink(FrameProcessor):+ async def process_frame(self, frame, direction):+ await super().process_frame(frame, direction)+ if hasattr(frame, "audio") and not isinstance(frame, InputAudioRawFrame):+ if R["lat"] is None and T_END[0] and loud(frame.audio): R["lat"] = time.monotonic() - T_END[0]+ elif isinstance(frame, LLMTextFrame): R["text"] += frame.text+ await self.push_frame(frame, direction)+async def main():+ llm = OpenAILiveLLMService(api_key="any", base_url=URL)+ task = PipelineTask(Pipeline([llm, Sink()]), params=PipelineParams(audio_in_sample_rate=SR, audio_out_sample_rate=SR))+ async def feed():+ await task.queue_frame(LLMContextFrame(LLMContext(messages=[{"role": "system", "content": "You are Nova, a friendly voice assistant. Keep replies short."}])))+ await asyncio.sleep(3)+ a, last = load(WAV); t0 = time.monotonic(); sil = np.zeros(STEP, np.int16).tobytes()+ for k, i in enumerate(range(0, len(a), STEP)):+ await task.queue_frame(InputAudioRawFrame(a[i:i + STEP].tobytes(), SR, 1))+ if k == last: T_END[0] = time.monotonic()+ await asyncio.sleep(max(0, t0 + (k + 1) * 0.02 - time.monotonic()))+ k0 = k+ while R["lat"] is None and time.monotonic() - T_END[0] < 15:+ k0 += 1; await task.queue_frame(InputAudioRawFrame(sil, SR, 1))+ await asyncio.sleep(max(0, t0 + (k0 + 1) * 0.02 - time.monotonic()))+ await asyncio.sleep(3); await task.queue_frame(EndFrame())+ await asyncio.gather(PipelineRunner(handle_sigint=False).run(task), feed())+ print(json.dumps(R, ensure_ascii=False))+asyncio.run(main())diff --git a/live/bench/frameworks/pipecat_realtime.py b/live/bench/frameworks/pipecat_realtime.pynew file mode 100644index 0000000..688bc8f--- /dev/null+++ b/live/bench/frameworks/pipecat_realtime.py@@ -0,0 +1,36 @@+import asyncio, json, sys, time, numpy as np+from loguru import logger; logger.remove()+from pipecat.frames.frames import InputAudioRawFrame, TTSAudioRawFrame, LLMTextFrame, EndFrame+from pipecat.pipeline.pipeline import Pipeline+from pipecat.pipeline.runner import PipelineRunner+from pipecat.pipeline.task import PipelineTask, PipelineParams+from pipecat.processors.frame_processor import FrameProcessor+from pipecat.services.openai.realtime.llm import OpenAIRealtimeLLMService+from common import *+URL, WAV = sys.argv[1], sys.argv[2]+R = {"client": "pipecat-realtime", "wav": WAV.split("/")[-1], "lat": None, "text": ""}; T_END = [None]+class Sink(FrameProcessor):+ async def process_frame(self, frame, direction):+ await super().process_frame(frame, direction)+ if isinstance(frame, TTSAudioRawFrame):+ if R["lat"] is None and T_END[0] and loud(frame.audio): R["lat"] = time.monotonic() - T_END[0]+ elif isinstance(frame, LLMTextFrame): R["text"] += frame.text+ await self.push_frame(frame, direction)+async def main():+ llm = OpenAIRealtimeLLMService(api_key="any", base_url=URL, model="sophon-realtime")+ task = PipelineTask(Pipeline([llm, Sink()]), params=PipelineParams(audio_in_sample_rate=SR, audio_out_sample_rate=SR))+ async def feed():+ await asyncio.sleep(3)+ a, last = load(WAV); t0 = time.monotonic(); sil = np.zeros(STEP, np.int16).tobytes()+ for k, i in enumerate(range(0, len(a), STEP)):+ await task.queue_frame(InputAudioRawFrame(a[i:i + STEP].tobytes(), SR, 1))+ if k == last: T_END[0] = time.monotonic()+ await asyncio.sleep(max(0, t0 + (k + 1) * 0.02 - time.monotonic()))+ k0 = k+ while R["lat"] is None and time.monotonic() - T_END[0] < 15:+ k0 += 1; await task.queue_frame(InputAudioRawFrame(sil, SR, 1))+ await asyncio.sleep(max(0, t0 + (k0 + 1) * 0.02 - time.monotonic()))+ await asyncio.sleep(3); await task.queue_frame(EndFrame())+ await asyncio.gather(PipelineRunner(handle_sigint=False).run(task), feed())+ print(json.dumps(R, ensure_ascii=False))+asyncio.run(main())diff --git a/live/bench/frameworks/realtime_functions.py b/live/bench/frameworks/realtime_functions.pynew file mode 100644index 0000000..6a3e61c--- /dev/null+++ b/live/bench/frameworks/realtime_functions.py@@ -0,0 +1,85 @@+"""11-29 Claude: OpenAI-Realtime-protocol checks against a Sophon Live gateway: tool call, barge-in, multi-turn.+usage: python rt_func.py ws://HOST:PORT/v1/realtime CASES_DIR"""+import asyncio, base64, json, sys, time+import numpy as np, websockets+from common import load, loud, SR, STEP+URL, C = sys.argv[1], sys.argv[2]+TOOLS = [{"type": "function", "name": "get_weather", "description": "Get the current weather for a city.",+ "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}]+class S:+ def __init__(s): s.ev = []; s.audio_t = []; s.text = ""; s.calls = []; s.t0 = time.monotonic()+ def t(s): return round(time.monotonic() - s.t0, 2)+async def session(st, ws):+ async for raw in ws:+ e = json.loads(raw); ty = e["type"]+ if ty == "response.output_audio.delta" or ty == "response.audio.delta":+ if loud(base64.b64decode(e["delta"])): st.audio_t.append(st.t())+ elif ty in ("response.output_audio_transcript.delta", "response.audio_transcript.delta", "response.output_text.delta"): st.text += e["delta"]+ elif ty == "response.function_call_arguments.done": st.calls.append((st.t(), e.get("name"), e.get("arguments"), e.get("call_id")))+ if ty not in ("response.output_audio.delta", "response.audio.delta", "response.output_audio_transcript.delta", "response.audio_transcript.delta"):+ st.ev.append((st.t(), ty))+async def stream(ws, a, st, t_mark=None):+ t0 = time.monotonic()+ for k, i in enumerate(range(0, len(a), STEP)):+ await ws.send(json.dumps({"type": "input_audio_buffer.append", "audio": base64.b64encode(a[i:i + STEP].tobytes()).decode()}))+ await asyncio.sleep(max(0, t0 + (k + 1) * 0.02 - time.monotonic()))+async def silence(ws, sec):+ z = np.zeros(STEP, np.int16).tobytes(); t0 = time.monotonic()+ for k in range(int(sec * 50)):+ await ws.send(json.dumps({"type": "input_audio_buffer.append", "audio": base64.b64encode(z).decode()}))+ await asyncio.sleep(max(0, t0 + (k + 1) * 0.02 - time.monotonic()))+async def open_(tools=None):+ ws = await websockets.connect(URL + "?model=sophon-realtime", max_size=None, additional_headers={"Authorization": "Bearer any"})+ sess = {"type": "realtime", "instructions": "You are a friendly voice assistant. Keep replies short. Use tools when the user asks for live data."}+ if tools: sess["tools"] = tools+ await ws.send(json.dumps({"type": "session.update", "session": sess})); return ws+async def tool_case(wav):+ st = S(); ws = await open_(TOOLS); rt = asyncio.create_task(session(st, ws))+ a, last = load(f"{C}/{wav}"); await silence(ws, 0.5); await stream(ws, a, st); t_end = st.t()+ for _ in range(300):+ if st.calls: break+ await silence(ws, 0.05)+ n_before = len(st.audio_t)+ if st.calls:+ cid = st.calls[0][3]+ await ws.send(json.dumps({"type": "conversation.item.create", "item": {"type": "function_call_output", "call_id": cid, "output": json.dumps({"city": "Shanghai", "temp_c": 18, "sky": "light rain"})}}))+ await ws.send(json.dumps({"type": "response.create"})); t_out = st.t()+ await silence(ws, 8)+ after = [x for x in st.audio_t if x > t_out]+ res = {"case": "tool", "wav": wav, "call": st.calls[0][1:3], "call_after_speech_end_s": round(st.calls[0][0] - t_end, 2),+ "result_to_audio_s": round(after[0] - t_out, 2) if after else None, "text": st.text[-120:]}+ else:+ await silence(ws, 3); res = {"case": "tool", "wav": wav, "call": None, "text": st.text[-120:]}+ rt.cancel(); await ws.close(); return res+async def barge_case():+ st = S(); ws = await open_(); rt = asyncio.create_task(session(st, ws))+ q, _ = load(f"{C}/en_know.wav"); b, _ = load(f"{C}/zh_chat1.wav")+ await silence(ws, 0.5); await stream(ws, q, st)+ for _ in range(400):+ if st.audio_t: break+ await silence(ws, 0.02)+ t_first = st.audio_t[0] if st.audio_t else None+ await silence(ws, 1.5); t_barge = st.t(); await stream(ws, b, st); t_b_end = st.t()+ await silence(ws, 6)+ gap = [x for x in st.audio_t if t_barge < x < t_b_end]+ stop = None+ for i in range(1, len(st.audio_t)):+ if st.audio_t[i - 1] > t_barge and st.audio_t[i] - st.audio_t[i - 1] > 0.3: stop = st.audio_t[i - 1]; break+ after = [x for x in st.audio_t if x > t_b_end]+ ev = [e for e in st.ev if e[0] >= t_barge and e[1] in ("input_audio_buffer.speech_started", "response.cancelled", "response.done", "response.created", "conversation.item.truncated")]+ rt.cancel(); await ws.close()+ return {"case": "barge", "first_audio": t_first, "barge_at": t_barge, "audio_during_barge_s": round((gap[-1] - gap[0]) if gap else 0, 2) if gap else 0,+ "last_audio_before_stop": stop, "new_reply_after_s": round(after[0] - t_b_end, 2) if after else None, "events": ev[:8], "text": st.text[-100:]}+async def multi_case():+ st = S(); ws = await open_(); rt = asyncio.create_task(session(st, ws)); out = []+ await silence(ws, 0.5)+ for w in ("d_hello.wav", "d_name.wav", "zh_chat2.wav", "d_bye.wav"):+ a, _ = load(f"{C}/{w}"); n0 = len(st.text); await stream(ws, a, st); t_end = st.t()+ await silence(ws, 6); aft = [x for x in st.audio_t if x > t_end]+ out.append((w, round(aft[0] - t_end, 2) if aft else None, st.text[n0:][:60]))+ rt.cancel(); await ws.close(); return {"case": "multi", "turns": out}+async def main():+ for c in ("zh_weather.wav", "en_weather.wav"): print(json.dumps(await tool_case(c), ensure_ascii=False), flush=True)+ print(json.dumps(await barge_case(), ensure_ascii=False), flush=True)+ print(json.dumps(await multi_case(), ensure_ascii=False), flush=True)+asyncio.run(main())diff --git a/live/bench/frameworks/run.sh b/live/bench/frameworks/run.shnew file mode 100755index 0000000..805c6db--- /dev/null+++ b/live/bench/frameworks/run.sh@@ -0,0 +1,12 @@+#!/bin/bash+# Latency of every client against one Sophon Live gateway. usage: bash run.sh [HOST:PORT] [ROUNDS]+# needs: pip install livekit-plugins-sophon "pipecat-ai[openai]" websockets numpy+cd "$(dirname "$0")"; G=${1:-127.0.0.1:8780}; N=${2:-3}; C=../../cases; P=${PYTHON:-python}+run(){ timeout 60 "$@" 2>/dev/null | grep "^{" | tail -1; }+for r in $(seq $N); do for w in en_know en_chat zh_chat1 zh_know; do+ run $P direct_realtime.py ws://$G/v1/realtime $C/$w.wav+ run $P livekit_realtime.py http://$G/v1 $C/$w.wav+ run $P pipecat_realtime.py ws://$G/v1/realtime $C/$w.wav+ run $P livekit_live.py http://$G/v1 $C/$w.wav+ run $P pipecat_live.py ws://$G/v1/live/sessions $C/$w.wav+done; donediff --git a/live/bench/frameworks/summarize.py b/live/bench/frameworks/summarize.pynew file mode 100644index 0000000..5125069--- /dev/null+++ b/live/bench/frameworks/summarize.py@@ -0,0 +1,9 @@+"""Median / P90 per client from run.sh output (one JSON line per run). usage: python summarize.py results.jsonl"""+import json, statistics, sys+d = {}+for line in open(sys.argv[1]):+ try: j = json.loads(line)+ except ValueError: continue+ if j.get("lat") is not None: d.setdefault((j["client"], j["wav"] == "en_chat.wav"), []).append(j["lat"])+for (c, laugh), v in sorted(d.items()):+ v.sort(); print(f"{c:18s} {'laughter clip' if laugh else 'other clips '} n={len(v):2d} median={statistics.median(v):.2f} p90={v[int(0.9 * (len(v) - 1))]:.2f}")diff --git a/live/examples/livekit_agent.py b/live/examples/livekit_agent.pyindex 60e0008..bf0e15a 100644--- a/live/examples/livekit_agent.py+++ b/live/examples/livekit_agent.py@@ -1,36 +1,34 @@"""LiveKit Agents voice agent backed by a self-hosted Sophon-Realtime model.-The Live gateway speaks the OpenAI Realtime protocol, so LiveKit's own OpenAI plugin works unchanged:-point RealtimeModel at the gateway with base_url.-- pip install "livekit-agents[openai]"+ pip install livekit-plugins-sophon# engine + gateway on YOUR_SERVER (see ../README.md):# sophon-realtime serve --port 8000# BUILD=tag PORT=8000 LIVE_PORT=8780 bash ../start_live.sh- python livekit_agent.py dev # needs LIVEKIT_URL / LIVEKIT_API_KEY / LIVEKIT_API_SECRET+ SOPHON_BASE_URL=http://YOUR_SERVER:8780/v1 python livekit_agent.py dev # needs LIVEKIT_URL / LIVEKIT_API_KEY / LIVEKIT_API_SECRET-Tested with livekit-agents 1.8.11: reply text and audio stream back.+Live mode (GPT-Live protocol, client delegation): use sophon.LiveModel instead, see ../../docs/frameworks.md.+Tested with livekit-agents 1.9.0 and livekit-plugins-sophon 0.1.0."""-import os-from livekit import agents-from livekit.agents import Agent, AgentSession-from livekit.plugins import openai+from livekit.agents import Agent, AgentSession, function_tool+from livekit.plugins import sophon+++class Assistant(Agent):+ def __init__(self):+ # give the agent a name and a persona: without one the model may invent a name+ super().__init__(instructions="You are Nova, a friendly voice assistant. Keep replies short.")-SOPHON_URL = os.environ.get("SOPHON_URL", "http://YOUR_SERVER:8780/v1") # the Live gateway, not the engine port+ @function_tool+ async def get_weather(self, city: str) -> str:+ """Get the current weather for a city."""+ return f"{city}: 18 degrees, light rain" # call your real weather API hereasync def entrypoint(ctx: agents.JobContext):await ctx.connect()- session = AgentSession(- llm=openai.realtime.RealtimeModel(- base_url=SOPHON_URL,- api_key=os.environ.get("SOPHON_API_KEY", "any"), # one of SOPHON_LIVE_REALTIME_KEYS if you set keys- model="sophon-realtime",- voice="chelsie",- )- )- await session.start(room=ctx.room, agent=Agent(instructions="You are a friendly voice assistant. Keep replies short."))+ session = AgentSession(llm=sophon.RealtimeModel()) # base_url from SOPHON_BASE_URL+ await session.start(room=ctx.room, agent=Assistant())if __name__ == "__main__":diff --git a/live/examples/pipecat_bot.py b/live/examples/pipecat_bot.pyindex 4848a96..5dda02a 100644--- a/live/examples/pipecat_bot.py+++ b/live/examples/pipecat_bot.py@@ -12,7 +12,7 @@ Bot:SOPHON_URL=ws://YOUR_SERVER:8780/v1/realtime python pipecat_bot.py# then open http://localhost:7860/client in a browser and talk-Tested with Pipecat v1.15.0. Maintained by Adventists AI (the Sophon-Realtime authors).+Tested with Pipecat v1.17.0. Maintained by Adventists AI (the Sophon-Realtime authors)."""import os@@ -46,7 +46,7 @@ async def run_bot(transport: BaseTransport, runner_args: RunnerArguments):base_url=SOPHON_URL,settings=OpenAIRealtimeLLMService.Settings(model="sophon-realtime",- system_instruction="You are a friendly voice assistant. Keep replies to one or two short sentences.",+ system_instruction="You are Nova, a friendly voice assistant. Keep replies to one or two short sentences.",),)