Skip to main content

智能模型路由网关 — 基于 LiteLLM 的多服务商自动路由 CLI 工具

Project description

English | 中文

Smart Router — Intelligent Model Routing Gateway

A multi-provider model intelligent routing CLI tool based on LiteLLM. Exposes a unified OpenAI API interface and automatically selects the most suitable underlying LLM based on task type and difficulty.

Features

  • 🔑 Single Entry: One API Key manages all providers
  • 🧠 Smart Routing: Auto-detects task types (coding/writing/reasoning/...) and selects optimal models
  • 🏷️ Stage Markers: Explicit routing control with [stage:code_review]
  • 🔄 Auto Fallback: Automatic model upgrade and retry on failure
  • 🌐 Multi-Provider: Supports OpenAI, Anthropic, Qwen, Kimi, MiniMax, GLM, etc.

🚀 5-Minute Quick Start

Prerequisites

  • Python 3.9+ is required

1. Installation

Choose one of the following methods:

Option A: pip install (Recommended)

pip install smartRouter

Option B: One-line curl install

curl -fsSL https://raw.githubusercontent.com/vaycentsun/smartRouter/main/script/install-remote.sh | bash

Option C: Homebrew (macOS/Linux)

brew tap vaycentsun/smart-router https://github.com/vaycentsun/smartRouter.git
brew install smart-router

Option D: Local install (from source)

git clone https://github.com/vaycentsun/smartRouter.git
cd smartRouter
./script/install.sh

Uninstall

One-line uninstall:

curl -fsSL https://raw.githubusercontent.com/vaycentsun/smartRouter/main/script/uninstall.sh | bash

Or manually:

# Stop service
smart-router stop

# Uninstall package
pip uninstall smartRouter

# Clean up data
rm -rf ~/.smart-router

2. Initialize Configuration

# Download config files via curl (no pip install needed)
curl -sSL https://raw.githubusercontent.com/vaycentsun/smartRouter/main/script/download-config.py | python3

# Or via CLI after pip install
smart-router init

# Force overwrite existing files
smart-router init --force

# Specify custom directory
smart-router init --output ./my-config

Edit the three config files:

vim ~/.smart-router/providers.yaml  # API keys and base URLs
vim ~/.smart-router/models.yaml     # Model capabilities
vim ~/.smart-router/routing.yaml    # Task definitions and routing strategies

Smart Router uses a three-file decoupled architecture:

  • providers.yaml - API keys and base URLs per provider
  • models.yaml - Model capabilities (quality/speed/cost scores)
  • routing.yaml - Task definitions and routing strategies

See Configuration Guide for details.

3. Start Service (Background)

# Start in background (recommended)
smart-router start

# Check status
smart-router status

# Output example:
# ● Smart Router is running
#   PID: 12345
#   Service: http://127.0.0.1:4000
#   Logs: ~/.smart-router/smart-router.log

Foreground mode (for debugging):

export OPENAI_API_KEY="your-key"
smart-router start --foreground

4. Test Routing (No Model Call)

# Test auto-routing
smart-router dry-run "Review this Python code"

# Use stage marker
smart-router dry-run "[stage:writing] Write a business email" --strategy quality

5. Client Usage

from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:4000",
    api_key="sk-smart-router-local"
)

# Auto-routing
response = client.chat.completions.create(
    model="auto",
    messages=[{"role": "user", "content": "Review this code"}]
)

# Use stage marker
response = client.chat.completions.create(
    model="auto",
    messages=[{"role": "user", "content": "[stage:code_review] Review this code"}]
)

📋 Quick Command Reference

Service Management

Command Description
smart-router start Start service in background
smart-router start --foreground Start in foreground (debug mode)
smart-router stop Stop service
smart-router restart Restart service
smart-router status Check service status

Logs

Command Description
smart-router logs View last 50 lines of logs
smart-router logs -n 100 View last 100 lines
smart-router logs -f Follow logs (Ctrl+C to exit)

Configuration & Testing

Command Description
smart-router init Generate default configuration

| smart-router doctor | Run health check (includes config validation) | | smart-router dry-run "prompt text" | Test routing decision | | smart-router list | List configured providers and models |


🎯 Stage Markers

Add markers to prompts for explicit routing control:

# Code review
"[stage:code_review] Review this code"

# Writing task (easy)
"[stage:writing] [difficulty:easy] Write an email"

# Complex reasoning
"[stage:reasoning] [difficulty:hard] Prove this theorem"

Supported Stages

Marker Purpose Default Models
brainstorming Brainstorming ideas qwen-turbo, gpt-4o-mini
code_review Code review claude-3-sonnet
writing Writing tasks qwen-turbo, kimi-k2
reasoning Logical reasoning claude-3-opus
chat General chat qwen-turbo, gpt-4o-mini

More details: Stage Marker System


⚙️ Configuration

Smart Router uses a three-file decoupled architecture:

config/
├── providers.yaml    # Provider connection settings
├── models.yaml       # Model capability declarations  
└── routing.yaml      # Task definitions and routing rules

providers.yaml

Define API endpoints and authentication once per provider:

providers:
  openai:
    api_base: https://api.openai.com/v1
    api_key: os.environ/OPENAI_API_KEY
    timeout: 30
    
  anthropic:
    api_base: https://api.anthropic.com
    api_key: os.environ/ANTHROPIC_API_KEY

models.yaml

Declare model capabilities (quality/speed/cost scores 1-10):

models:
  gpt-4o:
    provider: openai              # References provider above
    litellm_model: openai/gpt-4o
    capabilities:
      quality: 9                  # Quality score (1-10)
      speed: 8                    # Response speed (1-10)
      cost: 3                     # Cost efficiency (10=cheapest)
      context: 128000             # Context window
    supported_tasks: [chat, code_review, writing]
    difficulty_support: [easy, medium, hard]

routing.yaml

Define tasks and routing strategies:

tasks:
  code_review:
    name: "Code Review"
    description: "Review code quality"
    capability_weights:           # How to weight capabilities
      quality: 0.6                # 60% weight on quality
      speed: 0.2                  # 20% weight on speed
      cost: 0.2                   # 20% weight on cost

strategies:
  auto:     # Uses task weights to calculate composite score
  quality:  # Selects highest quality model
  speed:    # Selects fastest model
  cost:     # Selects most cost-effective model

fallback:
  mode: auto
  similarity_threshold: 2  # Models within ±2 quality are fallbacks

Key advantages:

  • Add/remove models by editing only models.yaml
  • Routing is dynamically calculated - no manual list maintenance
  • Fallback chains auto-derived from capability similarity
  • Clear separation of concerns

Routing Strategies

  • auto: Use weighted capability scores to select best model
  • speed: Select fastest responding model
  • cost: Select most cost-effective model
  • quality: Select highest quality model

More configuration details: Configuration Guide


🔧 Troubleshooting

Service Won't Start

# Check port usage
lsof -i :4000

# View logs
smart-router logs

# Run health check (includes config validation)
smart-router doctor

# Run in foreground to see detailed errors
smart-router start --foreground

Check Environment Variables

# Check API Keys
echo $OPENAI_API_KEY
echo $ANTHROPIC_API_KEY

# Set environment variable
export OPENAI_API_KEY="sk-..."

Test Connectivity

# Test if service is running
curl http://localhost:4000/v1/models \
  -H "Authorization: Bearer sk-smart-router-local"

More troubleshooting: Troubleshooting Guide


📚 Documentation

Document Content
Complete Guide Detailed CLI commands, configuration, best practices
V3 Config Examples V3 three-file configuration examples
V3 Design Spec V3 architecture design and migration guide
Design Doc Original architecture design and technical specs

Quick Navigation


🏗️ Architecture

User Request → LiteLLM Proxy → SmartRouter Plugin
                                  ├── Stage Marker Parsing
                                  ├── Task Classification (L1 Rules + L2 Similarity)
                                  ├── Model Selection (auto/speed/cost/quality)
                                  └── Fallback Management
                    ↓
            Target Model Provider

Components

  • core/smart_router/cli.py - CLI entry commands
  • core/smart_router/plugin.py - SmartRouter core plugin (V2 config)
  • core/smart_router/plugin_v3_adapter.py - V3 configuration adapter
  • core/smart_router/server.py - LiteLLM Proxy wrapper
  • core/smart_router/config/ - Configuration loading and validation
    • v3_schema.py - V3 Pydantic schemas
    • v3_loader.py - V3 three-file config loader
  • core/smart_router/classifier/ - Task classifier (L1 Rules + L2 Embedding)
  • core/smart_router/selector/ - Model selection strategies
    • v3_selector.py - V3 capability-based selector
  • core/smart_router/utils/ - Utility functions

🧪 Development

pip install -e ".[dev]"

pytest tests/ -v

📄 License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

smartrouter-1.1.2.tar.gz (395.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

smartrouter-1.1.2-py3-none-any.whl (271.7 kB view details)

Uploaded Python 3

File details

Details for the file smartrouter-1.1.2.tar.gz.

File metadata

  • Download URL: smartrouter-1.1.2.tar.gz
  • Upload date:
  • Size: 395.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for smartrouter-1.1.2.tar.gz
Algorithm Hash digest
SHA256 0c6d24be90180822fe22e51ae2072cfca1b7fad57002988e7d559545b37fdcee
MD5 e0e97eb1fba1026333805ee83da2ffe8
BLAKE2b-256 1446b852f5393d9fbb6d82123a2865ef2930d427dbf1908249fa3a671e5d1ee7

See more details on using hashes here.

Provenance

The following attestation bundles were made for smartrouter-1.1.2.tar.gz:

Publisher: publish.yml on vaycentsun/smartRouter

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file smartrouter-1.1.2-py3-none-any.whl.

File metadata

  • Download URL: smartrouter-1.1.2-py3-none-any.whl
  • Upload date:
  • Size: 271.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for smartrouter-1.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 ebedcf4169a7757176f8622ca9ec918a3842638430cb5e6377b65da3b9cbc4f0
MD5 17138f66970e95d3b093ed48939e3f07
BLAKE2b-256 57765818e4cdb5ee5b57d2b5184de0031d872854a677bb1408ca18fc5d1520f2

See more details on using hashes here.

Provenance

The following attestation bundles were made for smartrouter-1.1.2-py3-none-any.whl:

Publisher: publish.yml on vaycentsun/smartRouter

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page