OpenRouter 集成与实践

OpenRouter 集成与实践

LiveKit

2 分钟阅读

LiveKit

将 OpenRouter 与 LiveKit Agents 配合使用

使用 LiveKit Agents

LiveKit Agents 是用于构建语音 AI 智能体的开源框架。OpenRouter 插件让你可以通过统一 API 访问来自多家提供商的 400 多个 AI 模型,并支持自动回退与智能路由。

安装

安装 OpenAI 插件以添加 OpenRouter 支持:

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

认证

OpenRouter 插件需要 OpenRouter API 密钥。在 .env 文件中设置 OPENROUTER_API_KEY

基本用法

使用 with_openrouter 方法创建 OpenRouter LLM:

from livekit.plugins import openai

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

高级功能

回退模型

配置多个回退模型,以便在首选模型不可用时使用:

from livekit.plugins import openai

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

提供商路由

控制模型推理使用哪些提供商:

from livekit.plugins import openai

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

网络搜索插件

启用 OpenRouter 的网络搜索能力:

from livekit.plugins import openai

llm = openai.LLM.with_openrouter(
    model="google/gemini-3-flash-preview",
    plugins=[
        openai.OpenRouterWebPlugin(
            max_results=5,
            search_prompt="搜索相关信息",
        )
    ],
)

分析集成

包含站点和应用信息,供 OpenRouter 分析使用:

from livekit.plugins import openai

llm = openai.LLM.with_openrouter(
    model="openrouter/auto",
    site_url="https://myapp.com",
    app_name="我的语音智能体",
)

资源