智能 LLM 推理路由与成本优化
简介
开源 MIT 项目,通过硬件感知分类器智能路由 LLM 请求至最具成本效益的模型,显著降低 API 成本并优化推理性能。
原始描述
Configure, run, and troubleshoot the OpenRouter hardware-aware classifier router (wizard setup, local model, routing, and dashboard).
通过你的 Agent 添加
安装目录:clawhub-skill-2/(目录名取自 SKILL.md 的 frontmatter name,不是 URL 里的 slug)。
点「快速安装」复制一段指令贴给你的 Agent:它会先下载到 /tmp、把文件清单和校验值给你看,你确认之后才解压安装。不会一步装完、也不改系统其它位置。
或者手动安装
包是「根级 SKILL.md + 作者附带的文件」,解压到上面的 <slug>/ 目录即可;
目录名不用换,也不要把包直接解压到 skills 根目录。
技能申请的权限由作者决定:装之前先看清单里有没有脚本、它会读写什么。
中文使用说明 来自收录源
Xrouter 综合评估
核心用法
Xrouter 是一款 MIT 许可的开源推理路由器,定位为 OpenClaw 与 LLM 提供商之间的智能中间层。其核心工作流程为:接收 OpenAI 兼容格式的请求 → 通过硬件感知的三级分类器(0=廉价/1=中等/2=前沿)评估任务复杂度 → 自动路由至最具成本效益的模型处理 → 返回流式响应。支持纯本地、纯云端或混合部署模式,并内置 Redis/LRU 缓存层、令牌追踪仪表盘和多提供商适配器。
典型部署路径:
- 运行
npm run check-hw检测硬件并推荐本地引擎(TensorRT-LLM/vLLM/MLX/llama.cpp) - 执行
npm run configure启动交互式配置向导,选择本地分类器模型及 cheap/medium/frontier 三级路由的提供商 - 启动路由器
npm run dev,将 OpenAI 兼容请求发送至localhost:3000/v1/chat/completions - 通过响应头
X-Xrouter-decision和仪表盘监控路由决策与成本分布
显著优点
- 成本优化精准:三级分类策略可将简单请求路由至本地小模型,复杂请求才调用 GPT-4/Claude 级前沿模型,理论成本可降低 60-90%
- 硬件感知智能:自动检测 NVIDIA GPU、Apple Silicon 或 CPU 环境,推荐最优本地推理引擎
- 零侵入集成:完全兼容 OpenAI API 格式,现有客户端仅需修改 base_url 即可接入
- 多生态支持:原生支持 Ollama、vLLM、TensorRT-LLM、llama.cpp 本地引擎,以及 OpenAI、Anthropic、Gemini、Azure、Groq 等十余家云服务商
- 透明可观测:每请求返回路由决策头信息,仪表盘实时展示三级模型的令牌消耗占比
- 容错设计:分类器故障自动降级至 frontier 路由,模型加载期智能重试
潜在缺点与局限性
- 延迟权衡:首次请求需等待分类器推理(虽支持流式截断优化),本地模型冷启动可达数秒
- 分类准确率依赖:任务复杂度判断基于本地小模型,对边缘案例(如需创意但看似简单的提示)可能误判导致性能损失
- 运维复杂度:混合部署需同时维护本地模型服务和云 API 密钥,监控维度较单一云方案翻倍
- 功能限制:非 OpenAI 适配器仅支持文本消息和基础采样参数,多模态、工具调用等高级特性受限
- 生态依赖:分类器效果受限于所选本地模型质量,需手动调优 system prompt
适合人群
用户类型
适用场景
成本敏感型企业
高频调用场景(客服、内容审核)需显著降低 API 账单
隐私优先团队
简单请求必须本地处理,仅复杂查询上云
多模型管理开发者
希望统一接口调度本地+云端异构模型资源
边缘 AI 研究者
探索分级推理架构的实验性部署
常规风险
- 本地模型安全风险:若暴露 11434/8000/8080 等本地服务端口至公网,可能遭遇未授权访问
- API 密钥管理:配置文件中若误提交真实密钥至版本控制,存在泄露风险
- 分类器漂移:业务场景变化后需重新校准分类阈值,否则可能出现系统性路由错误
- 供应商锁定缓解:虽支持多提供商,但深度功能(如 Claude 的特定参数)可能仍依赖原生 API
- 依赖维护:Node.js 20+ 要求及上游推理引擎(vLLM/Ollama)更新需持续跟进
- 延迟权衡:首次请求需等待分类器推理(虽支持流式截断优化),本地模型冷启动可达数秒
- 分类准确率依赖:任务复杂度判断基于本地小模型,对边缘案例(如需创意但看似简单的提示)可能误判导致性能损失
- 运维复杂度:混合部署需同时维护本地模型服务和云 API 密钥,监控维度较单一云方案翻倍
- 功能限制:非 OpenAI 适配器仅支持文本消息和基础采样参数,多模态、工具调用等高级特性受限
- 生态依赖:分类器效果受限于所选本地模型质量,需手动调优 system prompt
适合人群
用户类型
适用场景
成本敏感型企业
高频调用场景(客服、内容审核)需显著降低 API 账单
隐私优先团队
简单请求必须本地处理,仅复杂查询上云
多模型管理开发者
希望统一接口调度本地+云端异构模型资源
边缘 AI 研究者
探索分级推理架构的实验性部署
常规风险
- 本地模型安全风险:若暴露 11434/8000/8080 等本地服务端口至公网,可能遭遇未授权访问
- API 密钥管理:配置文件中若误提交真实密钥至版本控制,存在泄露风险
- 分类器漂移:业务场景变化后需重新校准分类阈值,否则可能出现系统性路由错误
- 供应商锁定缓解:虽支持多提供商,但深度功能(如 Claude 的特定参数)可能仍依赖原生 API
- 依赖维护:Node.js 20+ 要求及上游推理引擎(vLLM/Ollama)更新需持续跟进
| 用户类型 | 适用场景 |
|---|---|
| 成本敏感型企业 | 高频调用场景(客服、内容审核)需显著降低 API 账单 |
| 隐私优先团队 | 简单请求必须本地处理,仅复杂查询上云 |
| 多模型管理开发者 | 希望统一接口调度本地+云端异构模型资源 |
| 边缘 AI 研究者 | 探索分级推理架构的实验性部署 |
- 本地模型安全风险:若暴露 11434/8000/8080 等本地服务端口至公网,可能遭遇未授权访问
- API 密钥管理:配置文件中若误提交真实密钥至版本控制,存在泄露风险
- 分类器漂移:业务场景变化后需重新校准分类阈值,否则可能出现系统性路由错误
- 供应商锁定缓解:虽支持多提供商,但深度功能(如 Claude 的特定参数)可能仍依赖原生 API
- 依赖维护:Node.js 20+ 要求及上游推理引擎(vLLM/Ollama)更新需持续跟进
技能正文
Xrouter
Xrouter is an open-source inference router that sits between OpenClaw and your LLM providers. It uses a fast, hardware-aware classifier to route each request to the most cost-effective model that can handle the task.
This project is MIT licensed. See the MIT License.
Core Features
- OpenAI-compatible reverse proxy at
POST /v1/chat/completions. - 3-tier classifier (0 = cheap, 1 = medium, 2 = frontier) with early stream cutoff.
- Hardware detection helper to recommend local engine.
- Provider selection wizard to choose local and cloud endpoints.
- Cache layer with Redis or in-memory LRU fallback.
- Full cloud mode when local inference is not viable.
- Token tracking dashboard at
/dashboard.
Workflow
flowchart TD
A["Client / OpenClaw request"] --> B["Router (OpenAI-compatible)"]
B --> C{"Classifier enabled?"}
C -->|No| F["Route to Frontier provider"]
C -->|Yes| D["Classifier (0 / 1 / 2)"]
D --> E{"Decision"}
E -->|0| G["Route to Cheap provider"]
E -->|1| M["Route to Medium provider"]
E -->|2| F
G --> H["Provider adapter (auto or explicit)"]
M --> H
F --> H
H --> I["Upstream API call"]
I --> J["Stream/Response back to client"]
Repository Layout
src/server.js: router and streaming proxy.src/classifier.js: classifier call and retry logic.src/config.js: configuration and env parsing.src/cache.js: Redis + LRU cache.src/token_tracker.js: token tracking.scripts/check_hw.js: hardware detection.scripts/configure_providers.js: interactive provider setup.
Requirements
- Node.js 20+.
- Local classifier engine (optional).
- A frontier provider endpoint (required).
Quickstart
- Install dependencies.
- (Optional) Start a local model server.
- Run the configuration wizard.
- Start the router.
npm install
npm run configure
npm run dev
How To Use
- Start your local model server (optional but recommended).
- Run the wizard to configure providers and models.
- Start the router.
- Send OpenAI-compatible requests to the router.
- Inspect routing decisions in response headers or the dashboard.
Example local setup (Ollama):
ollama pull llama3.1
ollama run llama3.1
Run the wizard:
npm run configure
Start the router:
npm run dev
Test a request:
curl -i http://localhost:3000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model":"any","messages":[{"role":"user","content":"Fix this sentence: I has a apple."}]}'
Look for these headers:
X-Xrouter-decision:0,1, or2.X-Xrouter-upstream:cheap,medium, orfrontier.
Open the dashboard:
http://localhost:3000/dashboard
Raw usage JSON:
http://localhost:3000/usage
Provider Selection (Terminal Wizard) Run:
npm run configure
The wizard:
- Scans hardware and recommends a local engine.
- Suggests a local classifier model.
- Lets you choose provider base URLs, API keys, and model overrides for cheap/medium/frontier routes.
- Writes
upstreams.jsonand optionally updates.env.
Quick Start Mode
- If your machine can run a local model, you can choose Quick Start.
- Quick Start auto-configures the local classifier.
- Cheap route always uses the same local model as the classifier to avoid Ollama model swapping.
- You only need to choose medium and frontier providers/models.
- On Apple Silicon (Ollama), the wizard lists installed Ollama models and can auto-download a recommended model.
Routing Behavior
- The classifier is called for each uncached request.
- The first
0,1, or2token returned decides the route. - If classification fails, the router defaults to the frontier route.
- When the classifier is enabled, cheap, medium, and frontier routes must be configured.
Compatibility
- The router accepts OpenAI-style requests and translates when needed.
- Provider type can be explicit (
xrouter,openai_compatible,openai,anthropic,gemini,cohere,azure_openai,mistral,groq,together,perplexity) orauto. autoinfers the provider adapter from the base URL or API key.- Providers that expose OpenAI-compatible endpoints use the
openai_compatibleadapter. - Anthropic/Gemini/Cohere streaming is translated into OpenAI-style SSE chunks.
- Non-OpenAI adapters currently support text-only messages and basic sampling params (temperature/top_p/stop).
Token Tracking Dashboard
GET /usage: returns cumulative token usage forcheap,medium, andfrontier.GET /dashboard: UI that displays token split and totals.- Local usage is counted inside
cheapwhen cheap uses the local model.
Environment Summary
HOST: bind host, default0.0.0.0.PORT: bind port, default3000.ROUTER_API_KEY: requireAuthorization: Bearer <key>.LOG_LEVEL: log level (debug/info/warn/error).LOG_TO_FILE: settrueto write logs to files.LOG_DIR: directory for log files (default./logs).CLASSIFIER_ENABLED: setfalseto disable local classification.CLASSIFIER_BASE_URL: OpenAI-compatible classifier endpoint.CLASSIFIER_MODEL: classifier model name.CLASSIFIER_SYSTEM_PROMPT: classifier prompt (single line).CLASSIFIER_TIMEOUT_MS: classifier timeout.CLASSIFIER_FORCE_STREAM: force streaming classifier request.CLASSIFIER_WARMUP: warm the classifier on server start.CLASSIFIER_WARMUP_DELAY_MS: delay before warmup request (ms).CLASSIFIER_KEEP_ALIVE_MS: keep-alive interval for classifier warmup (ms).CLASSIFIER_LOADING_RETRY_MS: delay between retries when the model is loading.CLASSIFIER_LOADING_MAX_RETRIES: max retries when the model is loading.CHEAP_BASE_URL: optional, defaults to classifier base URL.CHEAP_API_KEY: cheap provider API key.CHEAP_MODEL: optional model override for cheap route.CHEAP_PROVIDER: provider type for cheap route (autoif empty).CHEAP_HEADERS: optional JSON headers for cheap provider (stringified object).CHEAP_DEPLOYMENT: Azure deployment override for cheap route.CHEAP_API_VERSION: Azure API version override for cheap route.MEDIUM_BASE_URL: required when classifier is enabled.MEDIUM_API_KEY: medium provider API key.MEDIUM_MODEL: optional model override for medium route.MEDIUM_PROVIDER: provider type for medium route (autoif empty).MEDIUM_HEADERS: optional JSON headers for medium provider (stringified object).MEDIUM_DEPLOYMENT: Azure deployment override for medium route.MEDIUM_API_VERSION: Azure API version override for medium route.FRONTIER_BASE_URL: OpenAI-compatible frontier endpoint.FRONTIER_API_KEY: frontier API key.FRONTIER_MODEL: optional model override for frontier route.FRONTIER_PROVIDER: provider type for frontier route (autoif empty).FRONTIER_HEADERS: optional JSON headers for frontier provider (stringified object).FRONTIER_DEPLOYMENT: Azure deployment override for frontier route.FRONTIER_API_VERSION: Azure API version override for frontier route.REDIS_URL: if set, enables Redis cache.
Local Model Installation & Run Guides Ollama (best for Mac, easiest cross-platform)
- Install: Ollama Quickstart
- Pull a model:
ollama pull llama3.1 - Run:
ollama run llama3.1 - Base URL:
http://localhost:11434 - Router config:
CLASSIFIER_BASE_URL=http://localhost:11434CLASSIFIER_MODEL=llama3.1
vLLM (NVIDIA GPU)
- OpenAI server: vLLM OpenAI Server
- Example:
vllm serve NousResearch/Meta-Llama-3-8B-Instruct --dtype auto --api-key token-abc123 - Base URL:
http://localhost:8000 - Router config:
CLASSIFIER_BASE_URL=http://localhost:8000CLASSIFIER_MODEL=NousResearch/Meta-Llama-3-8B-Instruct
TensorRT-LLM (NVIDIA, max speed)
- Repo: TensorRT-LLM
- Server: trtllm-serve
- Base URL:
http://<host>:<port> - Router config:
CLASSIFIER_BASE_URL=http://<host>:<port>CLASSIFIER_MODEL=<your model>
llama.cpp (CPU/AMD fallback)
- Repo: llama.cpp
- Example:
llama-server -m model.gguf --port 8080 - Base URL:
http://localhost:8080 - Router config:
CLASSIFIER_BASE_URL=http://localhost:8080CLASSIFIER_MODEL=<gguf model name>
Docker Build and run the router with Redis:
docker compose -f deploy/docker-compose.yml up --build
Hardware Detection Run:
npm run check-hw
This prints the recommended engine:
tensorrt-llmfor large NVIDIA GPUs.vllmfor standard NVIDIA GPUs.mlxfor Apple Silicon.llama.cppfor CPU/AMD fallback.
Model List Fetching
- The wizard queries provider model list endpoints when possible.
- OpenAI-compatible:
/v1/models - Anthropic:
/v1/models - Gemini:
/v1beta/models - Cohere:
/v1/models - If listing fails, the wizard falls back to
scripts/cloud_model_catalog.json.
Star History
正文来自原始发布页, 版权归作者所有,许可未标注。 权利人认为有不妥,可申请下架。