Skip to content

LiveKit Agents 是开源实时语音 AI Agent 框架,通过 openai.LLM.with_openrouter() 方法即可接入 OpenRouter,获得 300+ 模型的访问能力。除基本模型切换外,还支持配置备用模型列表(fallback_models)、Provider 路由优先级、Web 搜索插件(OpenRouterWebPlugin),以及通过 site_url 和 app_name 参数上报站点信息用于 OpenRouter 统计。只需安装 livekit-agents[openai] 插件并设置 OPENROUTER_API_KEY 环境变量即可开始。

LiveKit Agents 是构建实时语音 AI Agent 的开源框架。通过其 OpenAI 插件,可以接入 OpenRouter 访问 300+ AI 模型,并利用 OpenRouter 的智能路由和自动 fallback 能力。

安装

使用 uv(LiveKit 推荐的包管理工具)安装 OpenAI 插件:

bash
uv add "livekit-agents[openai]~=1.2"

认证

.env 文件中设置:

bash
OPENROUTER_API_KEY=sk-or-...

基本用法

通过 openai.LLM.with_openrouter() 方法创建 LLM,传入 OpenRouter 的模型 ID:

python
from livekit.plugins import openai

session = AgentSession(
    llm=openai.LLM.with_openrouter(model="anthropic/claude-sonnet-4.5"),
    # ... tts, stt, vad, turn_detection 等其他配置
)

高级功能

备用模型

当主模型不可用时,自动尝试备用模型列表:

python
from livekit.plugins import openai

llm = openai.LLM.with_openrouter(
    model="openai/gpt-4o",
    fallback_models=[
        "anthropic/claude-sonnet-4",
        "openai/gpt-5-mini",
    ],
)

Provider 路由

精确控制使用哪些 Provider,以及路由优先策略:

python
llm = openai.LLM.with_openrouter(
    model="deepseek/deepseek-chat-v3.1",
    provider={
        "order": ["novita/fp8", "gmicloud/fp8", "google-vertex"],
        "allow_fallbacks": True,
        "sort": "latency",  # 按延迟排序
    },
)

sort 支持 "latency"(延迟)、"throughput"(吞吐)、"price"(价格)。

Web 搜索插件

为模型开启实时网页搜索能力(需模型支持):

python
llm = openai.LLM.with_openrouter(
    model="google/gemini-3-flash-preview",
    plugins=[
        openai.OpenRouterWebPlugin(
            max_results=5,
            search_prompt="Search for relevant information",
        )
    ],
)

站点分析上报

传入 site_urlapp_name 参数,用于 OpenRouter 使用统计和排名:

python
llm = openai.LLM.with_openrouter(
    model="openrouter/auto",
    site_url="https://myapp.com",
    app_name="My Voice Agent",
)

支持的模型

可以使用任意 OpenRouter 模型列表 中的模型,格式为 provider/model-name,例如 anthropic/claude-sonnet-4.5openai/gpt-4ogoogle/gemini-flash-1.5 等。

常见问题

Q: LiveKit Agents 的 with_openrouter() 和直接用 with_openai() 有什么区别?

A: with_openrouter() 会自动配置 OpenRouter 的 base URL,并支持 OpenRouter 专有参数(如 fallback_modelsprovider 路由、plugins)。用 with_openai() + 手动 base URL 也能调用 OpenRouter,但缺少这些专有功能的类型安全封装。

Q: openrouter/auto 模型是什么?

A: 这是 OpenRouter 的自动路由模型——OpenRouter 根据请求内容、当前各模型的可用性和性能,自动选择最合适的模型来处理请求,适合对模型选择没有强偏好的场景。

Q: 如何调试 Provider 路由是否生效?

A: 在 OpenRouter 控制台的 Activity 页面可以看到每次请求实际使用了哪个 Provider,以及是否触发了 fallback。