LiveKit Agents 接入 Inworld:语音合成(TTS)与流式语音识别(STT)插件实战指南
LiveKit Agents 接入 Inworld语音合成TTS与流式语音识别STT插件实战指南【免费下载链接】agentsA framework for building realtime voice AI agents ️项目地址: https://gitcode.com/GitHub_Trending/agen/agents本指南围绕 livekit-plugins-inworld 插件的完整能力展开讲解如何在 LiveKit Agents 语音 Agent 中接入 Inworld 的语音合成与流式语音识别服务。读完本文你将掌握TTS/STT 插件的安装与认证、全部核心参数的含义与默认值、基于 WebSocket 的低延迟流式合成用法、连接池与上下文管理原理以及一个可直接运行的 STT TTS 双通道语音 Agent 完整示例。插件定位与整体架构livekit-plugins-inworld是 LiveKit Agents 生态中的官方插件为实时语音 Agent 提供两大能力Inworld TTS文本转语音支持 HTTP 流式合成与 WebSocket 双向流式合成两种模式Inworld STT流式语音识别speech-to-text支持实时中间结果interim results与多种可替换的底层识别模型。从源码结构看插件主体位于 livekit/plugins/inworld 目录包含tts.pyTTS 实现与 WebSocket 连接池、stt.pySTT 实现与流式识别、_utils.py周期统计收集器与__init__.py公共 API 导出与插件注册。公共导出包括TTS、STT、ChunkedStream、SynthesizeStream、SpeechStream以及Encoding、TTSModels、TimestampType、TextNormalization、DeliveryMode等类型别名。安装与认证安装插件只需一行命令pip install livekit-plugins-inworld插件的包元数据定义在 pyproject.toml 中要求 Python 3.10依赖livekit-agents1.8.0。认证方式是在.env文件中设置 Inworld 平台颁发的 API KeyINWORLD_API_KEYyour_inworld_api_key源码层面的认证逻辑位于 tts.py 与 stt.py构造TTS或STT时若未显式传入api_key参数则从环境变量INWORLD_API_KEY读取两者均缺失时抛出ValueError。最终请求头中的认证信息为Basic {api_key}形式的 HTTP Basic 认证。因此你也可以在代码中显式传入from livekit.plugins import inworld tts inworld.TTS(api_keyyour_inworld_api_key)Inworld TTS参数详解与默认值通过AgentSession使用或作为独立的语音生成器from livekit.plugins import inworld tts inworld.TTS()带完整选项的构造方式如下from livekit.plugins import inworld tts inworld.TTS( voiceHades, # 音色 ID默认音色或自定义克隆音色 modelinworld-tts-1.5-max, # 或 inworld-tts-2 encodingOGG_OPUS, # LINEAR16, PCM, MP3, OGG_OPUS, FLAC sample_rate48000, # 采样率Hz bit_rate64000, # 比特率压缩格式生效 speaking_rate1.0, # 语速范围 0.5-1.5 temperature1.1, # 采样随机度范围 (0, 2] timestamp_typeWORD, # WORD, CHARACTER, TIMESTAMP_TYPE_UNSPECIFIED text_normalizationOFF, # ON, OFF, APPLY_TEXT_NORMALIZATION_UNSPECIFIED )核心参数速查表下表综合了 README 文档与 tts.py 源码 中的常量定义给出各参数的取值范围与实际默认值README 示例值可能与源码默认值不同实际运行以源码默认值为准参数说明取值范围源码默认值voice音色 ID平台音色或自定义克隆音色AshleymodelTTS 模型inworld-tts-2、inworld-tts-1.5-maxinworld-tts-1.5-maxencoding音频编码LINEAR16、PCM、MP3、OGG_OPUS、FLACPCMsample_rate采样率Hz8000-4800024000bit_rate比特率压缩格式整数64000speaking_rate语速0.5-1.51.0temperature采样随机度(0, 2]1.0language说话语言BCP-47 标签如en-US、fr-FR、ja-JP未设置使用模型默认timestamp_type时间戳粒度WORD、CHARACTER、TIMESTAMP_TYPE_UNSPECIFIED未设置text_normalization文本规范化ON、OFF、APPLY_TEXT_NORMALIZATION_UNSPECIFIED也接受布尔值未设置自动delivery_mode输出变化风格仅inworld-tts-2DELIVERY_MODE_UNSPECIFIED、STABLE、BALANCED、CREATIVE未设置服务端默认BALANCEDtimestamp_transport_strategy时间戳传输策略SYNC、ASYNCASYNCbuffer_char_threshold流式触发合成的字符数阈值整数120max_buffer_delay_ms流式最大缓冲时间ms整数3000关键参数的实现细节文本规范化text_normalizationON时数字、日期与缩写会被展开例如Dr.展开为DoctorOFF时按原文逐字朗读。源码的_resolve_text_normalizationtts.py还支持直接传布尔值——True映射为ONFalse映射为OFF。DeliveryMode 与 temperature 的取舍对inworld-tts-2模型Inworld API 会忽略temperature参数应改用delivery_mode控制输出变化程度。插件测试文件 test_plugin_inworld_tts.py 对该行为做了完整验证delivery_mode支持四个合法枚举值传入未知值如EXPRESSIVE会抛出ValueError同时测试确认了 WebSocketcreate报文与 HTTP 请求体在未设置delivery_mode时不会携带该字段服务端按默认处理设置后则携带在create.deliveryMode或请求体顶层deliveryMode。对齐字幕与时间戳设置timestamp_typeWORD或CHARACTER时TTS 能力声明中aligned_transcript会被置为True见 tts.py插件会解析服务端返回的 word/character 级时间戳并转换为TimedString可用于卡拉 OK 式字幕、逐词高亮与口型同步lipsync。timestamp_transport_strategySYNC让时间戳与音频数据同报文返回ASYNC则允许时间戳在音频之后以尾随报文到达。Markup 支持inworld-tts-2模型理解 LiveKit 的 markup 标签_provider_key返回inworld旧模型不会注入、转换或剥离这些标签tts.py。TTS 流式合成StreamingInworld TTS 通过 WebSocket 双向流式合成实现更低延迟的实时语音输出。使用stream()方法边生成文本边合成语音from livekit.plugins import inworld tts inworld.TTS( voiceHades, modelinworld-tts-1.5-max, buffer_char_threshold100, # 触发合成的缓冲字符数 max_buffer_delay_ms3000, # 最大缓冲时长ms ) # 创建实时合成流 stream tts.stream() # 增量推送文本 stream.push_text(Hello, ) stream.push_text(how are you today?) stream.flush() # 冲刷剩余缓冲文本 stream.end_input() # 标记输入结束 # 消费生成的音频帧 async for audio in stream: # 处理音频帧 pass从 SynthesizeStream 的实现 可以看出流式合成的内部流程输入的文本先进入SentenceTokenizer默认是livekit.agents.tokenize.blingfire.SentenceTokenizerretain_format默认为True按句子切分切分后的每个 token 再按1000 字符为一块发送给服务端Inworld 单次文本长度上限 1000 字符源码对此做了显式分块全部句子发送完毕后调用flush_context与close_context结束本次生成服务端返回的音频以 base64 解码后推入AudioEmitter当编码为PCM时每条音频块推送后立即flush。流式模式下buffer_char_threshold默认 120与max_buffer_delay_ms默认 3000共同决定攒多少字符/最多等多久才触发一次合成是延迟与体验之间最重要的两个旋钮。底层原理共享 WebSocket 连接池与上下文管理流式合成的高并发能力来自 tts.py 中实现的两层结构_InworldConnection单条连接维护一条到wss://api.inworld.ai/tts/v1/voice:streamBidirectional的双向 WebSocket最多承载5 个并发 contextMAX_CONTEXTS 5。每个 context 独立维护状态机CREATING → ACTIVE → CLOSING发送与接收分别由后台任务处理出站消息创建 context、发送文本、冲刷、关闭统一进入队列按序发送空闲超过阈值的 CLOSING context 会被定期清理任务回收每 60 秒巡检一次超过 120 秒强制释放。_ConnectionPool连接池管理多条连接默认最大20 条max_connections每条连接 5 个 context即理论并发上限约 100 个合成流。连接池按需创建新连接并在所有连接满载时等待容量释放可配置超时空闲连接超过idle_connection_timeout默认 300 秒即 5 分钟后自动关闭回收至少保留一条连接。此外TTS还提供了prewarm()方法用于提前建立连接池跳过首个请求的连接建立延迟list_voices()方法可以列出 API Key 对应工作区下的全部可用音色支持按 ISO 639-1 语言代码过滤如en、es、fr以及update_options()方法在运行期动态调整配置对新流生效。Inworld STT流式语音识别STT 同样支持在AgentSession中使用from livekit.agents import AgentSession from livekit.plugins import inworld session AgentSession( sttinworld.STT() # ... llm, tts 等 )指定模型并开启声纹voice profile检测from livekit.agents import AgentSession from livekit.plugins import inworld session AgentSession( sttinworld.STT( modelinworld/inworld-stt-1, enable_voice_profileTrue, ) # ... llm, tts 等 )STT 参数说明参考 stt.py 的构造函数与_build_transcribe_config方法核心参数如下参数说明默认值model识别模型 IDinworld/inworld-stt-1language语言代码en-USsample_rate音频采样率Hz16000num_channels音频声道数1enable_voice_profile声纹分析年龄、性别、情感、口音Truevoice_profile_top_n每个类别返回的 Top N 声纹结果1vad_thresholdVAD 灵敏度阈值未设置min_end_of_turn_silence_when_confident高置信度下的最小静音时长ms200end_of_turn_confidence_threshold话轮结束判定置信度阈值值越低越容易判定结束0.3几个值得注意的实现要点模型透传Inworld STT 平台同时托管多种识别模型如inworld/inworld-stt-1、assemblyai/universal-streaming-multilingual、soniox/stt-rt-v4等。插件对此不做任何校验任意模型字符串都会透传给服务端这样新模型上线无需升级插件即可使用。流式专用STT 能力声明为streamingTrue, interim_resultsTrue, offline_recognizeFalse即只支持流式识别不支持批量batch离线识别。若调用_recognize_impl批量接口会直接抛出NotImplementedError提示改用stream()。事件语义识别过程会产生START_OF_SPEECH、INTERIM_TRANSCRIPT、FINAL_TRANSCRIPT、END_OF_SPEECH等SpeechEvent声纹信息voice_profile会作为元数据挂载到转写结果上音频时长统计每 5 秒通过RECOGNITION_USAGE事件上报stt.py。动态更新update_options()支持运行期修改model、language、enable_voice_profile、VAD 阈值与话轮结束参数变更对之后新建的流生效stt.py。完整示例STT TTS 双通道语音 AgentREADME 提供了一段完整可运行的语音 Agent 示例同时使用 Inworld 承担识别与合成可直接保存为inworld_agent.py运行Inworld STT TTS voice agent example. Demonstrates using Inworld for both speech-to-text and text-to-speech in a LiveKit voice agent. Save this as inworld_agent.py and run: uv run inworld_agent.py console # local console mode uv run inworld_agent.py dev # LiveKit Cloud (requires LIVEKIT_URL, # LIVEKIT_API_KEY, LIVEKIT_API_SECRET) Then connect via https://agents-playground.livekit.io import logging from dotenv import load_dotenv from livekit.agents import ( Agent, AgentServer, AgentSession, JobContext, cli, inference, metrics, room_io, ) from livekit.agents.inference import TurnDetector from livekit.plugins import inworld logger logging.getLogger(inworld-agent) load_dotenv() class InworldAgent(Agent): def __init__(self) - None: super().__init__( instructions( Your name is Nova. You interact with users via voice. Keep your responses concise and to the point. Do not use emojis, asterisks, markdown, or other special characters. You are helpful, curious, and friendly. ), ) async def on_enter(self): self.session.generate_reply() server AgentServer() server.rtc_session() async def entrypoint(ctx: JobContext): ctx.log_context_fields {room: ctx.room.name} session AgentSession( sttinworld.STT(modelinworld/inworld-stt-1), llmopenai/gpt-4.1-mini, ttsinworld.TTS(voiceClive), turn_detectionTurnDetector(), vadinference.VAD(), ) usage_collector metrics.UsageCollector() session.on(metrics_collected) def _on_metrics(ev): metrics.log_metrics(ev.metrics) usage_collector.collect(ev.metrics) async def log_usage(): logger.info(fUsage: {usage_collector.get_summary()}) ctx.add_shutdown_callback(log_usage) await session.start( agentInworldAgent(), roomctx.room, room_optionsroom_io.RoomOptions(), ) if __name__ __main__: cli.run_app(server)这个示例演示了 LiveKit Agents 中完整语音链路的装配方式inworld.STT负责把用户语音转成文本LLM此处为openai/gpt-4.1-mini生成回复inworld.TTS把回复合成为语音TurnDetector()与inference.VAD()负责话轮检测与语音活动检测保证对话自然衔接metrics.UsageCollector配合metrics_collected事件收集每次会话的用量统计并在关闭时输出摘要。运行方式uv run inworld_agent.py console本地控制台模式无需 LiveKit 云服务即可体验uv run inworld_agent.py dev连接 LiveKit Cloud 开发环境需要配置LIVEKIT_URL、LIVEKIT_API_KEY、LIVEKIT_API_SECRET环境变量随后可通过 LiveKit Agents Playground 网页接入房间进行对话。组合使用TTS STT 双通道当同时需要 Inworld 承担识别与合成时只需在同一个AgentSession中同时传入两者from livekit.agents import AgentSession from livekit.plugins import inworld session AgentSession( ttsinworld.TTS(voiceHades), sttinworld.STT(), # ... llm 等 )此时整个语音 Agent 的听与说都由 Inworld 提供服务配合任意 LLM 即可快速搭建一套端到端的实时语音对话应用若某个环节已有其他供应商的插件也可以只替换其中一半例如仅使用inworld.STT识别、用其他 TTS 插件合成。小结livekit-plugins-inworld为 LiveKit Agents 提供了开箱即用的 Inworld 语音能力接入TTS 侧支持 HTTP 流式与 WebSocket 双向流式两种合成路径并内置共享连接池每连接 5 context、默认 20 连接、空闲 5 分钟回收来支撑高并发实时场景STT 侧提供流式识别、中间结果、话轮结束判定与声纹分析且模型字符串完全透传、可随平台能力平滑升级。结合本文的参数表与完整示例你可以快速在现有或全新的 LiveKit 语音 Agent 项目中接入 Inworld 的双通道语音能力。【免费下载链接】agentsA framework for building realtime voice AI agents ️项目地址: https://gitcode.com/GitHub_Trending/agen/agents创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考