@baiibayu/srouter

中文文档
0.1.70发布于 2026/11/06MITES Module构建来源已验证近 30 天下载 2276

SRouter — free open-source LLM router: run the gateway, set up coding agents, manage provider keys

原始使用文档
文档目录26 节
  1. The Ultimate Free AI Gateway & Smart LLM Router
  2. 🤔 Why SRouter?
  3. 🔄 How It Works
  4. ⚡ Quick Start
  5. 1. Run the Gateway via NPM / NPX
  6. 2. Upgrading
  7. 3. Docker & GHCR Alternative
  8. 🤖 Compatible Coding Agents & CLIs
  9. Setup Commands Reference
  10. Zero-Persistence Launchers
  11. Diagnostics & Health Check ( srouter doctor )
  12. CLI Generator Flags
  13. 🔑 Provider Keys Management
  14. 🔌 Supported Providers
  15. Provider Tiers
  16. 🌐 Unified API Endpoints
  17. 🛠️ MCP Server Setup
  18. Claude Desktop Configuration
  19. Cursor / Cline Configuration
  20. 🔒 Safety, Security & Local Privacy
  21. ⚠️ Troubleshooting & FAQ
  22. Port 20268 is already in use
  23. Rate limit hit (429 Too Many Requests)
  24. Where is my data stored?
  25. ❤️ Support the Developer
  26. 📄 License & Disclaimer

🚀 SRouter

The Ultimate Free AI Gateway & Smart LLM Router

Never hit rate limits again. Save tokens with prompt compression + auto-fallback to ~60 free AI providers and ~1,200+ models.

Connect all AI coding tools (Claude Code, Cursor, Windsurf, Cline, Codex, Copilot, Aider, OpenCode...) behind a single unified OpenAI-compatible endpoint.

npm version License: MIT Node.js Docker Ready GHCR Desktop App PRs Welcome Sponsor

⚡ Quick Start • 🤖 Coding Agents • 🔑 Keys CLI • 🔌 Providers • 🌐 API Endpoints • 🛠️ MCP Setup • 🤔 Why SRouter? • 🔄 How It Works • ❤️ Support

Self-host with Docker Download for Windows Download for macOS (Apple Silicon) Download for macOS (Intel) Download for Linux

SRouter dashboard — live routing, monthly token budget, and usage stats

Your router auto-syncs its model catalog twice daily from a signed feed: new models, quota updates, and provider quirk fixes arrive automatically without needing a manual update.


🤔 Why SRouter?

Coding with AI agents (Claude Code, Cursor, Windsurf, Cline) is transformative, but developers constantly run into walls:

❌ The Headaches✅ The SRouter Solution
Quota Waste & Expirations: Monthly paid API allowances sit unused or expire at month-end.Maximize Every Token: Intelligently drains active quotas first, then rotates across other providers.
Sudden Rate Limits (429): One heavy prompt or repeated tool call halts your workflow mid-coding.Smart 3-Tier Auto-Fallback: Instant, seamless failover (Subscription → Budget → 100% Free Keyless) with zero downtime.
Token Burning on Tool Outputs: Long git diff, grep, test logs, and JSON outputs consume massive context windows.Prompt Compression & Token Saver: Built-in heuristics and structure-aware filters compress noisy tool results, typically saving 20–40% tokens.
SDK & API Fragmentation: Juggling 50+ incompatible SDKs, auth formats, and endpoint URLs.One Universal /v1 Gateway: A single OpenAI-compatible base URL (http://localhost:20268/v1) that also natively handles Anthropic Messages (/v1/messages), Codex (/v1/responses), Gemini (/v1beta), and Ollama emulation.
Unpredictable Free Tiers: Providers add, change, or deprecate free models every week.Self-Updating Catalog: Pinned Ed25519 signed catalog auto-updates ~1,200+ models twice daily into your local SQLite DB.
Privacy & Security Risks: Sending API keys to cloud proxy providers exposes your credentials.100% Local & Encrypted: Keys are stored locally using AES-256-GCM encryption; traffic proxies directly from your machine to upstream providers.

SRouter comparison vs OpenRouter, LiteLLM, and Portkey — one router, your keys, zero markup


🔄 How It Works

┌─────────────────────────────────────────────────────────────────────────────┐
│                       Your Coding Agents & IDEs                             │
│       (Claude Code, Cursor, Windsurf, Cline, Roo Code, Codex, Aider)        │
└──────────────────────────────────────┬──────────────────────────────────────┘
                                       │ http://localhost:20268/v1
                                       ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│                         SRouter Smart AI Gateway                            │
│  • Complexity Gate (System One: routes simple prompts fast, complex deep)  │
│  • Prompt Compressor & Token Saver (compacts tool results, trims context)  │
│  • Protocol Translation (OpenAI ↔ Anthropic Messages ↔ Gemini ↔ Ollama)     │
│  • Per-Key Rate Tracking (RPM / RPD / TPM / TPD tracking with auto-reset)   │
│  • Local AES-256-GCM Key Vault & SQLite Persistence                        │
└──────────────────────────────────────┬──────────────────────────────────────┘
                                       │
        ┌──────────────────────────────┼──────────────────────────────┐
        ▼                              ▼                              ▼
 ┌──────────────────────────┐   ┌──────────────────────────┐   ┌──────────────────────────┐
 │  Tier 1: Sub / Fast Key  │   │  Tier 2: Generous Quota  │   │ Tier 3: 100% Free / Anon │
 │  • Google Gemini 2.5     │   │  • Mistral / Codestral   │   │  • Kilo Gateway (No Key) │
 │  • Groq (Llama 3.3 70B)  │──►│  • Zhipu GLM-4 / CogView │──►│  • OpenCode Free (No Key)│
 │  • Pollinations (Free)   │   │  • Cloudflare Workers AI │   │  • OVH Endpoints (No Key)│
 │  • OpenRouter / DeepSeek │   │  • Cohere / NVIDIA NIM   │   │  • LLM7 / AI Horde       │
 └──────────────────────────┘   └──────────────────────────┘   └──────────────────────────┘

When a request arrives, SRouter evaluates model health, current RPM/RPD limits, and prompt complexity. If an upstream provider returns 429 Too Many Requests or 5xx Server Error, the key enters a temporary cooldown, and SRouter instantly retries the next best model in your fallback chain.

How SRouter routes one request through a live-scored fallback chain


⚡ Quick Start

1. Run the Gateway via NPM / NPX

Run SRouter anywhere Node 20+ is installed without cloning the repository:

# Install globally
npm install -g @baiibayu/srouter

# Launch the gateway & open the Web Dashboard (default port 20268)
srouter

# Or run headless with custom port
srouter serve --port 3000 --no-browser

# Or run directly without installing using npx
npx @baiibayu/srouter

The Web Dashboard opens automatically at http://localhost:20268. Data is safely stored in ~/.srouter.

2. Upgrading

Upgrades are seamless — your SQLite database and configuration survive updates:

# Check if a newer version exists
srouter update --check

# Upgrade to latest
srouter update
# or
npm install -g @baiibayu/srouter@latest

3. Docker & GHCR Alternative

# Run instantly from GitHub Container Registry
docker run -d --name srouter -p 20268:20268 -v srouter-data:/app/server/data ghcr.io/baiibayu/srouter:latest

🤖 Compatible Coding Agents & CLIs

SRouter includes automated configuration generators (setup-*) that inspect your live model catalog, take timestamped backups of existing settings, and write the exact configuration your tool expects:

Claude Code
Claude Code
Cursor
Cursor
Codex CLI
Codex CLI
Cline
Cline
Continue
Continue
Aider
Aider
OpenCode
OpenCode
Gemini CLI
Gemini CLI
Roo Code
Roo Code
Kilo Code
Kilo Code
Zed
Zed
JetBrains
JetBrains
Goose
Goose
Qwen Code
Qwen Code
Crush
Crush
Factory Droid
Factory Droid
OpenClaw
OpenClaw
DeepSeek Harness
DeepSeek Harness
Oh My Pi
Oh My Pi
Hermes
Hermes
Pi
Pi
AtomCode
AtomCode
Reasonix
Reasonix
OpenClaude
OpenClaude

Setup Commands Reference

Configure any agent with one command:

# Point Claude Code to SRouter
srouter setup-claude --url http://localhost:20268 --api-key <your-unified-key>

# Or run via npx without global install
npx @baiibayu/srouter setup-cursor --url http://localhost:20268 --api-key <your-unified-key>
ToolSetup CommandTarget Base URLProtocol
Claude Codesrouter setup-claudehttp://localhost:20268Native Anthropic /v1/messages
Cursorsrouter setup-cursorhttp://localhost:20268/v1OpenAI Chat Completions
Codex CLIsrouter setup-codexhttp://localhost:20268/v1Native /v1/responses
Clinesrouter setup-clinehttp://localhost:20268/v1OpenAI / Anthropic format
Continuesrouter setup-continuehttp://localhost:20268/v1Chat + Ghost-text completions
Aidersrouter setup-aiderhttp://localhost:20268/v1OpenAI Chat Completions
OpenCodesrouter setup-opencodehttp://localhost:20268/v1OpenAI Chat Completions
Goosesrouter setup-goosehttp://localhost:20268/v1OpenAI Chat Completions
Qwen Codesrouter setup-qwenhttp://localhost:20268/v1OpenAI or Gemini format
Roo Codesrouter setup-roohttp://localhost:20268/v1OpenAI Chat Completions
Kilo Codesrouter setup-kilohttp://localhost:20268/v1OpenAI Chat Completions
Crushsrouter setup-crushhttp://localhost:20268/v1OpenAI Chat Completions
DeepSeek Harnesssrouter setup-dshhttp://localhost:20268/v1OpenAI Chat Completions
MiMo Codesrouter setup-mimohttp://localhost:20268/v1OpenAI Chat Completions
Oh My Pisrouter setup-omphttp://localhost:20268/v1OpenAI Chat Completions
OpenClawsrouter setup-openclawhttp://localhost:20268/v1OpenAI Chat Completions
Hermes Agentsrouter setup-hermeshttp://localhost:20268/v1OpenAI Chat Completions
Pisrouter setup-pihttp://localhost:20268/v1OpenAI Chat Completions
Reasonixsrouter setup-reasonixhttp://localhost:20268/v1OpenAI Chat Completions
Factory Droidsrouter setup-droidhttp://localhost:20268/v1OpenAI Chat Completions
OpenClaudesrouter setup-openclaudehttp://localhost:20268/v1OpenAI Chat Completions
AtomCodesrouter setup-atomcodehttp://localhost:20268/v1OpenAI Chat Completions
Zed / JetBrainssrouter setup-zed / setup-jetbrainshttp://localhost:20268Ollama Emulation (/api/*)
Generic OpenAIsrouter setup-generichttp://localhost:20268/v1Standard OpenAI API

Zero-Persistence Launchers

Launch agents without writing sensitive keys to your disk:

# Injects credentials directly into Claude Code's child process environment
srouter launch

# Injects credentials directly into Codex CLI
srouter launch-codex

Diagnostics & Health Check (srouter doctor)

Diagnose whether your coding tools are actually reaching the gateway (resolving environment variables, configuration precedence, and reachability):

srouter doctor
# or check a specific tool:
srouter doctor claude
srouter doctor codex

CLI Generator Flags

FlagDescription
--url URLGateway base URL (default: http://localhost:20268 or SROUTER_URL)
--api-key KEYUnified API key (or SROUTER_API_KEY)
--profile NAMEName the generated profile/provider entry (default: default)
--model IDPin a specific model instead of the catalog default
--dry-runPrint the exact configuration diff to stdout and write nothing

🔑 Provider Keys Management

Manage upstream provider keys right from your terminal without opening a browser. These commands authenticate using your dashboard session token (SROUTER_DASHBOARD_TOKEN or --token):

export SROUTER_URL=http://localhost:20268
export SROUTER_DASHBOARD_TOKEN='<dashboard-session-token>'

# Interactive prompt (hidden input)
srouter keys add groq

# Non-interactive addition
srouter keys add groq --key 'gsk_...'

# List all stored keys (shows ID, platform, active models, health status)
srouter keys list

# Test provider key health through the gateway
srouter keys test groq
srouter keys test groq --id 3

# Remove a provider key safely
srouter keys remove groq --id 3

🔌 Supported Providers

SRouter aggregates ~60 providers and ~1,200+ endpoints behind one unified /v1 endpoint.

Google Gemini
Google Gemini
Groq
Groq
Mistral
Mistral
OpenRouter
OpenRouter
Alibaba Qwen
Alibaba Qwen
Nous Research
Nous Research
SiliconFlow
SiliconFlow
ModelScope
ModelScope
Cloudflare
Cloudflare
Cohere
Cohere
Zhipu GLM
Zhipu GLM
NVIDIA NIM
NVIDIA NIM
Baidu Qianfan
Baidu Qianfan
ByteDance Ark
ByteDance Ark
iFlytek Spark
iFlytek Spark
AMD Radeon
AMD Radeon
HuggingFace
HuggingFace
Kilo
Kilo
LLM7
LLM7
Ollama
Ollama
OVH
OVH
Pollinations
Pollinations
OpenCode
OpenCode
AI Horde
AI Horde

Provider Tiers

  1. ⚡ 100% Free / Keyless: Kilo Gateway (No Key), OpenCode Free (No Key), OVH AI Endpoints, LLM7, AI Horde.
  2. 🌐 Generous Free Tier with Key: Google AI Studio (Gemini 2.5 Flash / Pro), Groq (Llama 3.3 70B @ 30 RPM), Mistral AI (Codestral), Cloudflare Workers AI (10k neurons/day), Cohere, Zhipu GLM-4, NVIDIA NIM.
  3. 🌏 Regional & High Quota: ModelScope (Aliyun, 2,000 req/day), Baidu Qianfan, Volcengine Ark, NaraRouter, Sea-Lion.
  4. 🔌 Custom Local / Self-Hosted: Connect Ollama, LM Studio, vLLM, or llama.cpp directly via the Keys page.

🌐 Unified API Endpoints

SRouter translates diverse API wire protocols into standard surfaces:

EndpointMethodProtocol / TargetDescription
/v1/chat/completionsPOSTOpenAI ChatUniversal LLM chat completions with multi-tier auto-fallback
/v1/responsesPOSTOpenAI ResponsesNative Codex CLI response endpoint
/v1/messagesPOSTAnthropic MessagesNative wire format for Claude Code and Anthropic SDKs
/v1beta/models/*:generateContentPOSTGoogle GeminiNative Gemini wire API for Gemini CLI and SDKs
/v1/searchPOSTUnified SearchAggregated web search across DuckDuckGo, SearXNG, Brave, etc.
/v1/fetchPOSTWeb Fetch RelayClean reader-mode HTML/Markdown extraction for URLs
/v1/decisionPOSTDecision System OneFast heuristic prompt complexity & model selector
/mcpGET / POSTModel Context ProtocolStreamable HTTP transport for Claude Desktop, Cursor, and agents
/v1/modelsGETOpenAI ModelsModel catalog with live execution_status & available filters
/v1/embeddingsPOSTOpenAI EmbeddingsVector embeddings generation
/v1/images/generationsPOSTOpenAI ImagesMulti-provider image generation (Pollinations, Flux, SD)
/v1/audio/speechPOSTOpenAI Audio TTSText-to-speech audio synthesis
/v1/audio/transcriptionsPOSTOpenAI Audio STTSpeech-to-text audio transcription
/api/tagsGETOllama EmulationReturns local & active model catalog for Zed / JetBrains
/api/chatPOSTOllama EmulationNDJSON streaming chat completions for Ollama clients
/v1/docsGETOpenAPI DocumentationInteractive Swagger/Redoc API documentation viewer

[!TIP] Decision System One (/v1/decision): Use this endpoint before sending expensive queries to determine whether a prompt requires a lightweight fast model or a heavy reasoning model.

Web Tools (/v1/search & /v1/fetch): Built-in web scraping and search tools allow your coding agents to research latest docs, packages, and troubleshooting guides directly through the gateway.


🛠️ MCP Server Setup

SRouter includes a native Model Context Protocol (MCP) server over Streamable HTTP at http://localhost:20268/mcp.

Claude Desktop Configuration

Add SRouter to your claude_desktop_config.json:

{
  "mcpServers": {
    "srouter": {
      "url": "http://localhost:20268/mcp",
      "headers": {
        "Authorization": "Bearer srouter-your-unified-key"
      }
    }
  }
}

Cursor / Cline Configuration

In your editor's MCP settings, add a new server:

  • Name: srouter
  • Type: sse or streamable-http
  • URL: http://localhost:20268/mcp
  • Headers: {"Authorization": "Bearer srouter-your-unified-key"}

Available MCP tools include list_models, get_model_status, check_provider_health, and web_search.


🔒 Safety, Security & Local Privacy

  • Non-Destructive Generators: Generator commands merge into existing configuration files rather than overwriting them, taking a timestamped .bak backup first. --dry-run shows the exact diff beforehand.
  • Zero-Exposure Launchers: srouter launch and srouter launch-codex inject credentials only into child process memory — no keys are ever written to disk.
  • Local AES-256-GCM Vault: Upstream API keys are encrypted locally using AES-256-GCM in SQLite (~/.srouter/srouter.db). No telemetry, no cloud relays, no credential leakage.
  • Fail-Open Compression: Token saver and regex compression filters will fail-open safely: if a filter cannot parse an input, the raw prompt is forwarded intact.

⚠️ Troubleshooting & FAQ

Port 20268 is already in use

Specify an alternate port with --port:

srouter serve --port 3000

Rate limit hit (429 Too Many Requests)

SRouter automatically cools down the exhausted key and seamlessly retries the next provider in your fallback chain. If all keys for that model tier are exhausted, enable 100% keyless providers (such as Kilo Gateway or OpenCode Free) via the Web Dashboard.

Where is my data stored?

  • Global CLI: ~/.srouter/srouter.db
  • Docker: Named volume srouter-data (/app/server/data)
  • Windows Desktop: %APPDATA%\SRouter\srouter.db
  • macOS Desktop: ~/Library/Application Support/SRouter/srouter.db

❤️ Support the Developer

If SRouter saves you tokens, boosts your coding workflow, or saves you money, consider supporting development. Every coffee keeps this project independent and actively maintained!

Trakteer Ko-fi PayPal


📄 License & Disclaimer

  • License: Open-source under the MIT License.
  • Disclaimer: SRouter is designed for personal development, experimentation, and coding agent enhancement. Free tiers are governed by the terms of service of each respective upstream provider.
  • Repository: https://github.com/baiibayu/srouter
  • Author: baiibayu
Crafted with passion by @baiibayu & community contributors.

版本与发布记录

@baiibayu/srouter 共发布 12 个版本,首次发布于 2026/10/12;过去 12 个月发布了 12 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.1.70latest2026/11/061 天前
0.1.662026/11/044 天前
0.1.432026/10/2910 天前
0.1.312026/10/2910 天前
0.1.302026/10/2811 天前
0.1.242026/10/2711 天前

关于 @baiibayu/srouter 的常见问题

@baiibayu/srouter 是什么?

SRouter — free open-source LLM router: run the gateway, set up coding agents, manage provider keys

如何安装 @baiibayu/srouter?

在项目目录运行 npm install @baiibayu/srouter,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 srouter,可以用 npx srouter 直接运行。

@baiibayu/srouter 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/baiibayu__srouter 是否存在。

@baiibayu/srouter 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@baiibayu/srouter 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=20.18.0 <25.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@baiibayu/srouter 可以商用吗?

@baiibayu/srouter 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@baiibayu/srouter 的下载量有多少?

根据 npm 官方下载统计,@baiibayu/srouter 在 2026/10/08 – 2026/11/06 这 30 天内被下载 2,276 次,日均约 76 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@baiibayu/srouter 还在维护吗?

最新版本 0.1.70 发布于 2026/11/06(1 天前);至今共发布 12 个版本,其中过去 12 个月发布了 12 个;首次发布于 2026/10/12。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。