ypollak2/llm-router
pip install llm-routing # PyPI name is llm-routing; the CLI command is llm-router설치하는 이유
AI 코딩 도구는 기본적으로 너무 많은 프롬프트를 프리미엄 모델로 보냅니다.
즉, 다음과 같은 문제가 발생합니다:
간단한 질문에 유료 토큰을 낭비합니다
Claude, Gemini, OpenAI 할당량을 필요 이상으로 빠르게 소진합니다
한 제공자가 속도 제한에 걸리거나 다운되면 작업을 중단해야 합니다
llm-router는 코딩 도구와 모델 제공자 사이에 위치합니다. 각 프롬프트를 분류하고, 가장 저렴하면서도 작업을 처리할 수 있는 모델을 먼저 시도하며, 필요할 때 자동으로 대체합니다.
기존 워크플로우는 그대로 유지됩니다. 라우터가 그 아래에서 모델 선택만 변경합니다.
Related MCP server: MCP AI Router
RouterArena 8위
llm-router는 독립적으로 벤치마킹되어 RouterArena에서 8위를 차지했습니다. RouterArena는 라우팅 정확도, 지연 시간, 비용 효율성, 대체 신뢰성을 기준으로 모델 라우터를 평가하는 커뮤니티 리더보드입니다.
빠른 시작
1. 설치
pip install llm-routing
llm-router installPyPI 패키지 이름:
llm-routing. CLI 명령어:llm-router.
2. 제공자 추가 (선택 사항)
export OPENAI_API_KEY="sk-..." # GPT-4o, o3
export GEMINI_API_KEY="AIza..." # Gemini Flash/Pro (free tier available)
export OLLAMA_BASE_URL="http://localhost:11434" # Local models (free)
export OPENROUTER_API_KEY="sk-or-v1-…" # 343 OpenRouter models (qwen, deepseek, grok, …)Claude Code Pro/Max 구독에서는 API 키 없이 작동합니다. 라우팅은 유익한 경우에만 외부 모델을 호출하는 MCP 도구를 사용합니다. OPENROUTER_API_KEY를 추가하면 cost_aggressive 정책에서 사용하는 오픈 가중치 워크호스 풀을 사용할 수 있습니다.
3. 확인
llm-router health # Check provider connectivity이미 Claude Code, Codex, Gemini CLI를 사용 중이라면 기존 워크플로우를 유지하고 llm-router가 그 아래에서 모델을 선택하도록 하세요.
라우팅 예시
프롬프트 | 라우팅 대상 |
"이 Python 오류는 무슨 뜻인가요?" | Ollama / Gemini Flash / Codex |
"이 엔드포인트 리팩터링" | GPT-4o / Gemini Pro |
"분산 추적 전략 설계" | o3 / Claude Opus |
정확한 체인은 구성된 제공자, 예산 프로필, 라우팅 정책에 따라 달라집니다.
호환 대상
도구 | 모드 | 절감 효과 (이 호스트) |
Claude Code | 후크를 통한 전체 자동 라우팅 | 60–80% |
Codex CLI | 후크를 통한 전체 자동 라우팅 | 60–80% |
Gemini CLI | 후크를 통한 전체 자동 라우팅 | 50–70% |
VS Code / Cursor | 수동 MCP 도구 | 30–50% |
모든 MCP 클라이언트 | 수동 MCP 도구 | 상황에 따라 다름 |
전체 자동 라우팅은 후크가 프롬프트를 가로채 워크플로우 변경 없이 자동으로 라우팅함을 의미합니다.
수동 MCP 도구는
llm_query와 같은 도구를 통해 필요할 때 라우팅을 사용할 수 있음을 의미합니다.
llm-router install # Claude Code (default)
llm-router install --host codex # Codex CLI
llm-router install --host gemini-cli # Gemini CLI
llm-router install --host vscode # VS Code
llm-router install --host cursor # Cursor각 호스트에 대한 자세한 내용은 guide/HOST_SUPPORT_MATRIX.md를 참조하세요.
Claude Code 5시간 할당량 보호
enforce: smart + mode: zero_claude를 사용하면 프롬프트가 외부에서 완료되거나 네이티브 Claude가 실행되기 전에 중지됩니다. 자세한 내용은
**guide/GETTING_STARTED.md**를 참조하세요.
작동 방식
User prompt
│
▼
┌──────────────────────┐
│ Complexity Classifier │ ← Heuristic (free, instant) or Ollama/Flash ($0.0001)
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ Free-First Router │ ← Tries cheapest model first, walks up the chain
│ │
│ Ollama (free) │
│ → Codex (prepaid) │
│ → Gemini Flash │
│ → GPT-4o / Claude │
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ Guards (parallel) │ ← Circuit breaker, budget pressure, quality check
└──────────┬───────────┘
│
▼
Response + cost logged to local SQLite분류는 많은 작업에서 무료입니다(정규식 휴리스틱이 약 70%를 처리) 또는 로컬 Ollama나 Gemini Flash를 사용할 때 모호한 프롬프트의 경우 거의 무료입니다.
기능
"저렴한 프롬프트를 저렴한 모델로 보내기" 그 이상:
비밀 정보가 기기를 벗어나지 않습니다. API 키, 토큰 또는 개인 키가 포함된 프롬프트는 로컬 모델로만 라우팅됩니다. 외부 제공자에 도달할 수 없도록 fail-closed 방식입니다.
비용 역전 구독 라우팅. 간단하고 보통 수준의 프롬프트에는 무료/로컬을 우선 사용하고, 복잡한 프롬프트에는 유료 좌석을 우선 사용하며, 할당량이 부족할 때는 해당 좌석을 하위로 강등합니다.
LLM_ROUTER_SUBSCRIPTION_PROVIDER로 선택할 수 있습니다.회로 차단기가 포함된 자동 대체. 실패하거나 속도 제한에 걸린 제공자는 반복 재시도하지 않고 건너뜁니다.
작동 과정을 직접 볼 수 있습니다. 상태 표시줄, 터미널 제목, OS 알림에 마지막으로 라우팅된 모델, 절감액, 상태가 표시됩니다. 네이티브 상태 표시줄이 없는 호스트를 위한 기능입니다.
세션 종료 요약. 기준 대비 절감액, 계층 분포, 제공자별 비용, 지연 시간 p50/p95/p99, 주요 라우팅 경로가 표시됩니다.
미디어와 파이프라인도 지원합니다.
llm_image/llm_video/llm_audio, 다단계 리서치를 위한llm_orchestrate.
CLI
llm-router install # wire up your host (Claude Code by default)
llm-router health # provider connectivity
llm-router status # savings + quota at a glance
llm-router doctor # diagnose a broken setup전체 명령어 참조: guide/GETTING_STARTED.md
제공자
20개 이상의 제공자, 무료 우선. Ollama(로컬, 무료)가 체인의 선두이며, OpenRouter(하나의 키로 343개 모델)가 가장 큰 단일 해금이며, Gemini와 Groq는 사용 가능한 무료 티어가 있습니다. Anthropic은 기존 Claude 구독을 통해 작동합니다. API 키가 필요 없습니다.
모든 제공자, 모델, 비용 티어, 환경 변수: guide/PROVIDERS.md
라우팅 정책
정책은 라우터가 프리미엄 모델에서 얼마나 적극적으로 라우팅하는지를 결정합니다. conservative(10–15% 절감)부터 balanced(기본값, 35–45%), cost_aggressive(70–85%, OPENROUTER_API_KEY 필요)까지 있습니다.
llm-router policy set cost_aggressive6가지 정책 전체, 임계값, YAML 스키마: guide/POLICIES.md
MCP 도구
라우팅, 분석, 코드, 미디어, 예산, 진단에 걸친 60개 도구가 모든 MCP 호스트에 노출됩니다. 기본 consolidated 표면에는 11개의 프런트 도어 도구가 표시되며, LLM_ROUTER_SLIM=full로 설정하면 60개 모두 표시됩니다.
각 도구와 시그니처: guide/TOOLS.md
절감 효과: 작동 방식
절감액은 모든 작업을 Claude Sonnet/Opus로 라우팅하는 기준선과 실제 지출을 비교하여 계산됩니다.
방법론:
라우팅된 각 작업이 기록: 사용된 모델, 소비된 토큰, 예상 비용
동일한 토큰을 체인에서 가장 비싼 모델이 처리했을 때의 기준 비용을 계산
절감액 =
(기준 - 실제) / 기준
가정 및 제한 사항:
기준선은 모든 작업에 Opus/Sonnet을 사용했을 경우를 가정합니다(최악의 경우)
토큰 추정치는 정확한 토크나이저 수가 아닌
len(text) / 4근사치를 사용합니다비용 데이터는 LiteLLM의 가격 테이블에서 가져옵니다(제공자 가격 변경에 뒤처질 수 있음)
절감액은 워크로드에 따라 크게 달라집니다. 코드 중심 세션은 저렴한 모델로 더 많이 라우팅됩니다
라우터 자체는 약간의 오버헤드를 추가합니다(모호한 작업당 분류 비용 약 $0.0001)
관찰 범위: 정책과 작업 구성에 따라 35–80% 절감. 일부 문서의 "87%" 수치는 특정 개발 기간 동안의 단일 사용자 최고치이며 보장된 결과가 아닙니다.
신뢰, 개인정보 보호, 로컬 우선 설계
llm-router는 전적으로 사용자 기기에서 실행됩니다. 호스팅 프록시, 텔레메트리, 계정이 필요 없습니다.
항목 | 위치 | 세부 정보 |
사용자의 프롬프트 | 설정된 공급업체로 전송됨 | 해당 공급업체를 직접 사용하는 것과 동일 |
API 키 |
| 로컬 파일, 절대 전송되지 않음 |
사용 로그 |
| 암호화되지 않은 SQLite(파일 시스템 권한) |
분류 캐시 | 메모리 내 | 프로세스 재시작 시 지워짐 |
후크 스크립트 |
| 로컬 셸 스크립트, 검사 가능 |
우리가 하는 일:
구조화된 로그에서 API 키 제거
설치 전 후크 교착 상태 감지
모든 데이터를
~/.llm-router/에 로컬 저장공급업체 속도 제한 및 서비스 약관(TOS) 준수
알아야 할 사항:
프롬프트는 라우터가 선택한 공급업체로 전송됩니다 — 공급업체의 개인정보 처리방침을 검토하세요.
사용 로그(SQLite)는 저장 시 암호화되지 않습니다 — 필요한 경우 전체 디스크 암호화를 사용하세요.
라우터는 공급업체 수준에서 모델 탈옥이나 프롬프트 인젝션을 방지할 수 없습니다.
책임 있는 공개 정책은 SECURITY.md를 참조하세요.
구성
모든 것이 환경 변수입니다 — 시작하는 데 구성 파일이 필요 없습니다:
export OPENROUTER_API_KEY="sk-or-v1-..." # biggest single unlock
export OLLAMA_BASE_URL="http://localhost:11434" # local, free
export LLM_ROUTER_POLICY="cost_aggressive" # routing policy
export LLM_ROUTER_ENFORCE="smart" # off | advise | smart | hard전체 참조, 구성 파일 스키마 및 호스트별 재정의: guide/GETTING_STARTED.md
문서
전체 색인: guide/README.md
문서 | 목적 |
작동하는 라우팅을 위한 가장 빠른 경로 | |
전체 설정 안내 | |
호스트별 기능 비교 | |
공급업체 설정 및 모델 권장 사항 | |
| |
예제가 포함된 60개 MCP 도구 전체 | |
내부 설계 및 모듈 구조 | |
일반적인 문제 및 해결 방법 | |
라우팅 상태 확인을 위한 격리 테스트 모음 | |
모델 비용/지연 시간/품질 표, CI로 재생성됨 | |
릴리스 노트(아카이브) |
엔터프라이즈
llm-router는 개인 개발자와 소규모 팀을 위해 만들어졌습니다: 로컬 비용 절감, 운영 오버헤드 제로, 호스팅 서비스 없음. 팀 전체 정책 적용, 감사 내보내기, SSO 또는 조직별 예산이 필요하다면, 그것이 바로 **Chuzom**의 용도입니다.
기여
기여를 환영합니다. 전체 지침은 CONTRIBUTING.md를 참조하세요.
git clone https://github.com/ypollak2/llm-router.git
cd llm-router
uv sync --extra dev
uv run pytest tests/ -q # Run tests (1900+)
uv run ruff check src/ tests/ # Lint-|-----------|
| llm-routing | 현재 PyPI 패키지(pip install llm-routing) |
| llm-router | CLI 명령 및 GitHub 저장소 이름 |
| claude-code-llm-router | 더 이상 사용되지 않는 레거시 패키지(llm-routing으로 리디렉션됨) |
Available Tools
60 toolsagoragentic_browseA
Browse available services on the Agoragentic marketplace.
Shows trust-verified providers and their capabilities.
Returns: JSON list of available capabilities
Inputs: no named parameters. Returns: result
agoragentic_statusA
Get llm-router agent status on Agoragentic.
Shows registration status, available seller slots, listings, etc.
Returns: Agent status as JSON
Inputs: no named parameters. Returns: result
agoragentic_taskA
Execute a task on the Agoragentic capability marketplace.
Routes automatically to the best-matching trusted provider. Handles USDC settlement on Base L2 blockchain.
Args: task: Task type (e.g., "code_review", "summarization") input_json: Task input as JSON string max_budget_usdc: Maximum spend limit (optional)
Returns: Execution result as JSON string
Inputs: task (required), input_json (required), max_budget_usdc. Returns: result
agoragentic_walletA
Check Agoragentic wallet balance and status.
Returns: Wallet info including balance, chain, and currency
Inputs: no named parameters. Returns: result
llm_analyzeA
Deep analysis task — routes to the strongest reasoning model.
Best for: data analysis, code review, problem decomposition, debugging.
Args: prompt: What to analyze. complexity: Task complexity — "simple", "moderate", or "complex". Analysis tasks default to at least moderate. Pass "complex" for multi-file reviews or architecture decisions that warrant Opus/o3. system_prompt: Optional system instructions. max_tokens: Maximum output tokens. context: Optional conversation context to help the model understand the broader task.
Inputs: prompt (required), context, complexity, max_tokens, +1 more. Returns: result
llm_approve_routeA
Approve or reject a pending high-cost routing decision.
Use this when llm_route (or any routing tool) blocked a call because the estimated cost exceeded LLM_ROUTER_ESCALATE_ABOVE. The pending call is stored server-side until you approve or cancel it.
Args: approve: True to proceed with the call, False to cancel it. downgrade_to: Optional cheaper model to use instead of the blocked one (e.g. "gemini/gemini-2.5-flash" instead of "openai/o3").
Inputs: approve, downgrade_to. Returns: result
llm_audioA
Generate speech/audio — routes to ElevenLabs or OpenAI TTS.
Args: text: Text to convert to speech. model: Optional model override (e.g. "openai/tts-1-hd", "elevenlabs/eleven_multilingual_v2"). voice: Voice selection (OpenAI: alloy/echo/fable/onyx/nova/shimmer. ElevenLabs: voice ID).
Inputs: text (required), model, voice. Returns: result
llm_autoA
Auto-routing wrapper with persistent savings tracking — works from any host.
Equivalent to llm_route but additionally:
Flushes pending hook-written savings records into SQLite before routing.
Appends a compact savings envelope every 5 calls so you can see the cumulative value across all sessions and hosts without running llm_savings.
Use llm_auto instead of llm_route when you are in a host that lacks a UserPromptSubmit hook (Codex CLI, Claude Desktop, GitHub Copilot) — the savings are tracked server-side, so they accumulate correctly regardless of which client triggered the call.
Args: prompt: The task or question to route. task_type: Optional hint — "query", "research", "generate", "analyze", "code". profile_override: Force a routing profile — "budget", "balanced", or "premium". system_prompt: Optional system instructions. context: Optional conversation context.
Inputs: prompt (required), context, task_type, system_prompt, +1 more. Returns: result
llm_benchmarkA
Show routing accuracy benchmarks by task type.
Accuracy is computed from llm_rate feedback (thumbs up/down). The more you rate responses with llm_rate, the more accurate this becomes.
Also shows an optional community export status if LLM_ROUTER_COMMUNITY=true.
Inputs: no named parameters. Returns: result
llm_budgetA
Show real-time budget pressure for all configured providers (v5.0+).
Reads live budget state from the Budget Oracle, which normalises provider quota into a single pressure value (0.0 = fully available, 1.0 = exhausted).
Pressure sources by provider type: Local (Ollama, vLLM) — always 0.0 (free, no quota) Claude subscription — max(session_pct, weekly_pct, sonnet_pct) / 100 API-key providers — monthly spend / configured cap (0.0 if no cap)
Returns: A formatted budget summary with pressure bars per provider.
Inputs: no named parameters. Returns: result
llm_cache_clearA
Clear the prompt classification cache.
Inputs: no named parameters. Returns: result
llm_cache_statsA
Show prompt classification cache statistics — hit rate, entries, memory usage.
The cache stores ClassificationResult objects keyed by SHA-256(prompt + quality_mode + min_model). Budget pressure is always applied fresh, so cached classifications stay valid.
Inputs: no named parameters. Returns: result
llm_check_usageA
Check real-time Claude subscription usage (session limits, weekly limits, extra spend).
Shows cached data if available. If no data cached, returns the JS snippet to run via Playwright's browser_evaluate (one call, no page navigation needed).
The budget pressure from this data feeds directly into model routing — higher usage = more aggressive downshifting to cheaper models.
Inputs: no named parameters. Returns: result
llm_classifyA
Classify a prompt's complexity and recommend which model to use.
Returns a smart recommendation considering complexity, daily token budget, quality preference, and minimum model floor. Includes budget usage bar.
Complexity drives model selection at all times:
simple → haiku, moderate → sonnet, complex → opus Budget pressure is a late safety net only:
0-85%: no downshift — complexity routing handles efficiency
85-95%: downshift by 1 tier (opus→sonnet, sonnet→haiku)
95%+: downshift by 2 tiers, warns user
Args: prompt: The task or question to classify. quality: Override quality mode — "best", "balanced", or "conserve". min_model: Override minimum model floor — "haiku", "sonnet", or "opus".
Inputs: prompt (required), quality, min_model. Returns: result
llm_codeA
Coding task — routes to the best coding model.
Best for: code generation, refactoring suggestions, algorithm design.
Args: prompt: The coding task or question. complexity: Task complexity — "simple", "moderate", or "complex". Drives model selection: simple questions use Haiku/Flash, actual implementation tasks use Sonnet/GPT-4o, large refactors or architecture work use Opus/o3. system_prompt: Optional system instructions (language, framework, style). max_tokens: Maximum output tokens. context: Optional conversation context to help the model understand the broader task.
Inputs: prompt (required), context, complexity, max_tokens, +1 more. Returns: result
llm_codexA
Route a task to the local Codex desktop agent (OpenAI).
Uses the Codex CLI to run tasks non-interactively. This uses the user's OpenAI subscription (not Claude quota) — ideal as a fallback when Claude limits are tight, or for tasks that benefit from OpenAI's models.
Available models: gpt-5.4, o3, o4-mini, gpt-4o, gpt-4o-mini
Args: prompt: The task or question to send to Codex. model: OpenAI model to use (default: gpt-5.4).
Inputs: prompt (required), model. Returns: result
llm_dashboardA
Open the LLM Router web dashboard in the background.
Starts a local HTTP server at localhost: showing routing stats, cost trends, model distribution, and recent decisions. Refreshes every 30s.
The dashboard reads from the same SQLite DB the router writes — no extra configuration needed.
Args: port: TCP port for the dashboard server (default 7337).
Returns: URL and instructions for opening the dashboard.
Inputs: port. Returns: result
llm_digestA
Generate a savings digest and optionally send it to a webhook.
Formats a savings summary for the given period. Also detects spend spikes and shows a "what if router was off?" simulation.
Args:
period: "today", "week", "month", or "all time".
send: If True, POST the digest to LLM_ROUTER_WEBHOOK_URL.
Inputs: send, period. Returns: result
llm_editA
Route code-edit reasoning to a cheap model and return exact edit instructions.
Instead of Opus reasoning about what to change (expensive), a cheap model
reads the files, figures out the edits, and returns JSON {file, old_string, new_string} pairs that Claude can apply mechanically via the Edit tool.
How to use the result: After calling this tool, apply each edit instruction using the Edit tool with the exact old_string → new_string pairs provided.
Best for: refactoring, bug fixes, adding small features to existing files.
Args: task: Natural-language description of what to change (e.g. "Add type hints to all public functions in router.py"). files: List of file paths to read and include in the prompt. Relative paths are resolved from the current working directory. Files larger than 32 KB are truncated with a note. context: Optional conversation context to help the model understand the task.
Inputs: task (required), files (required), context. Returns: result
llm_fs_analyze_contextA
Analyze workspace files to build a routing context summary.
Scans key files (package.json, pyproject.toml, go.mod, Cargo.toml, README, open TODOs) and produces a compact semantic summary stored in ~/.llm-router/context_summary.json. Subsequent routing decisions inject this summary into the system prompt so cheap models have workspace context.
Call this once at the start of a project session or after major refactors. The summary is automatically used by llm_route and llm_auto — no further action required.
Args: path: Workspace root to analyze (default: current directory). max_files: Maximum files to read (default: 20).
Inputs: path, max_files. Returns: result
llm_fs_edit_manyA
Generate bulk edit instructions across multiple files.
Extends the llm_edit pattern to many files at once: the cheap model
reads all target files and returns a JSON array of {file, old_string, new_string} edit instructions. Claude applies them mechanically.
Use this for cross-file refactors, bulk renames within files, or updating repeated patterns across a module.
Args:
task: Natural-language description of what to change, e.g.
"replace all import sqlite3 with import aiosqlite as sqlite3"
or "update the copyright year from 2024 to 2025 in all file headers".
files: Explicit list of file paths to process.
glob_pattern: Glob pattern to find files (e.g. "src/**/*.py"). Use
either files or glob_pattern, not both.
max_files: Cap on files processed in one call (default 20). Raise if
you need more — but consider splitting into batches for large refactors.
Inputs: task (required), files, max_files, glob_pattern. Returns: result
llm_fs_findA
Generate glob/grep commands to find files matching a natural-language description.
Routes to Haiku/Ollama so the cheap model does pattern thinking. Claude executes the returned commands with Glob/Grep/Bash.
Args: description: What you're looking for, e.g. "all Python files that import sqlite3" or "TypeScript files with TODO comments added in the last week". root: Optional root directory to search in. Defaults to current working directory.
Inputs: description (required), root. Returns: result
llm_fs_renameA
Generate shell commands for a file rename/reorganisation operation.
Describe what you want to rename and the cheap model produces the mv/git mv
commands. Use dry_run=True (default) to get echo-prefixed commands safe
to inspect before running.
Args:
description: What to rename and how, e.g. "rename all _old.py files in
src/ to remove the old suffix" or "move all test*.py files from
tests/unit/ into tests/".
dry_run: When True, commands are prefixed with echo for safe review.
Set to False to get directly executable commands.
Inputs: description (required), dry_run. Returns: result
llm_gainA
Show token savings dashboard (RTK-style).
Displays comprehensive token savings metrics across all routing decisions, showing actual costs vs. Opus baseline and efficiency multiplier.
Features:
Total savings and efficiency multiplier
Breakdown by model, complexity, and tool
Daily trend analysis
Cost comparisons
Args: period: Time period to analyze: "today", "week" (default), "month", or "all"
Returns: Formatted savings dashboard
Inputs: period. Returns: result
llm_geminiA
Route a task to the local Gemini CLI agent (Google).
Uses the Gemini CLI to run tasks non-interactively. This uses the user's Google One AI Pro subscription (not Claude quota) — ideal as a fallback when Claude limits are tight, or for tasks that benefit from Google's Gemini models.
Available models: gemini-2.5-flash, gemini-2.0-flash, gemini-3-flash-preview
Args: prompt: The task or question to send to Gemini. model: Google model to use (default: gemini-2.5-flash).
Inputs: prompt (required), model. Returns: result
llm_generateA
Generate creative or long-form content — routes to the best generation model.
Best for: writing, summarization, brainstorming, content creation.
Args: prompt: What to generate. complexity: Task complexity — "simple", "moderate", or "complex". Drives model selection. Simple tasks (short summaries) use cheap models; complex tasks (long-form, nuanced writing) use premium models. system_prompt: Optional system instructions (tone, format, audience). temperature: Sampling temperature (higher = more creative). max_tokens: Maximum output tokens. context: Optional conversation context to help the model understand the broader task.
Inputs: prompt (required), context, complexity, max_tokens, +2 more. Returns: result
llm_healthA
Check the health status of all configured LLM providers.
Inputs: no named parameters. Returns: result
llm_hook_healthA
Check the health status of all routing hooks.
Shows:
Hook permission status (executable vs not)
Success/error counts
Recent errors with timestamps
Health status (healthy/degraded/failing)
Inputs: no named parameters. Returns: result
llm_imageA
Generate an image — auto-routes to Gemini Imagen, DALL-E, Flux, or Stable Diffusion.
Args: prompt: Description of the image to generate. model: Optional model override (e.g. "gemini/imagen-3", "openai/dall-e-3", "fal/flux-pro", "stability/stable-diffusion-3"). size: Image size (e.g. "1024x1024", "1792x1024"). quality: Image quality — "standard" or "hd" (DALL-E only).
Inputs: prompt (required), size, model, quality. Returns: result
llm_import_profileA
Import a learned routing profile from community or URL.
Imports a shared profile and merges it with your existing learned routes. Community profiles must have confidence >= 2 to be imported (strict validation).
Args: url: URL to a profile JSON file (optional; defaults to community latest)
Returns: Merge summary and new routes imported
Inputs: url. Returns: result
llm_model_evalA
Evaluate and benchmark all available local and remote models.
Runs a suite of benchmark tasks (reasoning, code) against each available model (Ollama, Codex, APIs) to determine quality, speed, and accuracy. Results are cached for 7 days and used to optimize routing priorities.
Can be called manually to force a re-evaluation, or automatically runs once per week during session-end.
Returns: Formatted evaluation results with quality scores and latency metrics.
Inputs: no named parameters. Returns: result
llm_model_exportA
Export model tracking data for external analysis.
Exports complete routing history to a file for analysis in spreadsheets or data tools (Excel, Python, R, etc.).
Args: format: Export format (csv, json). Default: csv
Returns: Path to exported file and record count.
Inputs: format. Returns: result
llm_model_usageA
Analyze which models are being selected in routing.
Shows usage statistics for the last N hours:
Top models selected
Task type distribution (code/query/analyze/etc)
Classification methods used (heuristic/ollama/api/fallback)
Individual model success rates with quality feedback
Args: hours: Look back this many hours (default: 24)
Returns: Formatted usage statistics and analysis.
Inputs: hours. Returns: result
llm_orchestrateA
Multi-step orchestration — automatically decomposes complex tasks across multiple LLMs.
Chains research, analysis, generation, and coding steps together, routing each to the optimal model. Use templates for common patterns or let the AI decompose.
Free tier: up to 2-step pipelines. Pro tier: unlimited steps + auto-decomposition.
Args: task: Description of the complex task to accomplish. template: Optional pipeline template: "research_report", "competitive_analysis", "content_pipeline", "code_review_fix". Omit for auto-decomposition.
Inputs: task (required), template. Returns: result
llm_pipeline_templatesA
List available pipeline templates for multi-step orchestration.
Inputs: no named parameters. Returns: result
llm_policyA
Show the active routing policy and recent policy audit events.
Displays the merged policy from all three layers:
Org policy (~/.llm-router/org-policy.yaml)
User policy (~/.llm-router/routing.yaml)
Repo policy (.llm-router.yml)
Also shows the last 10 policy enforcement events from the audit log.
Inputs: no named parameters. Returns: result
llm_providersA
List all supported providers and which ones are configured.
Inputs: no named parameters. Returns: result
llm_quality_guardA
Show quality scores per model with degradation alerts (v6.2).
Displays rolling average judge scores for all routed models over the past N days. Alerts if any model's score < 0.7 with sufficient samples (quality degradation).
Args: days: Number of days of history to analyze (default 7).
Returns: Formatted table with model scores, trend arrows, and alerts.
Inputs: days. Returns: result
llm_quality_reportA
Show routing quality metrics — classification accuracy, savings, model distribution.
Analyzes routing decisions over the specified period to show how the classifier is performing, which models are being selected, downshift rates, and cost efficiency.
Args: days: Number of days to include in the report (default 7).
Inputs: days. Returns: result
llm_queryA
Send a general query to the best available LLM.
Routes by complexity: simple→Haiku/Flash, moderate→Sonnet/GPT-4o, complex→Opus/o3.
Args: prompt: The question or prompt to send. complexity: Task complexity — "simple", "moderate", or "complex". Drives model selection: simple→cheap (Haiku/Flash), moderate→balanced (Sonnet/GPT-4o), complex→premium (Opus/o3). Auto-detected from prompt length when omitted. model: Explicit model override, bypasses complexity routing entirely. system_prompt: Optional system instructions. temperature: Sampling temperature (0.0-2.0). max_tokens: Maximum output tokens. context: Optional conversation context to help the model understand the broader task.
Inputs: prompt (required), model, context, complexity, +3 more. Returns: result
llm_quota_statusA
Show quota balance across Claude, Gemini CLI, and Codex subscriptions.
Monitors three subscription providers to help you understand which quota is being exhausted, and make routing decisions accordingly.
The QUOTA_BALANCED profile uses this data to dynamically reorder the routing chain — keeping usage balanced across all three subscriptions.
Returns: Formatted quota status with usage percentages and route recommendations.
Inputs: no named parameters. Returns: result
llm_rateA
Rate the last (or a specific) routing decision as good or bad.
Stores thumbs-up / thumbs-down feedback in the routing_decisions table.
Over time this signal can be used to retrain the local classifier so routing
choices improve based on your preferences.
Args: good: True = routing was a good choice; False = bad choice. decision_id: Row ID to rate. Omit (or pass None) to rate the most recent routing decision.
Returns: Confirmation string with the rated decision ID, or an error message.
Inputs: good (required), decision_id. Returns: result
llm_refresh_claude_usageA
Refresh Claude subscription usage via the OAuth API — no browser required.
Reads the Claude Code OAuth token from the macOS Keychain, calls the Anthropic OAuth usage endpoint, and updates the local usage cache.
Requires: Claude Code installed and authenticated on macOS.
Inputs: no named parameters. Returns: result
llm_rerouteA
Override the last routing decision and record it for feedback learning.
Logs the correction to the database so future routing decisions for this task type have lowered confidence. Use this when llm_route, llm_query, llm_code, or any other tool chose the wrong model for your task.
Args: to_tool: Which tool to use instead (e.g. "llm_analyze", "llm_code"). reason: Optional explanation — stored for routing quality improvement. original_tool: The tool that made the wrong decision (auto-detected if omitted). original_model: The model that was selected (for logging purposes).
Inputs: to_tool (required), reason, original_tool, original_model. Returns: result
llm_researchA
Search-augmented research query — routes to Perplexity for web-grounded answers.
Best for: fact-checking, current events, finding sources, market research.
Args: prompt: The research question. system_prompt: Optional system instructions. max_tokens: Maximum output tokens. context: Optional conversation context to help the model understand the broader task.
Inputs: prompt (required), context, max_tokens, system_prompt. Returns: result
llm_routeA
Smart router — classifies task complexity, then routes to the optimal external LLM.
Uses a cheap classifier to assess complexity, then picks the right model tier:
simple → budget models (Gemini Flash, GPT-4o-mini)
moderate → balanced models (GPT-4o, Sonnet, Gemini Pro)
complex → premium models (o3, Opus)
For routing to Claude Code's own models (haiku/sonnet) without API keys, use llm_classify instead and follow its recommendation.
Args: prompt: The task or question to route. task_type: Optional hint — "query", "research", "generate", "analyze", "code". Auto-detected if omitted. complexity_override: Skip classification — force "simple", "moderate", or "complex". system_prompt: Optional system instructions. temperature: Sampling temperature (0.0-2.0). max_tokens: Maximum output tokens. context: Optional conversation context to help the model understand the broader task.
Inputs: prompt (required), context, task_type, max_tokens, +3 more. Returns: result
llm_save_sessionA
Summarize and save the current session for cross-session context.
Uses a cheap model to generate a compact summary of the session's exchanges, then persists it to SQLite. Future routed calls will include this summary as context, giving external models awareness of prior work.
Call this before ending a session or when switching to a different task. Sessions with fewer than 3 exchanges are skipped.
Inputs: no named parameters. Returns: result
llm_savingsA
Show time-bucketed savings dashboard: today / this week / this month / all-time.
Displays actual spend vs Sonnet baseline and the efficiency multiplier (Nx) for each period. Use this to understand the real dollar value routing provides.
Returns: Formatted savings table with efficiency multiplier.
Inputs: no named parameters. Returns: result
llm_select_agentA
Classify a task prompt and return the recommended agent CLI + model for session-level routing.
Use this BEFORE starting a Claude Code / Codex / Gemini CLI session to pick the right agent runtime for the task. This is session-level routing — it selects which agent to invoke, not which model to call mid-session.
Decision tree (profile × complexity): budget + simple/moderate → codex + gpt-4o-mini budget + complex → codex + gpt-4o (Codex handles most coding; escalate if needed) balanced + simple → codex + gpt-4o-mini balanced + moderate → claude_code + sonnet balanced + complex → claude_code + opus premium + any → claude_code + opus
Returns JSON with: primary — agent binary name: "claude_code" | "codex" | "gemini_cli" primary_model — model flag value (pass via -m or --model) fallback — fallback agent if primary unavailable fallback_model — model for fallback task_type — classified task type (code / analyze / generate / research / query) complexity — simple | moderate | complex confidence — classifier confidence 0–1 reason — one-line classification rationale env_check — dict of required env vars and whether they're set
Args: prompt: The task description to classify (same text you'd pass to the agent). profile: Routing profile — "budget", "balanced", or "premium" (default: "balanced").
Inputs: prompt (required), profile. Returns: result
llm_session_spendA
Show real-time session cost breakdown.
Reports spend accumulated since this session started, broken down by model and tool. Fires an anomaly warning if spend exceeds the configured threshold (default $0.50) in under 10 minutes.
Returns a formatted summary with per-model costs and anomaly status.
Inputs: no named parameters. Returns: result
llm_set_profileB
Switch the active routing profile.
Args: profile: One of "budget", "balanced", or "premium".
Inputs: profile (required). Returns: result
llm_setupA
Set up and manage API providers, hooks, and routing enforcement.
Actions:
"status": Show which providers are configured and which are missing
"guide": Step-by-step guide to add recommended free/cheap providers
"discover": Scan for existing API keys in environment (safe, read-only)
"add": Add an API key for a provider (writes to .env file securely)
"test": Validate API keys with a minimal call (tests configured or specific provider)
"provider": Show details about a specific provider
"install_hooks": Install auto-routing hooks globally (every Claude Code session)
"uninstall_hooks": Remove auto-routing hooks
Args: action: What to do — "status", "guide", "discover", "add", "test", "provider", "install_hooks", or "uninstall_hooks". provider: Provider name (for "add", "test", and "provider" actions). api_key: API key value (for "add" action only). Key is validated before saving.
Inputs: action, api_key, provider. Returns: result
llm_streamA
Stream an LLM response for long-running tasks — shows output as it arrives.
Uses the same routing logic as llm_route but streams chunks instead of waiting for the full response. Ideal for long-form generation, research summaries, or any task where seeing partial output early is valuable.
Args: prompt: The task or question to stream. task_type: Task type hint — "query", "research", "generate", "analyze", "code". model: Optional model override (e.g. "openai/gpt-4o", "gemini/gemini-2.5-flash"). system_prompt: Optional system instructions. temperature: Sampling temperature (0.0-2.0). max_tokens: Maximum output tokens.
Inputs: prompt (required), model, task_type, max_tokens, +2 more. Returns: result
llm_team_pushA
Push the team savings report to the configured notification channel.
Sends a formatted message to the endpoint set by LLM_ROUTER_TEAM_ENDPOINT.
Channel is auto-detected from the URL:
hooks.slack.com → Slack Block Kit message
discord.com/api/webhooks → Discord Embed
api.telegram.org/bot* → Telegram MarkdownV2 message
anything else → Generic JSON POST
Args:
period: "today", "week", "month", or "all".
Inputs: period. Returns: result
llm_team_reportA
Show a team savings report for the current user and project.
Displays call counts, cost savings, free-tier usage, and top models, broken down for the auto-detected user (git email) and project (git remote).
Args:
period: "today", "week", "month", or "all".
Inputs: period. Returns: result
llm_track_usageA
Report Claude Code model token usage for budget tracking.
Call this after using an Agent with haiku/sonnet to track token consumption against the daily budget. This enables progressive model downshifting. Shows per-call savings vs opus and cumulative session savings.
Args: model: The Claude model used — "haiku", "sonnet", or "opus". tokens_used: Approximate tokens consumed by the Agent call. complexity: The task complexity that was routed — "simple", "moderate", "complex".
Inputs: model (required), tokens_used (required), complexity. Returns: result
llm_update_usageA
Update cached Claude usage from the JSON API response.
Call this with the result from browser_evaluate(FETCH_USAGE_JS). Accepts the full JSON object from the claude.ai internal API.
The cached data is used by llm_classify for real budget pressure instead of token-based estimates.
Args: data: JSON response from the claude.ai usage API (via browser_evaluate).
Inputs: data (required). Returns: result
llm_usageA
Unified usage dashboard — Claude subscription, Codex, external APIs, and savings.
Shows a complete picture of all LLM usage across all providers in one view.
Args: period: Time period — "today", "week", "month", or "all".
Inputs: period. Returns: result
llm_videoB
Generate a video — routes to Gemini Veo, Runway, Kling, or other video models.
Args: prompt: Description of the video to generate. model: Optional model override (e.g. "gemini/veo-2", "runway/gen3a_turbo", "fal/kling-video"). duration: Video duration in seconds (default: 5).
Inputs: prompt (required), model, duration. Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 60 tools
Many tools have overlapping purposes, e.g., llm_route, llm_auto, llm_query, llm_code, llm_generate, llm_analyze, llm_research all route tasks to LLMs based on complexity or task type. Additionally, multiple savings/usage tools (llm_savings, llm_gain, llm_digest, llm_team_report, llm_team_push, llm_session_spend) create confusion. While descriptions differentiate them, the sheer number of similar tools makes it hard for an agent to select the correct one.
The vast majority of tools follow a consistent `llm_<verb>_<noun>` or `llm_<noun>` pattern in snake_case. The five `agoragentic_*` tools are a separate prefix but still consistent within their own domain. Minor inconsistency: some tools use verb+noun (e.g., llm_check_usage, llm_set_profile) while others are just noun (llm_health, llm_budget). Overall, the pattern is clear and predictable.
With 60 tools, the server is severely over-scoped for an MCP server. A typical well-coherent server has 3–15 tools; this has 60, many of which are redundant or could be consolidated (e.g., multiple savings report tools, multiple file system helpers). The high count overwhelms the agent and reduces coherence.
The tool set covers an exceptionally broad domain: task routing, classification, evaluation, savings tracking, profile management, file system operations, orchestration, media generation, setup, health checks, and team collaboration. Few obvious gaps exist; almost any operation related to LLM routing is present. The only minor omission is perhaps a direct tool for model comparison or A/B testing, but overall completeness is high.
Maintenance
Related MCP Connectors
One API key for every AI model, routed to the cheapest provider. OpenAI-compatible.
AI model routing on your own vendor keys: pick the best model per prompt, or route and run it.
Real-time, drift-verified LLM pricing across 31 providers with cost+quality model routing.
AI routing, memory, guardrails, and governance. Routes across Claude, GPT, Gemini.
Related MCP Servers
- AlicenseCqualityDmaintenanceAn AI router that connects applications to multiple LLM providers (OpenAI, Anthropic, Google, DeepSeek, Ollama, etc.) with smart model orchestration capabilities, enabling dynamic switching between models for different reasoning tasks.341MIT
- -licenseNot gradedqualityNot gradedmaintenanceIntelligent routing service that selects optimal AI models based on capability requirements and normalizes input/output formats across multiple providers like OpenAI, Anthropic, Google, and others.-
- FlicenseNot gradedqualityDmaintenanceAutomatically routes queries to the most suitable AI model based on task type, cost constraints, and performance needs, supporting multiple providers and customizable priorities.-
- AlicenseBqualityDmaintenanceRoute prompts intelligently across Claude, Gemini, and GPT-4o, automatically picking the best model for every task while minimizing token cost.532 npmMIT