18 KiB
Note
本文档由 WeHub 基于上游 README 翻译整理,属于社区翻译,非官方中文文档。
English · 原始项目 · 上游 README
原作者、版权与许可证归属以原始项目及本仓库 LICENSE 文件为准。
在找 JS/TS 库?请查看 AgentsJS
Agents 是什么?
Agent Framework 专为构建在服务器上运行的实时、可编程参与者而设计。使用它可以创建能够看、听和理解的对话式、多模态语音智能体(voice agents)。
功能特性
- 灵活的集成:全面的生态系统,可按需混搭合适的 STT、LLM、TTS 和 Realtime API。
- 集成的任务调度:内置任务调度与分发,配合 dispatch APIs 将终端用户连接到智能体。
- 丰富的 WebRTC 客户端:使用 LiveKit 的开源 SDK 生态系统构建客户端应用,支持所有主流平台。
- 电话集成:与 LiveKit 的 telephony stack, 无缝配合,使智能体能够拨打或接听电话。
- 与客户端交换数据:使用 RPCs 及其他 Data APIs 与客户端无缝交换数据。
- 语义化话轮检测(Semantic turn detection):使用 transformer 模型检测用户是否已完成当前话轮,有助于减少打断。
- MCP 支持:原生支持 MCP。一行代码即可集成 MCP 服务器提供的工具。
- 内置测试框架:编写测试并使用评判器(judges)确保智能体按预期运行。
- 开源:完全开源,允许你在自己的服务器上运行整个技术栈,包括使用最广泛的 WebRTC 媒体服务器之一 LiveKit server,。
安装
安装核心 Agents 库以及常用模型提供商的插件:
pip install "livekit-agents[openai,deepgram,cartesia]"
文档与指南
有关该框架及其使用方法的文档可在此 查阅。
使用 AI 编程智能体进行开发
如果你使用 AI 编程助手来基于 LiveKit Agents 进行开发,我们建议采用以下配置以获得最佳效果:
-
安装 LiveKit Docs MCP server** — 让你的编程智能体访问最新的 LiveKit 文档、跨 LiveKit 仓库的代码搜索以及可用的示例。
-
安装 LiveKit Agent Skill** — 为你的编程智能体提供构建语音 AI 应用的架构指导与最佳实践,包括工作流设计、交接(handoffs)、任务和测试模式。
npx skills add livekit/agent-skills --skill livekit-agents
Agent Skill 与 MCP 服务器配合使用效果最佳:Skill 教会你的智能体如何着手基于 LiveKit 进行开发,而 MCP 服务器提供最新的 API 细节以确保正确实现。
核心概念
- Agent:具有明确定义指令的基于 LLM 的应用。
- AgentSession:管理智能体与终端用户交互的容器。
- entrypoint:交互式会话的入口,类似于 Web 服务器中的请求处理器。
- AgentServer:协调任务调度并为用户会话启动智能体的主进程。
用法
简单语音智能体
from livekit.agents import (
Agent,
AgentServer,
AgentSession,
JobContext,
RunContext,
cli,
function_tool,
inference,
)
@function_tool
async def lookup_weather(
context: RunContext,
location: str,
):
"""Used to look up weather information."""
return {"weather": "sunny", "temperature": 70}
server = AgentServer()
@server.rtc_session()
async def entrypoint(ctx: JobContext):
session = AgentSession(
vad=inference.VAD(),
# any combination of STT, LLM, TTS, or realtime API can be used
# this example shows LiveKit Inference, a unified API to access different models via LiveKit Cloud
# to use model provider keys directly, replace with the following:
# from livekit.plugins import deepgram, openai, cartesia
# stt=deepgram.STT(model="nova-3"),
# llm=openai.LLM(model="gpt-4.1-mini"),
# tts=cartesia.TTS(model="sonic-3", voice="9626c31c-bec5-4cca-baa8-f8ba9e84c8bc"),
stt=inference.STT("deepgram/nova-3", language="multi"),
llm=inference.LLM("openai/gpt-4.1-mini"),
tts=inference.TTS("cartesia/sonic-3", voice="9626c31c-bec5-4cca-baa8-f8ba9e84c8bc"),
)
agent = Agent(
instructions="You are a friendly voice assistant built by LiveKit.",
tools=[lookup_weather],
)
await session.start(agent=agent, room=ctx.room)
await session.generate_reply(instructions="greet the user and ask about their day")
if __name__ == "__main__":
cli.run_app(server)
运行此示例需要以下环境变量:
- LIVEKIT_URL
- LIVEKIT_API_KEY
- LIVEKIT_API_SECRET
多智能体交接
此代码片段为节选。完整示例请参阅 multi_agent.py
...
class IntroAgent(Agent):
def __init__(self) -> None:
super().__init__(
instructions=f"You are a story teller. Your goal is to gather a few pieces of information from the user to make the story personalized and engaging."
"Ask the user for their name and where they are from"
)
async def on_enter(self):
self.session.generate_reply(instructions="greet the user and gather information")
@function_tool
async def information_gathered(
self,
context: RunContext,
name: str,
location: str,
):
"""Called when the user has provided the information needed to make the story personalized and engaging.
Args:
name: The name of the user
location: The location of the user
"""
context.userdata.name = name
context.userdata.location = location
story_agent = StoryAgent(name, location)
return story_agent, "Let's start the story!"
class StoryAgent(Agent):
def __init__(self, name: str, location: str) -> None:
super().__init__(
instructions=f"You are a storyteller. Use the user's information in order to make the story personalized."
f"The user's name is {name}, from {location}",
# override the default model, switching to Realtime API from standard LLMs
llm=openai.realtime.RealtimeModel(voice="echo"),
chat_ctx=chat_ctx,
)
async def on_enter(self):
self.session.generate_reply()
@server.rtc_session()
async def entrypoint(ctx: JobContext):
userdata = StoryData()
session = AgentSession[StoryData](
vad=inference.VAD(),
stt="deepgram/nova-3",
llm="openai/gpt-4.1-mini",
tts="cartesia/sonic-3:9626c31c-bec5-4cca-baa8-f8ba9e84c8bc",
userdata=userdata,
)
await session.start(
agent=IntroAgent(),
room=ctx.room,
)
...
测试
自动化测试对于构建可靠的 Agent 至关重要,尤其是在 LLM(大语言模型)具有非确定性行为的情况下。LiveKit Agents 内置了测试集成,可帮助你创建稳定可靠的 Agent。
@pytest.mark.asyncio
async def test_no_availability() -> None:
llm = google.LLM()
async with AgentSession(llm=llm) as sess:
await sess.start(MyAgent())
result = await sess.run(
user_input="Hello, I need to place an order."
)
result.expect.skip_next_event_if(type="message", role="assistant")
result.expect.next_event().is_function_call(name="start_order")
result.expect.next_event().is_function_call_output()
await (
result.expect.next_event()
.is_message(role="assistant")
.judge(llm, intent="assistant should be asking the user what they would like")
)
示例
更多示例和详细设置说明,请参阅 examples 目录。如需更多示例,请参阅 python-agents-examples 仓库。
🎙️ Starter Agent针对语音对话优化的入门 Agent。 |
🔄 Multi-user push to talk通过按键通话(push-to-talk)响应房间内多位用户。 |
🎵 Background audio背景环境音和思考音效,提升真实感。 |
🛠️ Dynamic tool creation动态创建函数工具。 |
☎️ Outbound caller进行外呼电话的 Agent |
📋 Structured output使用 LLM 的结构化输出来指导 TTS 语调。 |
🔌 MCP support使用 MCP 服务器提供的工具 |
💬 Text-only agent完全跳过语音,使用相同代码进行纯文本集成 |
📝 Multi-user transcriber为房间内所有用户生成转录文本 |
🎥 Video avatars使用 Tavus、Bithuman、LemonSlice 等添加 AI 虚拟形象 |
🍽️ Restaurant ordering and reservations处理餐厅来电的完整 Agent 示例。 |
👁️ Gemini Live vision具备视觉能力的 Gemini Live Agent 完整示例(含 iOS 应用)。 |
运行你的 Agent
在终端中测试
python myagent.py console
在终端模式下运行 Agent,启用本地音频输入和输出以便测试。 此模式无需外部服务器或依赖,适合快速验证行为。
使用 LiveKit 客户端进行开发
python myagent.py dev
启动 Agent 服务器,并在文件变更时启用热重载。此模式允许每个进程高效托管多个并发 Agent。
Agent 会连接到 LiveKit Cloud 或你自托管的服务器。请设置以下环境变量:
- LIVEKIT_URL
- LIVEKIT_API_KEY
- LIVEKIT_API_SECRET
你可以使用任意 LiveKit 客户端 SDK 或电话集成进行连接。 要快速上手,请试用 Agents Playground.
生产环境运行
python myagent.py start
以面向生产环境的优化配置运行 Agent。
许可证
Agents 框架采用 Apache-2.0 许可证。LiveKit 话轮检测(turn detection)模型采用 LiveKit Model License 许可证。
贡献
Agents 框架正处于快速发展领域中的积极开发阶段。我们欢迎并感谢各类贡献,无论是反馈、错误修复、功能、新插件和工具,还是更完善的文档。你可以在本仓库提交 issue、发起 PR,或在 LiveKit 社区.
开发环境设置
本项目使用 uv 进行包管理。要安装开发依赖:
uv sync --all-extras --dev
示例
本项目在 examples 目录中包含许多示例。要运行它们,请创建文件 examples/.env,并填入 LiveKit Server 及所需模型提供商的凭据(参见 examples/.env.example),然后运行:
uv run examples/voice_agents/basic_agent.py dev
更多信息请参阅 examples README。
测试
单元测试位于 tests 目录,可通过以下命令运行:
uv run pytest --unit
各插件的集成测试需要多种 API 凭据,并在项目维护者提交的 PR 中于 GitHub CI 自动运行。详情请参阅 tests workflow。
格式化
本项目使用 ruff 进行格式化和 lint:
uv run ruff format
uv run ruff check --fix
文档
要使用 pdoc: 在本地生成文档:
uv sync --all-extras --group docs
uv run --active pdoc --skip-errors --html --output-dir=docs livekit
| LiveKit 生态系统 | |
|---|---|
| Agents SDK | Python · Node.js |
| LiveKit SDK | Browser · Swift · Android · Flutter · React Native · Rust · Node.js · Python · Unity · Unity (WebGL) · ESP32 · C++ |
| 入门应用 | Python Agent · TypeScript Agent · React App · SwiftUI App · Android App · Flutter App · React Native App · Web Embed |
| UI 组件 | React · Android Compose · SwiftUI · Flutter |
| 服务器 API | Node.js · Golang · Ruby · Java/Kotlin · Python · Rust · PHP (community) · .NET (community) |
| 资源 | Docs · Docs MCP Server · CLI · LiveKit Cloud |
| LiveKit Server OSS | LiveKit server · Egress · Ingress · SIP |
| 社区 | Developer Community · Slack · X · YouTube |