[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"similar-ulab-uiuc--LLMRouter":3,"tool-ulab-uiuc--LLMRouter":62},[4,18,26,36,46,54],{"id":5,"name":6,"github_repo":7,"description_zh":8,"stars":9,"difficulty_score":10,"last_commit_at":11,"category_tags":12,"status":17},4358,"openclaw","openclaw\u002Fopenclaw","OpenClaw 是一款专为个人打造的本地化 AI 助手，旨在让你在自己的设备上拥有完全可控的智能伙伴。它打破了传统 AI 助手局限于特定网页或应用的束缚，能够直接接入你日常使用的各类通讯渠道，包括微信、WhatsApp、Telegram、Discord、iMessage 等数十种平台。无论你在哪个聊天软件中发送消息，OpenClaw 都能即时响应，甚至支持在 macOS、iOS 和 Android 设备上进行语音交互，并提供实时的画布渲染功能供你操控。\n\n这款工具主要解决了用户对数据隐私、响应速度以及“始终在线”体验的需求。通过将 AI 部署在本地，用户无需依赖云端服务即可享受快速、私密的智能辅助，真正实现了“你的数据，你做主”。其独特的技术亮点在于强大的网关架构，将控制平面与核心助手分离，确保跨平台通信的流畅性与扩展性。\n\nOpenClaw 非常适合希望构建个性化工作流的技术爱好者、开发者，以及注重隐私保护且不愿被单一生态绑定的普通用户。只要具备基础的终端操作能力（支持 macOS、Linux 及 Windows WSL2），即可通过简单的命令行引导完成部署。如果你渴望拥有一个懂你",349277,3,"2026-04-06T06:32:30",[13,14,15,16],"Agent","开发框架","图像","数据工具","ready",{"id":19,"name":20,"github_repo":21,"description_zh":22,"stars":23,"difficulty_score":10,"last_commit_at":24,"category_tags":25,"status":17},3808,"stable-diffusion-webui","AUTOMATIC1111\u002Fstable-diffusion-webui","stable-diffusion-webui 是一个基于 Gradio 构建的网页版操作界面，旨在让用户能够轻松地在本地运行和使用强大的 Stable Diffusion 图像生成模型。它解决了原始模型依赖命令行、操作门槛高且功能分散的痛点，将复杂的 AI 绘图流程整合进一个直观易用的图形化平台。\n\n无论是希望快速上手的普通创作者、需要精细控制画面细节的设计师，还是想要深入探索模型潜力的开发者与研究人员，都能从中获益。其核心亮点在于极高的功能丰富度：不仅支持文生图、图生图、局部重绘（Inpainting）和外绘（Outpainting）等基础模式，还独创了注意力机制调整、提示词矩阵、负向提示词以及“高清修复”等高级功能。此外，它内置了 GFPGAN 和 CodeFormer 等人脸修复工具，支持多种神经网络放大算法，并允许用户通过插件系统无限扩展能力。即使是显存有限的设备，stable-diffusion-webui 也提供了相应的优化选项，让高质量的 AI 艺术创作变得触手可及。",162132,"2026-04-05T11:01:52",[14,15,13],{"id":27,"name":28,"github_repo":29,"description_zh":30,"stars":31,"difficulty_score":32,"last_commit_at":33,"category_tags":34,"status":17},1381,"everything-claude-code","affaan-m\u002Feverything-claude-code","everything-claude-code 是一套专为 AI 编程助手（如 Claude Code、Codex、Cursor 等）打造的高性能优化系统。它不仅仅是一组配置文件，而是一个经过长期实战打磨的完整框架，旨在解决 AI 代理在实际开发中面临的效率低下、记忆丢失、安全隐患及缺乏持续学习能力等核心痛点。\n\n通过引入技能模块化、直觉增强、记忆持久化机制以及内置的安全扫描功能，everything-claude-code 能显著提升 AI 在复杂任务中的表现，帮助开发者构建更稳定、更智能的生产级 AI 代理。其独特的“研究优先”开发理念和针对 Token 消耗的优化策略，使得模型响应更快、成本更低，同时有效防御潜在的攻击向量。\n\n这套工具特别适合软件开发者、AI 研究人员以及希望深度定制 AI 工作流的技术团队使用。无论您是在构建大型代码库，还是需要 AI 协助进行安全审计与自动化测试，everything-claude-code 都能提供强大的底层支持。作为一个曾荣获 Anthropic 黑客大奖的开源项目，它融合了多语言支持与丰富的实战钩子（hooks），让 AI 真正成长为懂上",160784,2,"2026-04-19T11:32:54",[14,13,35],"语言模型",{"id":37,"name":38,"github_repo":39,"description_zh":40,"stars":41,"difficulty_score":42,"last_commit_at":43,"category_tags":44,"status":17},8272,"opencode","anomalyco\u002Fopencode","OpenCode 是一款开源的 AI 编程助手（Coding Agent），旨在像一位智能搭档一样融入您的开发流程。它不仅仅是一个代码补全插件，而是一个能够理解项目上下文、自主规划任务并执行复杂编码操作的智能体。无论是生成全新功能、重构现有代码，还是排查难以定位的 Bug，OpenCode 都能通过自然语言交互高效完成，显著减少开发者在重复性劳动和上下文切换上的时间消耗。\n\n这款工具专为软件开发者、工程师及技术研究人员设计，特别适合希望利用大模型能力来提升编码效率、加速原型开发或处理遗留代码维护的专业人群。其核心亮点在于完全开源的架构，这意味着用户可以审查代码逻辑、自定义行为策略，甚至私有化部署以保障数据安全，彻底打破了传统闭源 AI 助手的“黑盒”限制。\n\n在技术体验上，OpenCode 提供了灵活的终端界面（Terminal UI）和正在测试中的桌面应用程序，支持 macOS、Windows 及 Linux 全平台。它兼容多种包管理工具，安装便捷，并能无缝集成到现有的开发环境中。无论您是追求极致控制权的资深极客，还是渴望提升产出的独立开发者，OpenCode 都提供了一个透明、可信",144296,1,"2026-04-16T14:50:03",[13,45],"插件",{"id":47,"name":48,"github_repo":49,"description_zh":50,"stars":51,"difficulty_score":32,"last_commit_at":52,"category_tags":53,"status":17},2271,"ComfyUI","Comfy-Org\u002FComfyUI","ComfyUI 是一款功能强大且高度模块化的视觉 AI 引擎，专为设计和执行复杂的 Stable Diffusion 图像生成流程而打造。它摒弃了传统的代码编写模式，采用直观的节点式流程图界面，让用户通过连接不同的功能模块即可构建个性化的生成管线。\n\n这一设计巧妙解决了高级 AI 绘图工作流配置复杂、灵活性不足的痛点。用户无需具备编程背景，也能自由组合模型、调整参数并实时预览效果，轻松实现从基础文生图到多步骤高清修复等各类复杂任务。ComfyUI 拥有极佳的兼容性，不仅支持 Windows、macOS 和 Linux 全平台，还广泛适配 NVIDIA、AMD、Intel 及苹果 Silicon 等多种硬件架构，并率先支持 SDXL、Flux、SD3 等前沿模型。\n\n无论是希望深入探索算法潜力的研究人员和开发者，还是追求极致创作自由度的设计师与资深 AI 绘画爱好者，ComfyUI 都能提供强大的支持。其独特的模块化架构允许社区不断扩展新功能，使其成为当前最灵活、生态最丰富的开源扩散模型工具之一，帮助用户将创意高效转化为现实。",109154,"2026-04-18T11:18:24",[14,15,13],{"id":55,"name":56,"github_repo":57,"description_zh":58,"stars":59,"difficulty_score":32,"last_commit_at":60,"category_tags":61,"status":17},6121,"gemini-cli","google-gemini\u002Fgemini-cli","gemini-cli 是一款由谷歌推出的开源 AI 命令行工具，它将强大的 Gemini 大模型能力直接集成到用户的终端环境中。对于习惯在命令行工作的开发者而言，它提供了一条从输入提示词到获取模型响应的最短路径，无需切换窗口即可享受智能辅助。\n\n这款工具主要解决了开发过程中频繁上下文切换的痛点，让用户能在熟悉的终端界面内直接完成代码理解、生成、调试以及自动化运维任务。无论是查询大型代码库、根据草图生成应用，还是执行复杂的 Git 操作，gemini-cli 都能通过自然语言指令高效处理。\n\n它特别适合广大软件工程师、DevOps 人员及技术研究人员使用。其核心亮点包括支持高达 100 万 token 的超长上下文窗口，具备出色的逻辑推理能力；内置 Google 搜索、文件操作及 Shell 命令执行等实用工具；更独特的是，它支持 MCP（模型上下文协议），允许用户灵活扩展自定义集成，连接如图像生成等外部能力。此外，个人谷歌账号即可享受免费的额度支持，且项目基于 Apache 2.0 协议完全开源，是提升终端工作效率的理想助手。",100752,"2026-04-10T01:20:03",[45,13,15,14],{"id":63,"github_repo":64,"name":65,"description_en":66,"description_zh":67,"ai_summary_zh":67,"readme_en":68,"readme_zh":69,"quickstart_zh":70,"use_case_zh":71,"hero_image_url":72,"owner_login":73,"owner_name":74,"owner_avatar_url":75,"owner_bio":76,"owner_company":77,"owner_location":77,"owner_email":77,"owner_twitter":78,"owner_website":77,"owner_url":79,"languages":80,"stars":93,"forks":94,"last_commit_at":95,"license":96,"difficulty_score":32,"env_os":97,"env_gpu":98,"env_ram":97,"env_deps":99,"category_tags":107,"github_topics":77,"view_count":32,"oss_zip_url":77,"oss_zip_packed_at":77,"status":17,"created_at":108,"updated_at":109,"faqs":110,"releases":111},9664,"ulab-uiuc\u002FLLMRouter","LLMRouter","LLMRouter: An Open-Source Library for LLM Routing","LLMRouter 是一款智能开源库，旨在优化大语言模型（LLM）的推理过程。它的核心功能是充当“交通指挥员”，根据用户提问的复杂度、成本预算及性能需求，动态自动地将任务分配给最合适的模型。这一机制有效解决了单一模型难以兼顾所有场景的痛点：既避免了简单任务浪费昂贵算力，又确保复杂难题能获得最强模型的支持，从而在成本控制与回答质量之间找到最佳平衡点。\n\n该工具特别适合 AI 开发者、研究人员以及需要部署高效模型服务的企业团队使用。其技术亮点在于提供了极其丰富的路由策略库，内置超过 16 种路由模型，涵盖从基础的机器学习算法到先进的代理式（Agentic）和个性化路由方案。此外，LLMRouter 还配备了统一命令行界面、基于 Gradio 的交互组件以及完整的数据生成流水线，甚至支持通过 ComfyUI 进行可视化流程构建。无论是希望深入研究路由算法的学者，还是寻求在生产环境中降低 API 成本的工程师，都能利用它轻松构建灵活、高效的智能模型调度系统。","\u003Cdiv align=\"center\">\n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fulab-uiuc_LLMRouter_readme_30b3b7ec022d.png\" alt=\"LLMRouter Logo\" width=\"200\">\n\u003C\u002Fdiv>\n\n\u003Ch1 align=\"center\">🚀 LLMRouter: An Open-Source Library for LLM Routing\u003C\u002Fh1>\n\n\n\u003Cdiv align=\"center\">\n  \u003Cp>\n    \u003Ca href=\"https:\u002F\u002Fwww.python.org\u002Fdownloads\u002Frelease\u002Fpython-3109\u002F\">\u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FPYTHON-3.10-3776AB?style=for-the-badge&logo=python&logoColor=white\" alt=\"Python\">\u003C\u002Fa>\n    \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Fulab-uiuc\u002FLLMRouter\u002Fpulls\">\u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FPRS-WELCOME-orange?style=for-the-badge\" alt=\"PRs\">\u003C\u002Fa>\n    \u003Ca href=\"https:\u002F\u002Fjoin.slack.com\u002Ft\u002Fllmrouteropen-ri04588\u002Fshared_invite\u002Fzt-3mkx82cut-A25v5yR52xVKi7_jm_YK_w\">\u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FSLACK-JOIN%20US-4A154B?style=for-the-badge&logo=slack&logoColor=white\" alt=\"Slack\">\u003C\u002Fa>\n    \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Fulab-uiuc\u002FLLMRouter\u002Fissues\u002F136\">\u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002F💬WeChat-Group-07c160?style=for-the-badge&logo=wechat&logoColor=white&labelColor=1a1a2e\">\u003C\u002Fa>\n    \u003Ca href=\"https:\u002F\u002Fulab-uiuc.github.io\u002FLLMRouter\u002F\" style=\"text-decoration:none;\">\u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FDOCS-ONLINE-0A9EDC?style=for-the-badge&logo=readthedocs&logoColor=white\" alt=\"Docs\">\u003C\u002Fa>\n    \u003Ca href=\"https:\u002F\u002Fx.com\u002Fyoujiaxuan\u002Fstatus\u002F2005877938554589370\" style=\"text-decoration:none;\">\u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FTWITTER-ANNOUNCEMENTS-1DA1F2?style=for-the-badge&logo=x&logoColor=white\" alt=\"Twitter\">\u003C\u002Fa>\n    \u003Ca href=\"LICENSE\">\u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FLICENSE-MIT-2EA44F?style=for-the-badge\" alt=\"License\">\u003C\u002Fa>\n  \u003C\u002Fp>\n\u003C\u002Fdiv>\n\n\n\n\n## ✨ Introduction\n\n\u003Cdiv align=\"center\">\n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fulab-uiuc_LLMRouter_readme_089cbd02a8ed.png\" alt=\"LLMRouter Overview\" style=\"width: 100%; max-width: 1000px;\">\n\u003C\u002Fdiv>\n\n\n**LLMRouter** is an intelligent routing system designed to optimize LLM inference by dynamically selecting the most suitable model for each query. To achieve intelligent routing, it defines:\n\n1. 🚀 *Smart Routing*: Automatically routes queries to the optimal LLM based on task complexity, cost, and performance requirements.\n2. 📊 *Multiple Router Models*: Support for **over 16 routing models**, organized into four major categories—**single-round routers, multi-round routers, agentic routers, and personalized routers**—covering a wide range of strategies such as KNN, SVM, MLP, Matrix Factorization, Elo Rating, graph-based routing, BERT-based routing, hybrid probabilistic methods, transformed-score routers, and more.\n3. 🛠️ *Unified CLI*: Complete command-line interface for training, inference, and interactive chat with Gradio-based UI.\n4. 📈 *Data Generation Pipeline*: Complete pipeline for generating training data from 11 benchmark datasets with automatic API calling and evaluation.\n\n## 📰 News\n\n- 🖥️ **[2026-02]**: **ComfyUI Interface** - We've released the visual interface for LLMRouter! Now you can visually construct data generation and routing pipelines, drag-and-drop nodes to train routers, and monitor performance in real-time. See [ComfyUI Interface](#-comfyui-interface) for details.\n\n- 🔗 **[2026-02]**: **OpenClaw Router** - OpenAI-compatible server with OpenClaw integration! We've also released llmrouter-lib v0.3.1. Deploy LLMRouter as a production API server that works seamlessly with Slack, Discord, and other messaging platforms via [OpenClaw](https:\u002F\u002Fgithub.com\u002Fopenclaw\u002Fopenclaw). Features include multimodal understanding (image\u002Faudio\u002Fvideo), retrieval-augmented routing memory, streaming support, and all 16+ LLMRouter routing strategies. See [OpenClaw Router Integration](#-openclaw-router-openclaw-integration). For deployment with social platforms like Slack, refer to the [Getting Started Guide](https:\u002F\u002Fwww.moltcn.com\u002Fstart\u002Fgetting-started.html) for step-by-step setup instructions.\n\n- ⭐ **[2026-01]**: **LLMRouter** just crossed 1K GitHub stars! We've also released llmrouter-lib v0.2.0. Updates include service-specific dict configs (OpenAI, Anthropic, etc.) and multimodal routing (Video\u002FImage + Text) on Geometry3K, MathVista, and Charades-Ego—all in the first unified open-source LLM routing library with 16+ routers, a unified CLI, Gradio UI, and 11 datasets. Install via pip install llmrouter-lib. More updates soon! 🚀\n\n- 🚀 **[2025-12]**: **LLMRouter** is officially released - ship smarter 🧠, cost-aware 💸 LLM routing with 16+ routers 🧭, a unified `llmrouter` CLI 🛠️, and a plugin workflow for custom routers 🧩.\n\n## 🔗 Links\n\n- [Supported Routers](#-supported-routers)\n- [Installation](#installation)\n- [Use Your Own Dataset](#-preparing-training-data)\n- [Training a Router](#training-a-router)\n- [Running Inference via a Router](#running-inference)\n- [Interactive Chat Interface with a Router](#interactive-chat-interface)\n- [ComfyUI Interface](#-comfyui-interface)\n- [Creating Your Own Routers](#-creating-your-own-routers)\n- [Adding Your Own Tasks](#-adding-your-own-tasks)\n- [OpenClaw Router (OpenClaw Integration)](#-openclaw-router-openclaw-integration)\n- [Acknowledgments](#-acknowledgments)\n- [Citation](#-citation)\n\n## 🧭 Supported Routers\n\n### Single-Round Routers\n| Router | Training | Inference | Description | Tutorial |\n|--------|:--------:|:---------:|-------------|:--------:|\n| `knnrouter` | ✅ | ✅ | K-Nearest Neighbors based routing | [📖](llmrouter\u002Fmodels\u002Fknnrouter\u002FREADME.md) |\n| `svmrouter` | ✅ | ✅ | Support Vector Machine based routing | [📖](llmrouter\u002Fmodels\u002Fsvmrouter\u002FREADME.md) |\n| `mlprouter` | ✅ | ✅ | Multi-Layer Perceptron based routing | [📖](llmrouter\u002Fmodels\u002Fmlprouter\u002FREADME.md) |\n| `mfrouter` | ✅ | ✅ | Matrix Factorization based routing | [📖](llmrouter\u002Fmodels\u002Fmfrouter\u002FREADME.md) |\n| `elorouter` | ✅ | ✅ | Elo Rating based routing | [📖](llmrouter\u002Fmodels\u002Felorouter\u002FREADME.md) |\n| `routerdc` | ✅ | ✅ | Dual Contrastive learning based routing | [📖](llmrouter\u002Fmodels\u002Frouterdc\u002FREADME.md) |\n| `automix` | ✅ | ✅ | Automatic model mixing | [📖](llmrouter\u002Fmodels\u002Fautomix\u002FREADME.md) |\n| `hybrid_llm` | ✅ | ✅ | Hybrid LLM routing strategy | [📖](llmrouter\u002Fmodels\u002Fhybrid_llm\u002FREADME.md) |\n| `graphrouter` | ✅ | ✅ | Graph-based routing | [📖](llmrouter\u002Fmodels\u002Fgraphrouter\u002FREADME.md) |\n| `causallm_router` | ✅ | ✅ | Causal Language Model router | [📖](llmrouter\u002Fmodels\u002Fcausallm_router\u002FREADME.md) |\n| `smallest_llm` | N\u002FA | ✅ | Always routes to smallest model | [📖](llmrouter\u002Fmodels\u002Fsmallest_llm\u002FREADME.md) |\n| `largest_llm` | N\u002FA | ✅ | Always routes to largest model | [📖](llmrouter\u002Fmodels\u002Flargest_llm\u002FREADME.md) |\n\n### Multi-Round Routers\n| Router | Training | Inference | Description | Tutorial |\n|--------|:--------:|:---------:|-------------|:--------:|\n| `router_r1` | [LINK](https:\u002F\u002Fgithub.com\u002Fulab-uiuc\u002FRouter-R1) | ✅ | Pre-trained Router-R1 model for multi-turn conversations | [📖](llmrouter\u002Fmodels\u002Frouter_r1\u002FREADME.md) |\n\n### Personalized Routers\n| Router | Training | Inference | Description | Tutorial |\n|--------|:--------:|:---------:|-------------|:--------:|\n| `gmtrouter` | ✅ | ✅ | Graph-based personalized router with user preference learning | [📖](llmrouter\u002Fmodels\u002Fgmtrouter\u002FREADME.md) |\n| `personalizedrouter` | ✅ | ✅ | GNN-based personalized router with user features | [📖](llmrouter\u002Fmodels\u002Fpersonalizedrouter\u002FREADME.md) |\n\n### Agentic Routers\n| Router | Training | Inference | Description | Tutorial |\n|--------|:--------:|:---------:|-------------|:--------:|\n| `knnmultiroundrouter` | ✅ | ✅ | KNN-based agentic router for complex tasks | [📖](llmrouter\u002Fmodels\u002Fknnmultiroundrouter\u002FREADME.md) |\n| `llmmultiroundrouter` | N\u002FA | ✅ | LLM-based agentic router for complex tasks | [📖](llmrouter\u002Fmodels\u002Fllmmultiroundrouter\u002FREADME.md) |\n\n## 🚀 Get Started\n\n### Installation\n\n#### Install from source\n\nClone the repository and install in editable mode using a virtual environment (e.g., with anaconda3):\n\n```bash\n# Clone the repository\ngit clone https:\u002F\u002Fgithub.com\u002Fulab-uiuc\u002FLLMRouter.git\ncd LLMRouter\n\n# Create and activate virtual environment\nconda create -n llmrouter python=3.10\nconda activate llmrouter\n\n# Install the package (base installation)\npip install -e .\n\n# Optional: Install with RouterR1 support (requires GPU)\n# RouterR1 is tested with vllm==0.6.3 (torch==2.4.0); the extra pins these versions.\npip install -e \".[router-r1]\"\n\n# Optional: Install all optional dependencies\npip install -e \".[all]\"\n```\n\n#### Install from PyPI\n\n```bash\npip install llmrouter-lib\n```\n\n### 🔑 Setting Up API Keys\n\nLLMRouter requires API keys to make LLM API calls for inference, chat, and data generation. Set the `API_KEYS` environment variable using one of the following formats:\n\n> 💡 **Free NVIDIA API Keys**: The NVIDIA endpoints currently used in LLMRouter have freely available API keys. To get started, visit [https:\u002F\u002Fbuild.nvidia.com\u002F](https:\u002F\u002Fbuild.nvidia.com\u002F) to create an account, then you can generate your API keys at no cost.\n\n#### **Service-Specific Dict Format** (recommended for multiple providers)\n\nUse this format when you have models from different service providers (e.g., NVIDIA, OpenAI, Anthropic) and want to use different API keys for each provider:\n\n```bash\nexport API_KEYS='{\"NVIDIA\": \"nvidia-key-1,nvidia-key-2\", \"OpenAI\": [\"openai-key-1\", \"openai-key-2\"], \"Anthropic\": \"anthropic-key-1\"}'\n```\n\n**Dict Format Details:**\n- **Keys**: Service provider names (must match the `service` field in your LLM candidate JSON)\n- **Values**: Can be:\n  - Comma-separated string: `\"key1,key2,key3\"`\n  - JSON array: `[\"key1\", \"key2\", \"key3\"]`\n  - Single string: `\"key1\"`\n- **Service Matching**: The system automatically matches the `service` field from your LLM candidate JSON to select the appropriate API keys\n- **Round-Robin**: Each service maintains its own round-robin counter for load balancing\n- **Error Handling**: If a service is not found in the dict, a clear error message will be raised with available services listed\n\n**Example LLM Candidate JSON with service field:**\n```json\n{\n  \"qwen2.5-7b-instruct\": {\n    \"service\": \"NVIDIA\",\n    \"model\": \"qwen\u002Fqwen2.5-7b-instruct\",\n    \"api_endpoint\": \"https:\u002F\u002Fintegrate.api.nvidia.com\u002Fv1\"\n  },\n  \"gpt-4\": {\n    \"service\": \"OpenAI\",\n    \"model\": \"gpt-4\",\n    \"api_endpoint\": \"https:\u002F\u002Fapi.openai.com\u002Fv1\"\n  }\n}\n```\n\n#### **Legacy Formats** (for single provider or backward compatibility)\n\n**JSON Array Format** (for multiple keys from same provider):\n```bash\nexport API_KEYS='[\"your-key-1\", \"your-key-2\", \"your-key-3\"]'\n```\n\n**Comma-Separated Format** (alternative for multiple keys):\n```bash\nexport API_KEYS='key1,key2,key3'\n```\n\n**Single Key** (for one API key):\n```bash\nexport API_KEYS='your-api-key'\n```\n\n**Notes**: \n- API keys are used for **inference**, **chat interface**, and **data generation** (Step 3 of the pipeline)\n- Multiple keys enable automatic load balancing across API calls\n- When using **dict format**, ensure the `service` field in your LLM candidate JSON matches the keys in your `API_KEYS` dict\n- The environment variable must be set before running inference, chat, or data generation commands\n- For persistent setup, add the export command to your shell profile (e.g., `~\u002F.bashrc` or `~\u002F.zshrc`)\n\n### 🌐 Configuring API Endpoints\n\nAPI endpoints can be specified at two levels (resolved in priority order):\n\n1. **Per-Model** (highest priority): `api_endpoint` field in LLM candidate JSON (`default_llm.json`)\n2. **Router-Level** (fallback): `api_endpoint` field in router YAML config\n3. **Error**: Raises descriptive error if neither is specified\n\n**LLM Candidate JSON** (per-model endpoints):\n```json\n{\n  \"qwen2.5-7b-instruct\": {\n    \"model\": \"qwen\u002Fqwen2.5-7b-instruct\",\n    \"api_endpoint\": \"https:\u002F\u002Fintegrate.api.nvidia.com\u002Fv1\",\n    ...\n  },\n  \"custom-model\": {\n    \"model\": \"custom\u002Fmodel-name\",\n    \"api_endpoint\": \"https:\u002F\u002Fapi.customprovider.com\u002Fv1\",\n    ...\n  }\n}\n```\n\n**Router YAML** (default endpoint):\n```yaml\napi_endpoint: 'https:\u002F\u002Fintegrate.api.nvidia.com\u002Fv1'  # Fallback for all models\n```\n\n**Benefits**: Different models can use different providers; easy migration; backward compatible with router configs.\n\nFor details, see [Data Generation Pipeline documentation](llmrouter\u002Fdata\u002FREADME.md#llm-data-json-default_llmjson).\n\n### 🖥️ Using Local LLM Models\n\nLLMRouter supports locally hosted LLM inference servers that provide OpenAI-compatible APIs (e.g., Ollama, vLLM, SGLang). For local providers, you can use an empty string `\"\"` as the API key value - the system automatically detects localhost endpoints and handles authentication accordingly.\n\n**Example with Ollama:**\n\n```bash\nexport API_KEYS='{\"Ollama\": \"\"}'\n```\n\n```json\n{\n  \"gemma3\": {\n    \"size\": \"3B\",\n    \"feature\": \"Gemma 3B model hosted locally via Ollama\",\n    \"input_price\": 0.0,\n    \"output_price\": 0.0,\n    \"model\": \"gemma3\",\n    \"service\": \"Ollama\",\n    \"api_endpoint\": \"http:\u002F\u002Flocalhost:11434\u002Fv1\"\n  }\n}\n```\n\n**Important**: Use the `\u002Fv1` endpoint (OpenAI-compatible), not the native API endpoints. Empty strings are automatically detected for localhost endpoints (`localhost` or `127.0.0.1`).\n\n### 🧪 Testing Model Availability\n\nYou can test the availability of different candidate models using the following curl commands. This is useful for verifying that your API keys work correctly and that specific models are accessible:\n\n**Note**: If you're using the dict format for `API_KEYS`, extract the NVIDIA key first (e.g., using `echo $API_KEYS | python3 -c \"import sys, json; print(json.load(sys.stdin)['NVIDIA'].split(',')[0])\"`), or set a temporary variable with your NVIDIA API key.\n\n```bash\n# export API_KEYS=...\n\n# Example API endpoint - adjust based on your configuration\n# This example uses NVIDIA's endpoint, but you should use the endpoint\n# specified in your LLM candidate JSON or router config\nAPI_ENDPOINT=\"https:\u002F\u002Fintegrate.api.nvidia.com\u002Fv1\u002Fchat\u002Fcompletions\"\n\n# Example model list - adjust based on your LLM candidate configuration\n# These are example models; replace with the actual model names\u002FIDs\n# from your LLM candidate JSON file\nMODELS=(\n  \"qwen\u002Fqwen2.5-7b-instruct\"\n  \"meta\u002Fllama-3.1-8b-instruct\"\n  \"mistralai\u002Fmistral-7b-instruct-v0.3\"\n  \"nvidia\u002Fllama-3.3-nemotron-super-49b-v1\"\n  \"mistralai\u002Fmixtral-8x7b-instruct-v0.1\"\n  \"mistralai\u002Fmixtral-8x22b-instruct-v0.1\"\n)\n\nSYSTEM_PROMPT=\"Hello.\"\nPROMPT=\"Hello.\"\n\nfor MODEL in \"${MODELS[@]}\"; do\n  echo \"===== $MODEL =====\"\n\n  curl \"$API_ENDPOINT\" \\\n    -H \"Content-Type: application\u002Fjson\" \\\n    -H \"Authorization: Bearer $API_KEYS\" \\\n    -d \"{\n      \\\"model\\\": \\\"$MODEL\\\",\n      \\\"messages\\\": [\n        {\n          \\\"role\\\": \\\"system\\\",\n          \\\"content\\\": \\\"$SYSTEM_PROMPT\\\"\n        },\n        {\n          \\\"role\\\": \\\"user\\\",\n          \\\"content\\\": \\\"$PROMPT\\\"\n        }\n      ],\n      \\\"temperature\\\": 0.8,\n      \\\"max_tokens\\\": 200\n    }\"\n\n  echo\ndone\n```\n\nThis script will test each model in the list and display the response, helping you verify which models are available and working with your API key.\n\n\n\n### 📊 Preparing Training Data\n\nLLMRouter includes a complete data generation pipeline that transforms raw benchmark datasets into formatted routing data with embeddings. The pipeline supports 11 diverse benchmark datasets including Natural QA, Trivia QA, MMLU, GPQA, MBPP, HumanEval, GSM8K, CommonsenseQA, MATH, OpenbookQA, and ARC-Challenge.\n\n> 💡 **Multimodal Integration**: Learn how to incorporate complex multimodal tasks (Video\u002FImage + Text) into LLMRouter by checking our [Multimodal Task Guide](data\u002Fmultimodal_tasks\u002FREADME.md). We currently support 5 multimodal tasks across 3 datasets (Geometry3K, MathVista, Charades-Ego).\n\n#### Pipeline Overview\n\nThe data generation pipeline consists of three main steps:\n\n1. **Generate Query Data** - Extract queries from benchmark datasets and create train\u002Ftest split JSONL files\n2. **Generate LLM Embeddings** - Create embeddings for LLM candidates from their metadata\n3. **API Calling & Evaluation** - Call LLM APIs, evaluate responses, and generate unified embeddings + routing data\n\n#### Quick Start\n\n\nStart with the sample configuration file:\n\n```bash\n# Step 1: Generate query data\npython llmrouter\u002Fdata\u002Fdata_generation.py --config llmrouter\u002Fdata\u002Fsample_config.yaml\n\n# Step 2: Generate LLM embeddings\npython llmrouter\u002Fdata\u002Fgenerate_llm_embeddings.py --config llmrouter\u002Fdata\u002Fsample_config.yaml\n\n# Step 3: API calling & evaluation (requires API_KEYS - see \"Setting Up API Keys\" section above)\npython llmrouter\u002Fdata\u002Fapi_calling_evaluation.py --config llmrouter\u002Fdata\u002Fsample_config.yaml --workers 100\n```\n\n#### Output Files\n\nThe pipeline generates the following files:\n\n- **Query Data** (JSONL): `query_data_train.jsonl` and `query_data_test.jsonl` - Query data with train\u002Ftest split\n- **LLM Embeddings** (JSON): `default_llm_embeddings.json` - LLM metadata with embeddings\n- **Query Embeddings** (PyTorch): `query_embeddings_longformer.pt` - Unified embeddings for all queries\n- **Routing Data** (JSONL): `default_routing_train_data.jsonl` and `default_routing_test_data.jsonl` - Complete routing data with model responses, performance scores, and token usage\n\n**Example routing data entry:**\n```json\n{\n  \"task_name\": \"gsm8k\",\n  \"query\": \"Janet has 4 apples. She gives 2 to Bob. How many does she have left?\",\n  \"ground_truth\": \"2\",\n  \"metric\": \"GSM8K\",\n  \"model_name\": \"llama3-chatqa-1.5-8b\",\n  \"response\": \"Janet has 4 apples and gives 2 to Bob, so she has 4 - 2 = 2 apples left.\",\n  \"performance\": 1.0,\n  \"embedding_id\": 42,\n  \"token_num\": 453\n}\n```\n\n#### Configuration\n\nAll paths and parameters are controlled via YAML configuration. The sample config file (`llmrouter\u002Fdata\u002Fsample_config.yaml`) references the example data directory and can be used as-is or customized for your setup.\n\n**Note**: Step 3 requires API keys for calling LLM services. See the [Setting Up API Keys](#-setting-up-api-keys) section above for configuration details.\n\nFor complete documentation including detailed file formats, embedding mapping system, configuration options, and troubleshooting, see **[llmrouter\u002Fdata\u002FREADME.md](llmrouter\u002Fdata\u002FREADME.md)**.\n\n### Training a Router\n\nBefore training, ensure you have prepared your data using the [Data Generation Pipeline](#-preparing-training-data) or use the example data in `data\u002Fexample_data\u002F`.\n\nTrain various router models with your configuration:\n```bash\n# Train KNN router\nllmrouter train --router knnrouter --config configs\u002Fmodel_config_train\u002Fknnrouter.yaml\n\n# Train MLP router with GPU\nCUDA_VISIBLE_DEVICES=2 llmrouter train --router mlprouter --config configs\u002Fmodel_config_train\u002Fmlprouter.yaml --device cuda\n\n# Train MF router quietly\nCUDA_VISIBLE_DEVICES=1 llmrouter train --router mfrouter --config configs\u002Fmodel_config_train\u002Fmfrouter.yaml --device cuda --quiet\n```\n\n### Running Inference\n\nPerform inference with trained routers (requires API keys - see [Setting Up API Keys](#-setting-up-api-keys) section):\n```bash\n# Single query inference\nllmrouter infer --router knnrouter --config config.yaml --query \"What is machine learning?\"\n\n# Batch inference from file\nllmrouter infer --router knnrouter --config config.yaml --input queries.txt --output results.json\n\n# Route only (without calling LLM API - no API keys needed)\nllmrouter infer --router knnrouter --config config.yaml --query \"Hello\" --route-only\n\n# Custom generation parameters\nllmrouter infer --router knnrouter --config config.yaml --query \"Explain AI\" --temp 0.7 --max-tokens 2048 --verbose\n```\n\nInput file formats supported: `.txt` (one query per line), `.json` (list of strings or objects with `\"query\"` field), `.jsonl` (one JSON object per line).\n\n### Interactive Chat Interface\n\n\u003Cdiv style=\"text-align:center;\">\n    \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fulab-uiuc_LLMRouter_readme_8f3512362212.gif\" style=\"width: 100%; height: auto;\">\n\u003C\u002Fdiv>\n\n\u003Cp align=\"center\">\n    \u003Cstrong>📱 Quick Preview:\u003C\u002Fstrong> Animated overview of the LLMRouter chat interface showing real-time routing and model selection.\n\u003C\u002Fp>\n\n\u003Cdiv style=\"text-align:center;\">\n    \u003Cvideo width=\"100%\" controls style=\"max-width: 800px; height: auto;\">\n        \u003Csource src=\"assets\u002Fllmrouter_chat_demo.mov\" type=\"video\u002Fquicktime\">\n        Your browser does not support the video tag.\n    \u003C\u002Fvideo>\n\u003C\u002Fdiv>\n\nLaunch the chat interface (requires API keys - see [Setting Up API Keys](#-setting-up-api-keys) section):\n\n```bash\n# Basic chat interface\nllmrouter chat --router knnrouter --config config.yaml\n\n# Custom host and port\nllmrouter chat --router knnrouter --config config.yaml --host 0.0.0.0 --port 7860\n\n# With public sharing link\nllmrouter chat --router knnrouter --config config.yaml --share\n\n# Specify query mode\nllmrouter chat --router knnrouter --config config.yaml --mode full_context --top_k 5\n```\n\nQuery Modes:\n- `current_only`: Routes based on current query only (default)\n- `full_context`: Combines all chat history with current query\n- `retrieval`: Retrieves top-k similar historical queries for context\n\n### Direct Script Execution\n\nYou can also run the CLI scripts directly:\n```bash\n# Training\npython -m llmrouter.cli.router_train --router knnrouter --config config.yaml\n\n# Inference\npython -m llmrouter.cli.router_inference --router knnrouter --config config.yaml --query \"Hello\"\n\n# Chat\npython -m llmrouter.cli.router_chat --router knnrouter --config config.yaml\n```\n\n## 🎨 ComfyUI Interface\n\nLLMRouter offers a powerful **Visual Interface** via [ComfyUI](https:\u002F\u002Fgithub.com\u002FComfy-Org\u002FComfyUI), transforming how you interact with the routing pipeline. Instead of editing YAML files and running terminal scripts, you can drag, drop, and connect nodes to build your workflow.\n\n\u003Cdiv align=\"center\">\n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fulab-uiuc_LLMRouter_readme_fb5775136849.png\" alt=\"LLMRouter ComfyUI Interface\" width=\"100%\">\n\u003C\u002Fdiv>\n\n### Key Highlights\n\n- **Visual Configuration**: Forget complex YAML files and terminal scripts. Adjust parameters (e.g., sample size, model candidates) and select datasets directly on the canvas.\n- **End-to-End Automation**: Seamlessly link nodes to build a complete pipeline: Data Generation $\\to$ Router Training $\\to$ Evaluation.\n- **Real-Time Monitoring**: Track the status of query generation, embedding extraction, and model training with instant visual feedback.\n- **Modular Design**: Custom construct your pipeline by dragging, dropping, and connecting nodes for Datasets, LLMs, and Routers.\n\n### Installation & Setup\n\nPrerequisites: You must have [ComfyUI](https:\u002F\u002Fgithub.com\u002FComfy-Org\u002FComfyUI) installed.\n\nTo install the LLMRouter custom nodes, you need to create two symbolic links (soft links).\n\n#### 1. Link the Custom Nodes\nThis allows ComfyUI to load the LLMRouter Python backend logic in the ComfyUI \"Nodes\" category.\n\n```bash\nln -s \u002Fpath\u002Fto\u002FLLMRouter\u002FComfyUI \u002Fpath\u002Fto\u002FComfyUI\u002Fcustom_nodes\u002FLLMRouter\n```\n\n#### 2. Link the Workflow Example (Optional)\nThis allows you to see the pre-configured workflow in the ComfyUI \"Workflows\" category.\n\n```bash\nln -s \u002Fpath\u002Fto\u002FLLMRouter\u002FComfyUI\u002Fworkflows\u002Fllm_router_example.json \u002Fpath\u002Fto\u002FComfyUI\u002Fuser\u002Fdefault\u002Fworkflows\u002Fllm_router_example.json\n```\n\n#### 3. Running the Application\n\nTo start the ComfyUI server with the LLMRouter nodes:\n\n```bash\npython \u002Fpath\u002Fto\u002FComfyUI\u002Fmain.py\n```\n\n#### 4. Remote Access & Port Forwarding\n\nIf you are running ComfyUI on a remote server (e.g., a compute cluster) and wish to access the interface locally, you can use SSH tunneling. Once the tunnel is established, access the interface at `http:\u002F\u002F127.0.0.1:8188`.\n\n### Using the ComfyUI Interface\n\n#### Find the Nodes\nTo use the nodes:\n1.  Open the ComfyUI web interface.\n2.  Use the **Node Library** sidebar or **Right-click** on the canvas.\n3.  Navigate to the **`LLMRouter`** category.\n4.  You will find nodes organized by function:\n    - **Data**: `Select Datasets`, `Select LLMs`, `Generate Data`.\n    - **Single-Round**: `KNN Router`, `SVM Router`, `MLP Router`, etc.\n    - **Multi-Round \u002F Agentic**: Specialized routers for complex tasks.\n\n#### Load the Example\nTo use the ready-to-run example:\n1.  Click the **`Workflows`** tab.\n2.  Select **`llm_router_example.json`**.\n3.  This loads a complete pipeline.\n\n## 🔧 Creating Your Own Routers\n\nLLMRouter supports a **plugin system** that allows you to add custom router implementations without modifying the core codebase. This makes it easy to experiment with new routing strategies or domain-specific routers.\n\n### Quick Start\n\n**1. Create your router directory:**\n```bash\nmkdir -p custom_routers\u002Fmy_router\n```\n\n**2. Implement your router** (`custom_routers\u002Fmy_router\u002Frouter.py`):\n```python\nfrom llmrouter.models.meta_router import MetaRouter\nimport torch.nn as nn\n\nclass MyRouter(MetaRouter):\n    \"\"\"Your custom router implementation.\"\"\"\n\n    def __init__(self, yaml_path: str):\n        # Initialize with a model (can be nn.Identity() for simple routers)\n        model = nn.Identity()\n        super().__init__(model=model, yaml_path=yaml_path)\n\n        # Get available LLM names from config\n        self.llm_names = list(self.llm_data.keys())\n\n    def route_single(self, query_input: dict) -> dict:\n        \"\"\"Route a single query to the best LLM.\"\"\"\n        query = query_input['query']\n\n        # Your custom routing logic here\n        # Example: route based on query length\n        selected_llm = (self.llm_names[0] if len(query) \u003C 50\n                       else self.llm_names[-1])\n\n        return {\n            \"query\": query,\n            \"model_name\": selected_llm,\n            \"predicted_llm\": selected_llm,\n        }\n\n    def route_batch(self, batch: list) -> list:\n        \"\"\"Route multiple queries.\"\"\"\n        return [self.route_single(q) for q in batch]\n```\n\n**3. Create configuration** (`custom_routers\u002Fmy_router\u002Fconfig.yaml`):\n```yaml\ndata_path:\n  llm_data: 'data\u002Fexample_data\u002Fllm_candidates\u002Fdefault_llm.json'\n\nhparam:\n  # Your hyperparameters here\n\n# Optional: Default API endpoint (used as fallback if models don't specify their own)\n# Individual models can override this by specifying api_endpoint in the llm_data JSON file\napi_endpoint: 'https:\u002F\u002Fintegrate.api.nvidia.com\u002Fv1'\n```\n\n**4. Use your custom router** (same as built-in routers!):\n```bash\n# Inference\nllmrouter infer --router my_router \\\n  --config custom_routers\u002Fmy_router\u002Fconfig.yaml \\\n  --query \"What is machine learning?\"\n\n# List all routers (including custom ones)\nllmrouter list-routers\n```\n\n### Plugin Discovery\n\nCustom routers are automatically discovered from:\n- `.\u002Fcustom_routers\u002F` (recommended - project directory)\n- `~\u002F.llmrouter\u002Fplugins\u002F` (user home directory)\n- `$LLMROUTER_PLUGINS` environment variable (colon-separated paths)\n\n### Example Routers\n\nLLMRouter includes example custom routers you can learn from:\n\n**RandomRouter** - Simple baseline that randomly selects an LLM\n```bash\nllmrouter infer --router randomrouter \\\n  --config custom_routers\u002Frandomrouter\u002Fconfig.yaml \\\n  --query \"Hello world\"\n```\n\n**ThresholdRouter** - Advanced trainable router with difficulty estimation\n```bash\n# Train the router\nllmrouter train --router thresholdrouter \\\n  --config custom_routers\u002Fthresholdrouter\u002Fconfig.yaml\n\n# Use for inference\nllmrouter infer --router thresholdrouter \\\n  --config custom_routers\u002Fthresholdrouter\u002Fconfig.yaml \\\n  --query \"Explain quantum computing\"\n```\n\n### Documentation\n\nFor detailed guides on creating custom routers:\n- 📖 **Quick Start**: [custom_routers\u002FREADME.md](custom_routers\u002FREADME.md)\n- 📖 **Implementation Summary**: [CUSTOM_ROUTER_SUMMARY.md](CUSTOM_ROUTER_SUMMARY.md)\n\n### Common Routing Patterns\n\n**Rule-based routing:**\n```python\ndef route_single(self, query_input):\n    query = query_input['query'].lower()\n    if 'code' in query:\n        return {\"model_name\": \"code-specialist\"}\n    elif len(query) \u003C 50:\n        return {\"model_name\": \"small-fast-model\"}\n    else:\n        return {\"model_name\": \"large-capable-model\"}\n```\n\n**Embedding-based routing:**\n```python\nfrom llmrouter.utils import get_longformer_embedding\n\ndef route_single(self, query_input):\n    embedding = get_longformer_embedding(query_input['query'])\n    # Use embedding similarity to select best model\n    selected = self._find_best_model(embedding)\n    return {\"model_name\": selected}\n```\n\n**Cost-optimized routing:**\n```python\ndef route_single(self, query_input):\n    difficulty = self._estimate_difficulty(query_input)\n    # Select cheapest model that can handle the difficulty\n    for model_name, info in sorted(self.llm_data.items(),\n                                   key=lambda x: x[1]['cost']):\n        if info['capability'] >= difficulty:\n            return {\"model_name\": model_name}\n```\n\n## 📝 Adding Your Own Tasks\n\nLLMRouter supports **custom task definitions** that allow you to add new task types with custom prompt templates and evaluation metrics. Custom tasks are automatically discovered and integrated into the data generation and evaluation pipeline.\n\n### Quick Start\n\n**1. Create a task formatter** (`custom_tasks\u002Fmy_tasks.py`):\n```python\nfrom llmrouter.utils.prompting import register_prompt\nfrom llmrouter.prompts import load_prompt_template\n\n@register_prompt('my_task', default_metric='my_metric')\ndef format_my_task_prompt(sample_data):\n    system_prompt = load_prompt_template(\"task_my_task\")\n    user_query = f\"Question: {sample_data.get('query', '')}\"\n    return {\"system\": system_prompt, \"user\": user_query}\n```\n\n**2. Create a prompt template** (`custom_tasks\u002Ftask_prompts\u002Ftask_my_task.yaml`):\n```yaml\ntemplate: |\n  You are an expert at [task description]. [Instructions].\n```\n\n**3. Register a custom metric** (optional):\n```python\nfrom llmrouter.evaluation import evaluation_metric\n\n@evaluation_metric('my_metric')\ndef my_metric(prediction: str, ground_truth: str, **kwargs) -> float:\n    return 1.0 if prediction == ground_truth else 0.0\n```\n\n**4. Use your custom task:**\n```python\nimport custom_tasks.my_tasks  # Import triggers registration\n\nfrom llmrouter.utils import generate_task_query\nfrom llmrouter.utils.evaluation import calculate_task_performance\n\n# Generate prompt\nprompt = generate_task_query('my_task', {'query': '...'})\n\n# Evaluate (metric automatically inferred from task)\nscore = calculate_task_performance(\n    prediction=\"...\", \n    ground_truth=\"...\", \n    task_name=\"my_task\"\n)\n```\n\n### Documentation\n\nFor detailed guides on creating custom tasks:\n- 📖 **Complete Guide**: [custom_tasks\u002FREADME.md](custom_tasks\u002FREADME.md)\n\n### 🎥 Hands-on: Multi-View Video Tasks\n\nFollow our **step-by-step walkthrough** in the [Charades-Ego Integration Guide](data\u002Fcharades_ego\u002FREADME.md) to process paired egocentric videos, generate VLM-based features, and train routers for **Activity**, **Object**, and **Verb** recognition.\n\n## 🔌 OpenClaw Router (OpenClaw Integration)\n\n**OpenClaw Router** is an OpenAI-compatible API server that brings LLMRouter's intelligent routing to production environments. It integrates seamlessly with [OpenClaw](https:\u002F\u002Fgithub.com\u002Fopenclaw\u002Fopenclaw), enabling you to deploy LLM routing via Slack, Discord, and other messaging platforms.\n\n### Why OpenClaw Router?\n\n| Feature | Benefit |\n|---------|---------|\n| **OpenAI-Compatible API** | Drop-in replacement for any OpenAI client (`\u002Fv1\u002Fchat\u002Fcompletions`) |\n| **All Routing Strategies** | Use any of the 16+ LLMRouter strategies (KNN, SVM, MLP, LLM-based, etc.) |\n| **Multimodal Understanding** | Process images, audio, and video - convert to text for routing decisions |\n| **Routing Memory** | Persist query→model history; retrieve similar past routes for better decisions |\n| **Streaming Support** | Full streaming responses with optional `[model_name]` prefix |\n| **Multi-Provider** | Route to Together AI, NVIDIA, OpenAI, Anthropic, or local models |\n\n### Architecture\n\n```\n┌─────────────────┐     ┌──────────────────────┐     ┌─────────────────────┐\n│  Slack\u002FDiscord  │────▶│   OpenClaw Gateway   │────▶│   OpenClaw Router    │\n│  (Mobile\u002FWeb)   │     │   (Socket Mode)      │     │   (Port 8000)       │\n└─────────────────┘     └──────────────────────┘     └──────────┬──────────┘\n                                                                 │\n                        ┌────────────────────────────────────────┼────────────────────────────────────────┐\n                        │                                        │                                        │\n                        ▼                                        ▼                                        ▼\n              ┌─────────────────┐                      ┌─────────────────┐                      ┌─────────────────┐\n              │   Fast Model    │                      │ Balanced Model  │                      │ Powerful Model  │\n              │   (e.g. 8B)     │                      │   (e.g. 70B)    │                      │  (e.g. 405B)    │\n              └─────────────────┘                      └─────────────────┘                      └─────────────────┘\n```\n\n### Quick Start\n\n**1. Configure OpenClaw Router** (`openclaw_router\u002Fconfig.yaml`):\n\n```yaml\nserve:\n  host: \"0.0.0.0\"\n  port: 8000\n  show_model_prefix: true\n\nrouter:\n  strategy: llm  # or: random, round_robin, rules, llmrouter\n  provider: together\n  base_url: https:\u002F\u002Fapi.together.xyz\u002Fv1\n  model: \"meta-llama\u002FMeta-Llama-3.1-8B-Instruct-Turbo\"\n\napi_keys:\n  together: ${TOGETHER_API_KEY}\n\nllms:\n  llama-3.1-8b:\n    provider: together\n    model: \"meta-llama\u002FMeta-Llama-3.1-8B-Instruct-Turbo\"\n    base_url: https:\u002F\u002Fapi.together.xyz\u002Fv1\n    description: \"Fast responses\"\n\n  llama-3.3-70b:\n    provider: together\n    model: \"meta-llama\u002FLlama-3.3-70B-Instruct-Turbo\"\n    base_url: https:\u002F\u002Fapi.together.xyz\u002Fv1\n    description: \"Complex reasoning\"\n```\n\n**2. Start the server**:\n\n```bash\n# Using the startup script (recommended - also starts OpenClaw gateway)\n.\u002Fscripts\u002Fstart-openclaw.sh\n\n# Or directly via CLI\nllmrouter serve --config openclaw_router\u002Fconfig.yaml\n\n# With ML-based router\nllmrouter serve --config openclaw_router\u002Fconfig.yaml --router knnrouter\n```\n\n**3. Test the API**:\n\n```bash\ncurl http:\u002F\u002Flocalhost:8000\u002Fv1\u002Fchat\u002Fcompletions \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"model\": \"auto\",\n    \"messages\": [{\"role\": \"user\", \"content\": \"Explain quantum computing\"}]\n  }'\n```\n\n### Optional Features\n\n**Routing Memory** (retrieval-augmented routing):\n```yaml\nmemory:\n  enabled: true\n  path: \"${HOME}\u002F.llmrouter\u002Fopenclaw_memory.jsonl\"\n  top_k: 10\n  retriever_model: \"facebook\u002Fcontriever-msmarco\"\n```\n\n**Media Understanding** (multimodal support):\n```yaml\nmedia:\n  enabled: true\n  vision_model: \"Qwen\u002FQwen3-VL-8B-Instruct\"\n  audio_model: \"openai\u002Fwhisper-large-v3\"\n```\n\n### Documentation\n\nFor complete setup instructions including Slack\u002FDiscord integration:\n- 📖 **Full Guide**: [openclaw_router\u002FREADME.md](openclaw_router\u002FREADME.md)\n\n\n## 🗺️ TODO\n\n- [ ] Improve personalized routers: stronger user profiling, cold-start strategies, and online feedback updates.\n- [ ] Integrate a multimodal router: support image\u002Faudio inputs and route by modality + task type to the right multimodal model.\n- [ ] Add continual\u002Fonline learning to adapt routers to domain drift (e.g., periodic re-training + feedback loops).\n\n\n\n## 🙏 Acknowledgments\n\nLLMRouter builds upon the excellent research from the community. We gratefully acknowledge the following works that inspired our router implementations:\n\n- [**RouteLLM**](https:\u002F\u002Farxiv.org\u002Fabs\u002F2406.18665) - Learning to Route LLMs with Preference Data (ICLR 2025)\n- [**RouterDC**](https:\u002F\u002Farxiv.org\u002Fabs\u002F2409.19886) - Query-Based Router by Dual Contrastive Learning (NeurIPS 2024)\n- [**AutoMix**](https:\u002F\u002Farxiv.org\u002Fabs\u002F2310.12963) - Automatically Mixing Language Models (NeurIPS 2024)\n- [**Hybrid LLM**](https:\u002F\u002Farxiv.org\u002Fabs\u002F2404.14618) - Cost-Efficient and Quality-Aware Query Routing (ICLR 2024)\n- [**GraphRouter**](https:\u002F\u002Farxiv.org\u002Fabs\u002F2410.03834) - A Graph-based Router for LLM Selections (ICLR 2025)\n- [**GMTRouter**](https:\u002F\u002Farxiv.org\u002Fabs\u002F2511.08590) - Personalized LLM Router over Multi-turn User Interactions\n- [**PersonalizedRouter**](https:\u002F\u002Farxiv.org\u002Fabs\u002F2511.16883) - Personalized LLM Routing via Graph-based User Preference Modeling\n- [**Router-R1**](https:\u002F\u002Farxiv.org\u002Fabs\u002F2506.09033) - Teaching LLMs Multi-Round Routing and Aggregation via RL (NeurIPS 2025)\n- [**FusionFactory**](https:\u002F\u002Farxiv.org\u002Fabs\u002F2507.10540) - Fusing LLM Capabilities with Multi-LLM Log Data\n\nWe warmly welcome contributions from the community! A powerful open-source router framework requires the collective effort of everyone. If you have developed a new routing method, please consider submitting a PR to add it to LLMRouter. Together, we can build the most comprehensive LLM routing library!\n\n\n\n## 🤝 Contribution\n\nWe warmly welcome contributions from the community. **LLMRouter is a living, extensible research framework**, and its impact grows through the creativity and expertise of its contributors.\n\nIf you have developed a **new routing strategy, learning objective, training paradigm, or evaluation protocol**, we strongly encourage you to submit a pull request to integrate it into LLMRouter. **All accepted contributions are explicitly credited**, documented, and made available to a broad research and practitioner audience.\n\nContributing to LLMRouter is more than adding code. It is an opportunity to **increase the visibility, adoption, and long-term impact of your work** within the LLM systems community. Together, we aim to build the **most comprehensive and extensible open-source library for LLM routing**.\n\n> **Notable contributions** may be highlighted in documentation, examples, benchmarks, or future releases.\n\n\n\u003C\u002Fbr>\n\n\u003Cdiv align=\"center\">\n  \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Fulab-uiuc\u002FLLMRouter\u002Fgraphs\u002Fcontributors\">\n    \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fulab-uiuc_LLMRouter_readme_88d3fb695e28.png\" style=\"border-radius: 15px; box-shadow: 0 0 20px rgba(0, 217, 255, 0.3);\" \u002F>\n  \u003C\u002Fa>\n\u003C\u002Fdiv>\n\n\n\n## Star History\n\n[![Star History Chart](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fulab-uiuc_LLMRouter_readme_e976252c911e.png)](https:\u002F\u002Fwww.star-history.com\u002F#ulab-uiuc\u002FLLMRouter&type=date&legend=top-left)\n\n\n\n\n## 📚 Citation\n\nIf you find LLMRouter useful for your research or projects, please cite it as:\n\n```bibtex\n@misc{llmrouter2025,\n  title        = {LLMRouter: An Open-Source Library for LLM Routing},\n  author       = {Tao Feng and Haozhen Zhang and Zijie Lei and Haodong Yue and Chongshan Lin and Ge Liu and Jiaxuan You},\n  year         = {2025},\n  howpublished = {\\url{https:\u002F\u002Fgithub.com\u002Fulab-uiuc\u002FLLMRouter}},\n  note         = {GitHub repository}\n}\n```\n","\u003Cdiv align=\"center\">\n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fulab-uiuc_LLMRouter_readme_30b3b7ec022d.png\" alt=\"LLMRouter Logo\" width=\"200\">\n\u003C\u002Fdiv>\n\n\u003Ch1 align=\"center\">🚀 LLMRouter：开源的大型语言模型路由库\u003C\u002Fh1>\n\n\n\u003Cdiv align=\"center\">\n  \u003Cp>\n    \u003Ca href=\"https:\u002F\u002Fwww.python.org\u002Fdownloads\u002Frelease\u002Fpython-3109\u002F\">\u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FPYTHON-3.10-3776AB?style=for-the-badge&logo=python&logoColor=white\" alt=\"Python\">\u003C\u002Fa>\n    \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Fulab-uiuc\u002FLLMRouter\u002Fpulls\">\u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FPRS-WELCOME-orange?style=for-the-badge\" alt=\"PRs\">\u003C\u002Fa>\n    \u003Ca href=\"https:\u002F\u002Fjoin.slack.com\u002Ft\u002Fllmrouteropen-ri04588\u002Fshared_invite\u002Fzt-3mkx82cut-A25v5yR52xVKi7_jm_YK_w\">\u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FSLACK-JOIN%20US-4A154B?style=for-the-badge&logo=slack&logoColor=white\" alt=\"Slack\">\u003C\u002Fa>\n    \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Fulab-uiuc\u002FLLMRouter\u002Fissues\u002F136\">\u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002F💬WeChat-Group-07c160?style=for-the-badge&logo=wechat&logoColor=white&labelColor=1a1a2e\">\u003C\u002Fa>\n    \u003Ca href=\"https:\u002F\u002Fulab-uiuc.github.io\u002FLLMRouter\u002F\" style=\"text-decoration:none;\">\u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FDOCS-ONLINE-0A9EDC?style=for-the-badge&logo=readthedocs&logoColor=white\" alt=\"Docs\">\u003C\u002Fa>\n    \u003Ca href=\"https:\u002F\u002Fx.com\u002Fyoujiaxuan\u002Fstatus\u002F2005877938554589370\" style=\"text-decoration:none;\">\u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FTWITTER-ANNOUNCEMENTS-1DA1F2?style=for-the-badge&logo=x&logoColor=white\" alt=\"Twitter\">\u003C\u002Fa>\n    \u003Ca href=\"LICENSE\">\u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FLICENSE-MIT-2EA44F?style=for-the-badge\" alt=\"License\">\u003C\u002Fa>\n  \u003C\u002Fp>\n\u003C\u002Fdiv>\n\n\n\n\n## ✨ 简介\n\n\u003Cdiv align=\"center\">\n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fulab-uiuc_LLMRouter_readme_089cbd02a8ed.png\" alt=\"LLMRouter Overview\" style=\"width: 100%; max-width: 1000px;\">\n\u003C\u002Fdiv>\n\n\n**LLMRouter** 是一个智能路由系统，旨在通过动态选择最适合每个查询的模型来优化大型语言模型的推理过程。为了实现智能路由，它定义了以下功能：\n\n1. 🚀 *智能路由*：根据任务复杂度、成本和性能要求，自动将查询路由到最优的大型语言模型。\n2. 📊 *多种路由模型*：支持 **超过16种路由模型**，分为四大类——**单轮路由、多轮路由、代理式路由和个性化路由**——涵盖了广泛的策略，如KNN、SVM、MLP、矩阵分解、Elo评分、基于图的路由、BERT-based路由、混合概率方法、转换分数路由等。\n3. 🛠️ *统一的命令行界面*：完整的命令行接口，用于训练、推理以及通过Gradio构建的交互式聊天界面。\n4. 📈 *数据生成流水线*：从11个基准数据集自动生成训练数据的完整流水线，具备自动API调用和评估功能。\n\n## 📰 最新消息\n\n- 🖥️ **[2026-02]**：**ComfyUI界面**——我们发布了LLMRouter的可视化界面！现在你可以直观地构建数据生成和路由流水线，拖拽节点来训练路由模型，并实时监控性能。详情请参见 [ComfyUI界面](#-comfyui-interface)。\n\n- 🔗 **[2026-02]**：**OpenClaw路由器**——兼容OpenAI的服务器，集成OpenClaw！我们还发布了llmrouter-lib v0.3.1。你可以将LLMRouter部署为生产级API服务器，通过 [OpenClaw](https:\u002F\u002Fgithub.com\u002Fopenclaw\u002Fopenclaw) 与Slack、Discord等消息平台无缝对接。该版本新增了多模态理解（图像\u002F音频\u002F视频）、检索增强型路由记忆、流式传输支持，以及所有16+种LLMRouter路由策略。详情请参见 [OpenClaw路由器集成](#-openclaw-router-openclaw-integration)。若需在Slack等社交平台上部署，请参考 [入门指南](https:\u002F\u002Fwww.moltcn.com\u002Fstart\u002Fgetting-started.html)，获取详细的设置步骤。\n\n- ⭐ **[2026-01]**：**LLMRouter** 刚刚突破1000颗GitHub星！我们还发布了llmrouter-lib v0.2.0。此次更新包括针对不同服务的字典配置（如OpenAI、Anthropic等），以及在Geometry3K、MathVista和Charades-Ego数据集上实现的多模态路由（视频\u002F图像+文本）。这是首个统一的开源LLM路由库，内置16+种路由模型、统一的CLI、Gradio UI和11个数据集。可通过 `pip install llmrouter-lib` 进行安装。更多更新即将发布！🚀\n\n- 🚀 **[2025-12]**：**LLMRouter** 正式发布——以更智能的思维🧠、更具成本意识的方式💸，利用16+种路由模型🧭、统一的 `llmrouter` CLI 🛠️，以及用于自定义路由的插件工作流 🧩，实现高效的大型语言模型路由。\n\n## 🔗 链接\n\n- [支持的路由模型](#-supported-routers)\n- [安装指南](#installation)\n- [使用自有数据集](#-preparing-training-data)\n- [训练路由模型](#training-a-router)\n- [通过路由模型进行推理](#running-inference)\n- [与路由模型的交互式聊天界面](#interactive-chat-interface)\n- [ComfyUI界面](#-comfyui-interface)\n- [创建自定义路由模型](#-creating-your-own-routers)\n- [添加自定义任务](#-adding-your-own-tasks)\n- [OpenClaw路由器（OpenClaw集成）](#-openclaw-router-openclaw-integration)\n- [致谢](#-acknowledgments)\n- [引用](#-citation)\n\n## 🧭 支持的路由模型\n\n### 单轮路由模型\n| 路由模型 | 训练 | 推理 | 描述 | 教程 |\n|--------|:--------:|:---------:|-------------|:--------:|\n| `knnrouter` | ✅ | ✅ | 基于K近邻的路由 | [📖](llmrouter\u002Fmodels\u002Fknnrouter\u002FREADME.md) |\n| `svmrouter` | ✅ | ✅ | 基于支持向量机的路由 | [📖](llmrouter\u002Fmodels\u002Fsvmrouter\u002FREADME.md) |\n| `mlprouter` | ✅ | ✅ | 基于多层感知器的路由 | [📖](llmrouter\u002Fmodels\u002Fmlprouter\u002FREADME.md) |\n| `mfrouter` | ✅ | ✅ | 基于矩阵分解的路由 | [📖](llmrouter\u002Fmodels\u002Fmfrouter\u002FREADME.md) |\n| `elorouter` | ✅ | ✅ | 基于Elo评分的路由 | [📖](llmrouter\u002Fmodels\u002Felorouter\u002FREADME.md) |\n| `routerdc` | ✅ | ✅ | 基于双对比学习的路由 | [📖](llmrouter\u002Fmodels\u002Frouterdc\u002FREADME.md) |\n| `automix` | ✅ | ✅ | 自动模型混合 | [📖](llmrouter\u002Fmodels\u002Fautomix\u002FREADME.md) |\n| `hybrid_llm` | ✅ | ✅ | 混合LLM路由策略 | [📖](llmrouter\u002Fmodels\u002Fhybrid_llm\u002FREADME.md) |\n| `graphrouter` | ✅ | ✅ | 基于图的路由 | [📖](llmrouter\u002Fmodels\u002Fgraphrouter\u002FREADME.md) |\n| `causallm_router` | ✅ | ✅ | 因果语言模型路由 | [📖](llmrouter\u002Fmodels\u002Fcausallm_router\u002FREADME.md) |\n| `smallest_llm` | N\u002FA | ✅ | 始终路由到最小模型 | [📖](llmrouter\u002Fmodels\u002Fsmallest_llm\u002FREADME.md) |\n| `largest_llm` | N\u002FA | ✅ | 始终路由到最大模型 | [📖](llmrouter\u002Fmodels\u002Flargest_llm\u002FREADME.md) |\n\n### 多轮路由模型\n| 路由模型 | 训练 | 推理 | 描述 | 教程 |\n|--------|:--------:|:---------:|-------------|:--------:|\n| `router_r1` | [LINK](https:\u002F\u002Fgithub.com\u002Fulab-uiuc\u002FRouter-R1) | ✅ | 预训练的Router-R1模型，适用于多轮对话 | [📖](llmrouter\u002Fmodels\u002Frouter_r1\u002FREADME.md) |\n\n### 个性化路由\n| 路由器 | 训练 | 推理 | 描述 | 教程 |\n|--------|:--------:|:---------:|-------------|:--------:|\n| `gmtrouter` | ✅ | ✅ | 基于图的个性化路由，支持用户偏好学习 | [📖](llmrouter\u002Fmodels\u002Fgmtrouter\u002FREADME.md) |\n| `personalizedrouter` | ✅ | ✅ | 基于 GNN 的个性化路由，结合用户特征 | [📖](llmrouter\u002Fmodels\u002Fpersonalizedrouter\u002FREADME.md) |\n\n### 智能体路由\n| 路由器 | 训练 | 推理 | 描述 | 教程 |\n|--------|:--------:|:---------:|-------------|:--------:|\n| `knnmultiroundrouter` | ✅ | ✅ | 基于 KNN 的智能体路由，适用于复杂任务 | [📖](llmrouter\u002Fmodels\u002Fknnmultiroundrouter\u002FREADME.md) |\n| `llmmultiroundrouter` | N\u002FA | ✅ | 基于 LLM 的智能体路由，适用于复杂任务 | [📖](llmrouter\u002Fmodels\u002Fllmmultiroundrouter\u002FREADME.md) |\n\n## 🚀 开始使用\n\n### 安装\n\n#### 从源码安装\n\n克隆仓库并使用虚拟环境（例如 anaconda3）以可编辑模式安装：\n\n```bash\n# 克隆仓库\ngit clone https:\u002F\u002Fgithub.com\u002Fulab-uiuc\u002FLLMRouter.git\ncd LLMRouter\n\n# 创建并激活虚拟环境\nconda create -n llmrouter python=3.10\nconda activate llmrouter\n\n# 安装基础包\npip install -e .\n\n# 可选：安装 RouterR1 支持（需要 GPU）\n# RouterR1 已在 vllm==0.6.3 (torch==2.4.0) 上测试过；额外固定这些版本。\npip install -e \".[router-r1]\"\n\n# 可选：安装所有可选依赖\npip install -e \".[all]\"\n```\n\n#### 从 PyPI 安装\n\n```bash\npip install llmrouter-lib\n```\n\n### 🔑 设置 API 密钥\n\nLLMRouter 需要 API 密钥来进行推理、聊天和数据生成等 LLM API 调用。请使用以下格式之一设置 `API_KEYS` 环境变量：\n\n> 💡 **免费 NVIDIA API 密钥**：LLMRouter 目前使用的 NVIDIA 端点提供免费的 API 密钥。要开始使用，请访问 [https:\u002F\u002Fbuild.nvidia.com\u002F](https:\u002F\u002Fbuild.nvidia.com\u002F) 创建一个账户，然后即可免费生成您的 API 密钥。\n\n#### **服务特定字典格式**（推荐用于多个提供商）\n\n当您拥有来自不同服务提供商（如 NVIDIA、OpenAI、Anthropic）的模型，并希望为每个提供商使用不同的 API 密钥时，可以使用此格式：\n\n```bash\nexport API_KEYS='{\"NVIDIA\": \"nvidia-key-1,nvidia-key-2\", \"OpenAI\": [\"openai-key-1\", \"openai-key-2\"], \"Anthropic\": \"anthropic-key-1\"}'\n```\n\n**字典格式详情**：\n- **键**：服务提供商名称（必须与 LLM 候选者 JSON 中的 `service` 字段匹配）\n- **值**：可以是：\n  - 逗号分隔的字符串：“key1,key2,key3”\n  - JSON 数组：“[“key1”, “key2”, “key3”]”\n  - 单个字符串：“key1”\n- **服务匹配**：系统会自动匹配 LLM 候选者 JSON 中的 `service` 字段，以选择相应的 API 密钥\n- **轮询机制**：每个服务都会维护自己的轮询计数器，用于负载均衡\n- **错误处理**：如果字典中未找到某项服务，系统将抛出明确的错误信息，并列出可用的服务。\n\n**带有 service 字段的 LLM 候选者 JSON 示例**：\n```json\n{\n  \"qwen2.5-7b-instruct\": {\n    \"service\": \"NVIDIA\",\n    \"model\": \"qwen\u002Fqwen2.5-7b-instruct\",\n    \"api_endpoint\": \"https:\u002F\u002Fintegrate.api.nvidia.com\u002Fv1\"\n  },\n  \"gpt-4\": {\n    \"service\": \"OpenAI\",\n    \"model\": \"gpt-4\",\n    \"api_endpoint\": \"https:\u002F\u002Fapi.openai.com\u002Fv1\"\n  }\n}\n```\n\n#### **旧版格式**（适用于单个提供商或向后兼容）\n\n**JSON 数组格式**（适用于同一提供商的多个密钥）：\n```bash\nexport API_KEYS='[\"your-key-1\", \"your-key-2\", \"your-key-3\"]'\n```\n\n**逗号分隔格式**（多个密钥的另一种方式）：\n```bash\nexport API_KEYS='key1,key2,key3'\n```\n\n**单个密钥**（仅有一个 API 密钥时）：\n```bash\nexport API_KEYS='your-api-key'\n```\n\n**注意事项**：\n- API 密钥用于 **推理**、**聊天界面** 和 **数据生成**（管道中的第 3 步）\n- 多个密钥可以实现 API 调用的自动负载均衡\n- 使用 **字典格式** 时，请确保 LLM 候选者 JSON 中的 `service` 字段与 `API_KEYS` 字典中的密钥相匹配\n- 必须在运行推理、聊天或数据生成命令之前设置该环境变量\n- 为了持久化设置，可将 export 命令添加到您的 shell 配置文件中（例如 `~\u002F.bashrc` 或 `~\u002F.zshrc`）。\n\n### 🌐 配置 API 端点\n\nAPI 端点可以在两个层级指定（按优先级顺序解析）：\n\n1. **每模型级别**（最高优先级）：LLM 候选者 JSON 中的 `api_endpoint` 字段（`default_llm.json`）\n2. **路由器级别**（备用）：路由器 YAML 配置中的 `api_endpoint` 字段\n3. **错误**：如果两者均未指定，则会抛出描述性错误。\n\n**LLM 候选者 JSON**（每模型端点）：\n```json\n{\n  \"qwen2.5-7b-instruct\": {\n    \"model\": \"qwen\u002Fqwen2.5-7b-instruct\",\n    \"api_endpoint\": \"https:\u002F\u002Fintegrate.api.nvidia.com\u002Fv1\",\n    ...\n  },\n  \"custom-model\": {\n    \"model\": \"custom\u002Fmodel-name\",\n    \"api_endpoint\": \"https:\u002F\u002Fapi.customprovider.com\u002Fv1\",\n    ...\n  }\n}\n```\n\n**路由器 YAML**（默认端点）：\n```yaml\napi_endpoint: 'https:\u002F\u002Fintegrate.api.nvidia.com\u002Fv1'  # 所有模型的备用端点\n```\n\n**优点**：不同模型可以使用不同的提供商；易于迁移；与路由器配置向后兼容。\n\n有关详细信息，请参阅 [数据生成管道文档](llmrouter\u002Fdata\u002FREADME.md#llm-data-json-default_llmjson)。\n\n### 🖥️ 使用本地 LLM 模型\n\nLLMRouter 支持提供 OpenAI 兼容 API 的本地 LLM 推理服务器（例如 Ollama、vLLM、SGLang）。对于本地提供商，您可以将 API 密钥值设为空字符串 `\"\"`——系统会自动检测 localhost 端点并相应地处理身份验证。\n\n**Ollama 示例**：\n\n```bash\nexport API_KEYS='{\"Ollama\": \"\"}'\n```\n\n```json\n{\n  \"gemma3\": {\n    \"size\": \"3B\",\n    \"feature\": \"Gemma 3B 模型通过 Ollama 在本地托管\",\n    \"input_price\": 0.0,\n    \"output_price\": 0.0,\n    \"model\": \"gemma3\",\n    \"service\": \"Ollama\",\n    \"api_endpoint\": \"http:\u002F\u002Flocalhost:11434\u002Fv1\"\n  }\n}\n```\n\n**重要提示**：请使用 `\u002Fv1` 端点（OpenAI 兼容），而不是原生 API 端点。空字符串会被自动检测为 localhost 端点（`localhost` 或 `127.0.0.1`）。\n\n### 🧪 测试模型可用性\n\n您可以使用以下 curl 命令测试不同候选模型的可用性。这对于验证您的 API 密钥是否正常工作以及特定模型是否可访问非常有用：\n\n**注意**：如果您使用的是 `API_KEYS` 的字典格式，请先提取 NVIDIA 密钥（例如，使用 `echo $API_KEYS | python3 -c \"import sys, json; print(json.load(sys.stdin)['NVIDIA'].split(',')[0])\"`），或者临时设置一个包含 NVIDIA API 密钥的变量。\n\n```bash\n# export API_KEYS=...\n\n# 示例 API 端点 - 根据您的配置调整\n# 此示例使用 NVIDIA 的端点，但您应使用 LLM 候选者 JSON 或路由器配置中指定的端点\nAPI_ENDPOINT=\"https:\u002F\u002Fintegrate.api.nvidia.com\u002Fv1\u002Fchat\u002Fcompletions\"\n\n# 示例模型列表 - 根据您的 LLM 候选者配置调整\n\n# 这些是示例模型；请替换为您 LLM 候选 JSON 文件中的实际模型名称\u002FID\nMODELS=(\n  \"qwen\u002Fqwen2.5-7b-instruct\"\n  \"meta\u002Fllama-3.1-8b-instruct\"\n  \"mistralai\u002Fmistral-7b-instruct-v0.3\"\n  \"nvidia\u002Fllama-3.3-nemotron-super-49b-v1\"\n  \"mistralai\u002Fmixtral-8x7b-instruct-v0.1\"\n  \"mistralai\u002Fmixtral-8x22b-instruct-v0.1\"\n)\n\nSYSTEM_PROMPT=\"你好。\"\nPROMPT=\"你好。\"\n\nfor MODEL in \"${MODELS[@]}\"; do\n  echo \"===== $MODEL =====\"\n\n  curl \"$API_ENDPOINT\" \\\n    -H \"Content-Type: application\u002Fjson\" \\\n    -H \"Authorization: Bearer $API_KEYS\" \\\n    -d \"{\n      \\\"model\\\": \\\"$MODEL\\\",\n      \\\"messages\\\": [\n        {\n          \\\"role\\\": \\\"system\\\",\n          \\\"content\\\": \\\"$SYSTEM_PROMPT\\\"\n        },\n        {\n          \\\"role\\\": \\\"user\\\",\n          \\\"content\\\": \\\"$PROMPT\\\"\n        }\n      ],\n      \\\"temperature\\\": 0.8,\n      \\\"max_tokens\\\": 200\n    }\"\n\n  echo\ndone\n```\n\n此脚本将测试列表中的每种模型并显示响应，帮助您验证哪些模型可用以及是否能与您的 API 密钥正常工作。\n\n\n\n### 📊 准备训练数据\n\nLLMRouter 包含一个完整的数据生成管道，可将原始基准测试数据集转换为带有嵌入的格式化路由数据。该管道支持 11 种多样化的基准测试数据集，包括自然问答、琐事问答、MMLU、GPQA、MBPP、HumanEval、GSM8K、常识问答、数学、OpenbookQA 和 ARC-Challenge。\n\n> 💡 **多模态集成**：请查看我们的 [多模态任务指南](data\u002Fmultimodal_tasks\u002FREADME.md)，了解如何将复杂的多模态任务（视频\u002F图像 + 文本）纳入 LLMRouter。目前我们支持 3 个数据集中的 5 项多模态任务（Geometry3K、MathVista、Charades-Ego）。\n\n#### 管道概述\n\n数据生成管道包含三个主要步骤：\n\n1. **生成查询数据** - 从基准测试数据集中提取查询，并创建训练\u002F测试分割的 JSONL 文件\n2. **生成 LLM 嵌入** - 根据 LLM 候选者的元数据为其创建嵌入\n3. **API 调用与评估** - 调用 LLM API，评估响应，并生成统一的嵌入和路由数据\n\n#### 快速入门\n\n\n首先使用示例配置文件：\n\n```bash\n# 第一步：生成查询数据\npython llmrouter\u002Fdata\u002Fdata_generation.py --config llmrouter\u002Fdata\u002Fsample_config.yaml\n\n# 第二步：生成 LLM 嵌入\npython llmrouter\u002Fdata\u002Fgenerate_llm_embeddings.py --config llmrouter\u002Fdata\u002Fsample_config.yaml\n\n# 第三步：API 调用与评估（需要 API_KEYS - 参见上面的“设置 API 密钥”部分）\npython llmrouter\u002Fdata\u002Fapi_calling_evaluation.py --config llmrouter\u002Fdata\u002Fsample_config.yaml --workers 100\n```\n\n#### 输出文件\n\n管道会生成以下文件：\n\n- **查询数据**（JSONL）：`query_data_train.jsonl` 和 `query_data_test.jsonl` - 包含训练\u002F测试分割的查询数据\n- **LLM 嵌入**（JSON）：`default_llm_embeddings.json` - 包含嵌入的 LLM 元数据\n- **查询嵌入**（PyTorch）：`query_embeddings_longformer.pt` - 所有查询的统一嵌入\n- **路由数据**（JSONL）：`default_routing_train_data.jsonl` 和 `default_routing_test_data.jsonl` - 包含模型响应、性能评分和 token 使用情况的完整路由数据\n\n**路由数据条目示例：**\n```json\n{\n  \"task_name\": \"gsm8k\",\n  \"query\": \"珍妮特有 4 个苹果。她给了鲍勃 2 个。她还剩多少个？\",\n  \"ground_truth\": \"2\",\n  \"metric\": \"GSM8K\",\n  \"model_name\": \"llama3-chatqa-1.5-8b\",\n  \"response\": \"珍妮特有 4 个苹果，给了鲍勃 2 个，所以她还剩下 4 - 2 = 2 个苹果。\",\n  \"performance\": 1.0,\n  \"embedding_id\": 42,\n  \"token_num\": 453\n}\n```\n\n#### 配置\n\n所有路径和参数都通过 YAML 配置文件进行控制。示例配置文件 (`llmrouter\u002Fdata\u002Fsample_config.yaml`) 引用了示例数据目录，您可以直接使用，也可以根据自己的设置进行自定义。\n\n**注意**：第 3 步需要 API 密钥才能调用 LLM 服务。有关配置详情，请参阅上面的 [设置 API 密钥](#-setting-up-api-keys) 部分。\n\n如需完整的文档，包括详细的文件格式、嵌入映射系统、配置选项和故障排除信息，请参阅 **[llmrouter\u002Fdata\u002FREADME.md](llmrouter\u002Fdata\u002FREADME.md)**。\n\n### 训练路由器\n\n在开始训练之前，请确保已使用 [数据生成管道](#-preparing-training-data) 准备好数据，或使用 `data\u002Fexample_data\u002F` 中的示例数据。\n\n使用您的配置训练各种路由器模型：\n```bash\n# 训练 KNN 路由器\nllmrouter train --router knnrouter --config configs\u002Fmodel_config_train\u002Fknnrouter.yaml\n\n# 使用 GPU 训练 MLP 路由器\nCUDA_VISIBLE_DEVICES=2 llmrouter train --router mlprouter --config configs\u002Fmodel_config_train\u002Fmlprouter.yaml --device cuda\n\n# 静默训练 MF 路由器\nCUDA_VISIBLE_DEVICES=1 llmrouter train --router mfrouter --config configs\u002Fmodel_config_train\u002Fmfrouter.yaml --device cuda --quiet\n```\n\n### 运行推理\n\n使用训练好的路由器进行推理（需要 API 密钥 - 参见 [设置 API 密钥](#-setting-up-api-keys) 部分）：\n```bash\n# 单个查询推理\nllmrouter infer --router knnrouter --config config.yaml --query \"什么是机器学习？\"\n\n# 从文件批量推理\nllmrouter infer --router knnrouter --config config.yaml --input queries.txt --output results.json\n\n# 仅路由（无需调用 LLM API - 不需要 API 密钥）\nllmrouter infer --router knnrouter --config config.yaml --query \"你好\" --route-only\n\n# 自定义生成参数\nllmrouter infer --router knnrouter --config config.yaml --query \"解释人工智能\" --temp 0.7 --max-tokens 2048 --verbose\n```\n\n支持的输入文件格式：`.txt`（每行一个查询）、`.json`（字符串列表或包含 `\"query\"` 字段的对象）、`.jsonl`（每行一个 JSON 对象）。\n\n### 交互式聊天界面\n\n\u003Cdiv style=\"text-align:center;\">\n    \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fulab-uiuc_LLMRouter_readme_8f3512362212.gif\" style=\"width: 100%; height: auto;\">\n\u003C\u002Fdiv>\n\n\u003Cp align=\"center\">\n    \u003Cstrong>📱 快速预览：\u003C\u002Fstrong> LLMRouter 聊天界面的动画概览，展示实时路由和模型选择。\n\u003C\u002Fp>\n\n\u003Cdiv style=\"text-align:center;\">\n    \u003Cvideo width=\"100%\" controls style=\"max-width: 800px; height: auto;\">\n        \u003Csource src=\"assets\u002Fllmrouter_chat_demo.mov\" type=\"video\u002Fquicktime\">\n        您的浏览器不支持 video 标签。\n    \u003C\u002Fvideo>\n\u003C\u002Fdiv>\n\n启动聊天界面（需要 API 密钥 - 参见 [设置 API 密钥](#-setting-up-api-keys) 部分）：\n\n```bash\n# 基本聊天界面\nllmrouter chat --router knnrouter --config config.yaml\n\n# 自定义主机和端口\nllmrouter chat --router knnrouter --config config.yaml --host 0.0.0.0 --port 7860\n\n# 启用公开分享链接\nllmrouter chat --router knnrouter --config config.yaml --share\n\n# 指定查询模式\nllmrouter chat --router knnrouter --config config.yaml --mode full_context --top_k 5\n```\n\n查询模式：\n- `current_only`：仅根据当前查询进行路由（默认）\n- `full_context`：将所有聊天历史与当前查询结合\n- `retrieval`：检索 top-k 相似的历史查询以提供上下文\n\n### 直接执行脚本\n\n您也可以直接运行 CLI 脚本：\n\n# 训练\npython -m llmrouter.cli.router_train --router knnrouter --config config.yaml\n\n# 推理\npython -m llmrouter.cli.router_inference --router knnrouter --config config.yaml --query \"Hello\"\n\n# 对话\npython -m llmrouter.cli.router_chat --router knnrouter --config config.yaml\n```\n\n## 🎨 ComfyUI 界面\n\nLLMRouter 通过 [ComfyUI](https:\u002F\u002Fgithub.com\u002FComfy-Org\u002FComfyUI) 提供了一个强大的 **可视化界面**，彻底改变了您与路由流程交互的方式。您不再需要编辑 YAML 文件或运行终端脚本，而是可以通过拖放节点来构建工作流。\n\n\u003Cdiv align=\"center\">\n  \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fulab-uiuc_LLMRouter_readme_fb5775136849.png\" alt=\"LLMRouter ComfyUI 界面\" width=\"100%\">\n\u003C\u002Fdiv>\n\n### 主要亮点\n\n- **可视化配置**：告别复杂的 YAML 文件和终端命令。您可以在画布上直接调整参数（如样本大小、模型候选）并选择数据集。\n- **端到端自动化**：无缝连接各个节点，构建完整的流程：数据生成 $\\to$ 路由器训练 $\\to$ 评估。\n- **实时监控**：通过即时的视觉反馈，跟踪查询生成、嵌入提取和模型训练的状态。\n- **模块化设计**：通过拖放和连接数据集、LLM 和路由器等节点，自定义构建您的工作流。\n\n### 安装与设置\n\n先决条件：您必须已安装 [ComfyUI](https:\u002F\u002Fgithub.com\u002FComfy-Org\u002FComfyUI)。\n\n要安装 LLMRouter 自定义节点，您需要创建两个符号链接（软链接）。\n\n#### 1. 链接自定义节点\n这使得 ComfyUI 能够在“Nodes”类别中加载 LLMRouter 的 Python 后端逻辑。\n\n```bash\nln -s \u002Fpath\u002Fto\u002FLLMRouter\u002FComfyUI \u002Fpath\u002Fto\u002FComfyUI\u002Fcustom_nodes\u002FLLMRouter\n```\n\n#### 2. 链接工作流示例（可选）\n这使您能够在 ComfyUI 的“Workflows”类别中查看预配置的工作流。\n\n```bash\nln -s \u002Fpath\u002Fto\u002FLLMRouter\u002FComfyUI\u002Fworkflows\u002Fllm_router_example.json \u002Fpath\u002Fto\u002FComfyUI\u002Fuser\u002Fdefault\u002Fworkflows\u002Fllm_router_example.json\n```\n\n#### 3. 运行应用程序\n\n要启动带有 LLMRouter 节点的 ComfyUI 服务器：\n\n```bash\npython \u002Fpath\u002Fto\u002FComfyUI\u002Fmain.py\n```\n\n#### 4. 远程访问与端口转发\n\n如果您在远程服务器上运行 ComfyUI（例如计算集群），并希望在本地访问界面，可以使用 SSH 隧道。隧道建立后，您可以通过 `http:\u002F\u002F127.0.0.1:8188` 访问界面。\n\n### 使用 ComfyUI 界面\n\n#### 查找节点\n要使用这些节点：\n1. 打开 ComfyUI 的网页界面。\n2. 使用侧边栏中的 **Node Library** 或右键单击画布。\n3. 导航到 **`LLMRouter`** 类别。\n4. 您会发现按功能组织的节点：\n    - **数据**：`Select Datasets`、`Select LLMs`、`Generate Data`。\n    - **单轮**：`KNN Router`、`SVM Router`、`MLP Router` 等。\n    - **多轮\u002F代理式**：专为复杂任务设计的路由器。\n\n#### 加载示例\n要使用即用型示例：\n1. 点击 **`Workflows`** 选项卡。\n2. 选择 **`llm_router_example.json`**。\n3. 这将加载一个完整的流程。\n\n## 🔧 创建您自己的路由器\n\nLLMRouter 支持 **插件系统**，允许您在不修改核心代码库的情况下添加自定义路由器实现。这使得尝试新的路由策略或特定领域的路由器变得非常容易。\n\n### 快速入门\n\n**1. 创建您的路由器目录：**\n```bash\nmkdir -p custom_routers\u002Fmy_router\n```\n\n**2. 实现您的路由器** (`custom_routers\u002Fmy_router\u002Frouter.py`)：\n```python\nfrom llmrouter.models.meta_router import MetaRouter\nimport torch.nn as nn\n\nclass MyRouter(MetaRouter):\n    \"\"\"您的自定义路由器实现。\"\"\"\n\n    def __init__(self, yaml_path: str):\n        # 使用模型初始化（对于简单路由器可以使用 nn.Identity()）\n        model = nn.Identity()\n        super().__init__(model=model, yaml_path=yaml_path)\n\n        # 从配置中获取可用的 LLM 名称\n        self.llm_names = list(self.llm_data.keys())\n\n    def route_single(self, query_input: dict) -> dict:\n        \"\"\"将单个查询路由到最佳 LLM。\"\"\"\n        query = query_input['query']\n\n        # 在这里编写您的自定义路由逻辑\n        # 示例：根据查询长度进行路由\n        selected_llm = (self.llm_names[0] if len(query) \u003C 50\n                       else self.llm_names[-1])\n\n        return {\n            \"query\": query,\n            \"model_name\": selected_llm,\n            \"predicted_llm\": selected_llm,\n        }\n\n    def route_batch(self, batch: list) -> list:\n        \"\"\"路由多个查询。\"\"\"\n        return [self.route_single(q) for q in batch]\n```\n\n**3. 创建配置文件** (`custom_routers\u002Fmy_router\u002Fconfig.yaml`)：\n```yaml\ndata_path:\n  llm_data: 'data\u002Fexample_data\u002Fllm_candidates\u002Fdefault_llm.json'\n\nhparam:\n  # 您的超参数在这里\n\n# 可选：默认 API 端点（当模型未指定自己的端点时作为备用）\n# 单个模型可以通过在 llm_data JSON 文件中指定 api_endpoint 来覆盖此设置\napi_endpoint: 'https:\u002F\u002Fintegrate.api.nvidia.com\u002Fv1'\n```\n\n**4. 使用您的自定义路由器**（与内置路由器相同！）：\n```bash\n# 推理\nllmrouter infer --router my_router \\\n  --config custom_routers\u002Fmy_router\u002Fconfig.yaml \\\n  --query \"什么是机器学习？\"\n\n# 列出所有路由器（包括自定义路由器）\nllmrouter list-routers\n```\n\n### 插件发现\n\n自定义路由器会自动从以下路径中被发现：\n- `.\u002Fcustom_routers\u002F`（推荐——项目目录）\n- `~\u002F.llmrouter\u002Fplugins\u002F`（用户主目录）\n- `$LLMROUTER_PLUGINS` 环境变量（以冒号分隔的路径）\n\n### 示例路由器\n\nLLMRouter 包含一些您可以学习的自定义示例路由器：\n\n**RandomRouter** —— 一个简单的基线，随机选择 LLM\n```bash\nllmrouter infer --router randomrouter \\\n  --config custom_routers\u002Frandomrouter\u002Fconfig.yaml \\\n  --query \"你好，世界\"\n```\n\n**ThresholdRouter** —— 一个高级可训练路由器，具备难度估计功能\n```bash\n# 训练路由器\nllmrouter train --router thresholdrouter \\\n  --config custom_routers\u002Fthresholdrouter\u002Fconfig.yaml\n\n# 推理\nllmrouter infer --router thresholdrouter \\\n  --config custom_routers\u002Fthresholdrouter\u002Fconfig.yaml \\\n  --query \"解释量子计算\"\n```\n\n### 文档\n\n有关创建自定义路由器的详细指南：\n- 📖 **快速入门**：[custom_routers\u002FREADME.md](custom_routers\u002FREADME.md)\n- 📖 **实现概览**：[CUSTOM_ROUTER_SUMMARY.md](CUSTOM_ROUTER_SUMMARY.md)\n\n### 常见路由模式\n\n**基于规则的路由：**\n```python\ndef route_single(self, query_input):\n    query = query_input['query'].lower()\n    if 'code' in query:\n        return {\"model_name\": \"code-specialist\"}\n    elif len(query) \u003C 50:\n        return {\"model_name\": \"small-fast-model\"}\n    else:\n        return {\"model_name\": \"large-capable-model\"}\n```\n\n**基于嵌入的路由：**\n```python\nfrom llmrouter.utils import get_longformer_embedding\n\ndef route_single(self, query_input):\n    embedding = get_longformer_embedding(query_input['query'])\n    # 使用嵌入相似度选择最佳模型\n    selected = self._find_best_model(embedding)\n    return {\"model_name\": selected}\n```\n\n**成本优化的路由：**\n```python\ndef route_single(self, query_input):\n    difficulty = self._estimate_difficulty(query_input)\n    # 选择能够处理该难度且最便宜的模型\n    for model_name, info in sorted(self.llm_data.items(),\n                                   key=lambda x: x[1]['cost']):\n        if info['capability'] >= difficulty:\n            return {\"model_name\": model_name}\n```\n\n## 📝 添加您自己的任务\n\nLLMRouter 支持**自定义任务定义**，允许您添加具有自定义提示模板和评估指标的新任务类型。自定义任务会自动被发现并集成到数据生成和评估流程中。\n\n### 快速入门\n\n**1. 创建任务格式化器**（`custom_tasks\u002Fmy_tasks.py`）：\n```python\nfrom llmrouter.utils.prompting import register_prompt\nfrom llmrouter.prompts import load_prompt_template\n\n@register_prompt('my_task', default_metric='my_metric')\ndef format_my_task_prompt(sample_data):\n    system_prompt = load_prompt_template(\"task_my_task\")\n    user_query = f\"问题: {sample_data.get('query', '')}\"\n    return {\"system\": system_prompt, \"user\": user_query}\n```\n\n**2. 创建提示模板**（`custom_tasks\u002Ftask_prompts\u002Ftask_my_task.yaml`）：\n```yaml\ntemplate: |\n  你是一位[任务描述]方面的专家。[指令]。\n```\n\n**3. 注册自定义指标**（可选）：\n```python\nfrom llmrouter.evaluation import evaluation_metric\n\n@evaluation_metric('my_metric')\ndef my_metric(prediction: str, ground_truth: str, **kwargs) -> float:\n    return 1.0 如果 prediction 等于 ground_truth，否则为 0.0\n```\n\n**4. 使用您的自定义任务：**\n```python\nimport custom_tasks.my_tasks  # 导入会触发注册\n\nfrom llmrouter.utils import generate_task_query\nfrom llmrouter.utils.evaluation import calculate_task_performance\n\n# 生成提示\nprompt = generate_task_query('my_task', {'query': '...'})\n\n# 评估（指标会自动从任务中推断）\nscore = calculate_task_performance(\n    prediction=\"...\",\n    ground_truth=\"...\",\n    task_name=\"my_task\"\n)\n```\n\n### 文档\n\n有关创建自定义任务的详细指南：\n- 📖 **完整指南**：[custom_tasks\u002FREADME.md](custom_tasks\u002FREADME.md)\n\n### 🎥 实战：多视角视频任务\n\n请按照 [Charades-Ego 集成指南](data\u002Fcharades_ego\u002FREADME.md) 中的**分步教程**，处理成对的第一人称视角视频，生成基于 VLM 的特征，并训练用于**活动**、**物体**和**动词**识别的路由器。\n\n## 🔌 OpenClaw 路由器（OpenClaw 集成）\n\n**OpenClaw 路由器**是一个与 OpenAI 兼容的 API 服务器，可将 LLMRouter 的智能路由功能引入生产环境。它可与 [OpenClaw](https:\u002F\u002Fgithub.com\u002Fopenclaw\u002Fopenclaw) 无缝集成，使您能够通过 Slack、Discord 等消息平台部署 LLM 路由。\n\n### 为什么选择 OpenClaw 路由器？\n\n| 特性 | 优势 |\n|---------|---------|\n| **与 OpenAI 兼容的 API** | 可作为任何 OpenAI 客户端的即插即用替代品（`\u002Fv1\u002Fchat\u002Fcompletions`） |\n| **所有路由策略** | 可使用 LLMRouter 的 16 种以上策略（KNN、SVM、MLP、基于 LLM 的等） |\n| **多模态理解** | 处理图像、音频和视频——将其转换为文本以进行路由决策 |\n| **路由记忆** | 持久保存查询到模型的历史记录；检索类似的历史路由以做出更好的决策 |\n| **流式支持** | 完整的流式响应，可选带 `[model_name]` 前缀 |\n| **多提供商支持** | 可路由至 Together AI、NVIDIA、OpenAI、Anthropic 或本地模型 |\n\n### 架构\n\n```\n┌─────────────────┐     ┌──────────────────────┐     ┌─────────────────────┐\n│  Slack\u002FDiscord  │────▶│   OpenClaw Gateway   │────▶│   OpenClaw Router    │\n│  (移动\u002F网页)   │     │   (Socket 模式)      │     │   (端口 8000)       │\n└─────────────────┘     └──────────────────────┘     └──────────┬──────────┘\n                                                                 │\n                        ┌────────────────────────────────────────┼────────────────────────────────────────┐\n                        │                                        │                                        │\n                        ▼                                        ▼                                        ▼\n              ┌─────────────────┐                      ┌─────────────────┐                      ┌─────────────────┐\n              │   快速模型    │                      │ 平衡模型  │                      │ 强大模型  │\n              │   （如 8B）     │                      │   （如 70B）    │                      │  （如 405B）    │\n              └─────────────────┘                      └─────────────────┘                      └─────────────────┘\n```\n\n### 快速入门\n\n**1. 配置 OpenClaw 路由器**（`openclaw_router\u002Fconfig.yaml`）：\n\n```yaml\nserve:\n  host: \"0.0.0.0\"\n  port: 8000\n  show_model_prefix: true\n\nrouter:\n  strategy: llm  # 或：random、round_robin、rules、llmrouter\n  provider: together\n  base_url: https:\u002F\u002Fapi.together.xyz\u002Fv1\n  model: \"meta-llama\u002FMeta-Llama-3.1-8B-Instruct-Turbo\"\n\napi_keys:\n  together: ${TOGETHER_API_KEY}\n\nllms:\n  llama-3.1-8b:\n    provider: together\n    model: \"meta-llama\u002FMeta-Llama-3.1-8B-Instruct-Turbo\"\n    base_url: https:\u002F\u002Fapi.together.xyz\u002Fv1\n    description: \"快速响应\"\n\n  llama-3.3-70b:\n    provider: together\n    model: \"meta-llama\u002FLlama-3.3-70B-Instruct-Turbo\"\n    base_url: https:\u002F\u002Fapi.together.xyz\u002Fv1\n    description: \"复杂推理\"\n```\n\n**2. 启动服务器**：\n\n```bash\n# 使用启动脚本（推荐——也会启动 OpenClaw 网关）\n.\u002Fscripts\u002Fstart-openclaw.sh\n\n# 或直接通过命令行\nllmrouter serve --config openclaw_router\u002Fconfig.yaml\n\n# 使用基于机器学习的路由器\nllmrouter serve --config openclaw_router\u002Fconfig.yaml --router knnrouter\n```\n\n**3. 测试 API**：\n\n```bash\ncurl http:\u002F\u002Flocalhost:8000\u002Fv1\u002Fchat\u002Fcompletions \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"model\": \"auto\",\n    \"messages\": [{\"role\": \"user\", \"content\": \"解释量子计算\"}]\n  }'\n```\n\n### 可选功能\n\n**路由记忆**（检索增强路由）：\n```yaml\nmemory:\n  enabled: true\n  path: \"${HOME}\u002F.llmrouter\u002Fopenclaw_memory.jsonl\"\n  top_k: 10\n  retriever_model: \"facebook\u002Fcontriever-msmarco\"\n```\n\n**媒体理解**（多模态支持）：\n```yaml\nmedia:\n  enabled: true\n  vision_model: \"Qwen\u002FQwen3-VL-8B-Instruct\"\n  audio_model: \"openai\u002Fwhisper-large-v3\"\n```\n\n### 文档\n\n有关包括 Slack\u002FDiscord 集成在内的完整设置说明：\n- 📖 **完整指南**：[openclaw_router\u002FREADME.md](openclaw_router\u002FREADME.md)\n\n\n## 🗺️ 待办事项\n\n- [ ] 改进个性化路由器：更强大的用户画像、冷启动策略以及在线反馈更新。\n- [ ] 集成多模态路由器：支持图像\u002F音频输入，并根据模态和任务类型将请求路由到合适的多模态模型。\n- [ ] 添加持续\u002F在线学习功能，以适应领域漂移（例如定期重新训练 + 反馈循环）。\n\n\n\n## 🙏 致谢\n\nLLMRouter 建立在社区优秀研究的基础上。我们衷心感谢以下工作，它们启发了我们的路由器实现：\n\n- [**RouteLLM**](https:\u002F\u002Farxiv.org\u002Fabs\u002F2406.18665) - 使用偏好数据学习 LLM 路由（ICLR 2025）\n- [**RouterDC**](https:\u002F\u002Farxiv.org\u002Fabs\u002F2409.19886) - 基于查询的双对比学习路由器（NeurIPS 2024）\n- [**AutoMix**](https:\u002F\u002Farxiv.org\u002Fabs\u002F2310.12963) - 自动混合语言模型（NeurIPS 2024）\n- [**Hybrid LLM**](https:\u002F\u002Farxiv.org\u002Fabs\u002F2404.14618) - 成本高效且质量导向的查询路由（ICLR 2024）\n- [**GraphRouter**](https:\u002F\u002Farxiv.org\u002Fabs\u002F2410.03834) - 基于图的 LLM 选择路由器（ICLR 2025）\n- [**GMTRouter**](https:\u002F\u002Farxiv.org\u002Fabs\u002F2511.08590) - 基于多轮用户交互的个性化 LLM 路由器\n- [**PersonalizedRouter**](https:\u002F\u002Farxiv.org\u002Fabs\u002F2511.16883) - 基于图的用户偏好建模的个性化 LLM 路由\n- [**Router-R1**](https:\u002F\u002Farxiv.org\u002Fabs\u002F2506.09033) - 通过强化学习教授 LLM 多轮路由与聚合（NeurIPS 2025）\n- [**FusionFactory**](https:\u002F\u002Farxiv.org\u002Fabs\u002F2507.10540) - 利用多 LLM 日志数据融合 LLM 能力\n\n我们热烈欢迎社区的贡献！一个强大的开源路由器框架需要大家的共同努力。如果您开发了新的路由方法，请考虑提交 PR 将其添加到 LLMRouter 中。让我们携手共建最全面的 LLM 路由库！\n\n\n\n## 🤝 贡献\n\n我们热烈欢迎来自社区的贡献。**LLMRouter 是一个不断发展的可扩展研究框架**，其影响力随着贡献者的创造力和专业知识而不断增强。\n\n如果您开发了**新的路由策略、学习目标、训练范式或评估协议**，我们强烈鼓励您提交拉取请求将其集成到 LLMRouter 中。**所有被接受的贡献都会被明确署名**，并记录在文档中，供广大的研究人员和从业者使用。\n\n为 LLMRouter 做贡献不仅仅是添加代码，更是一个提升您在 LLM 系统社区中**作品的可见性、采用率和长期影响力**的机会。我们共同的目标是打造**最全面、最具扩展性的 LLM 路由开源库**。\n\n> **杰出的贡献**可能会在文档、示例、基准测试或未来的版本中得到重点展示。\n\n\n\u003C\u002Fbr>\n\n\u003Cdiv align=\"center\">\n  \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Fulab-uiuc\u002FLLMRouter\u002Fgraphs\u002Fcontributors\">\n    \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fulab-uiuc_LLMRouter_readme_88d3fb695e28.png\" style=\"border-radius: 15px; box-shadow: 0 0 20px rgba(0, 217, 255, 0.3);\" \u002F>\n  \u003C\u002Fa>\n\u003C\u002Fdiv>\n\n\n\n## 星标历史\n\n[![星标历史图表](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fulab-uiuc_LLMRouter_readme_e976252c911e.png)](https:\u002F\u002Fwww.star-history.com\u002F#ulab-uiuc\u002FLLMRouter?type=date&legend=top-left)\n\n\n\n\n## 📚 引用\n\n如果您发现 LLMRouter 对您的研究或项目有所帮助，请按以下方式引用：\n\n```bibtex\n@misc{llmrouter2025,\n  title        = {LLMRouter：一个用于 LLM 路由的开源库},\n  author       = {Tao Feng 和 Haozhen Zhang 和 Zijie Lei 和 Haodong Yue 和 Chongshan Lin 和 Ge Liu 和 Jiaxuan You},\n  year         = {2025},\n  howpublished = {\\url{https:\u002F\u002Fgithub.com\u002Fulab-uiuc\u002FLLMRouter}},\n  note         = {GitHub 仓库}\n}\n```","# LLMRouter 快速上手指南\n\nLLMRouter 是一个智能路由系统，旨在通过为每个查询动态选择最合适的模型来优化大语言模型（LLM）的推理成本与性能。它支持超过 16 种路由策略（如 KNN、SVM、Elo 评级、图神经网络等），并提供统一的命令行工具和可视化界面。\n\n## 1. 环境准备\n\n在开始之前，请确保您的开发环境满足以下要求：\n\n*   **操作系统**: Linux, macOS 或 Windows (推荐 Linux)\n*   **Python 版本**: Python 3.10 (必须)\n*   **依赖管理**: 推荐使用 `conda` 或 `venv` 创建虚拟环境\n*   **硬件要求**: \n    *   基础路由模型训练\u002F推理：CPU 即可\n    *   若使用 `Router-R1` 或多模态功能：需要 NVIDIA GPU\n\n## 2. 安装步骤\n\n您可以选择从源码安装（推荐，功能最全）或通过 PyPI 安装。\n\n### 方式一：从源码安装（推荐）\n\n此方式支持所有可选功能（包括 Router-R1）。\n\n```bash\n# 1. 克隆仓库\ngit clone https:\u002F\u002Fgithub.com\u002Fulab-uiuc\u002FLLMRouter.git\ncd LLMRouter\n\n# 2. 创建并激活虚拟环境 (以 conda 为例)\nconda create -n llmrouter python=3.10\nconda activate llmrouter\n\n# 3. 安装基础包\npip install -e .\n\n# [可选] 如果需要支持 Router-R1 (需 GPU)，执行以下命令\n# pip install -e \".[router-r1]\"\n\n# [可选] 安装所有可选依赖\n# pip install -e \".[all]\"\n```\n\n### 方式二：通过 PyPI 安装\n\n仅包含核心库功能，适合快速集成。\n\n```bash\npip install llmrouter-lib\n```\n\n> 💡 **国内加速提示**：如果下载速度较慢，建议使用国内镜像源安装：\n> `pip install -e . -i https:\u002F\u002Fpypi.tuna.tsinghua.edu.cn\u002Fsimple`\n\n## 3. 基本使用\n\n### 第一步：配置 API Keys\n\nLLMRouter 需要访问 LLM API 进行推理和数据生成。您需要设置 `API_KEYS` 环境变量。\n\n**推荐格式（多服务商支持）**：\n如果您同时使用 NVIDIA、OpenAI 等不同服务商，请使用 JSON 字典格式：\n\n```bash\nexport API_KEYS='{\"NVIDIA\": \"your-nvidia-key\", \"OpenAI\": \"your-openai-key\"}'\n```\n\n**简单格式（单服务商）**：\n```bash\nexport API_KEYS='your-api-key'\n```\n\n> **免费资源提示**：LLMRouter 默认支持 NVIDIA 端点，您可以前往 [NVIDIA Build](https:\u002F\u002Fbuild.nvidia.com\u002F) 免费注册获取 API Key。\n\n### 第二步：准备模型配置文件\n\n创建一个 JSON 文件（例如 `my_models.json`）定义候选模型列表。LLMRouter 将根据路由策略从中选择最佳模型。\n\n```json\n{\n  \"small-model\": {\n    \"service\": \"NVIDIA\",\n    \"model\": \"meta\u002Fllama3-8b-instruct\",\n    \"api_endpoint\": \"https:\u002F\u002Fintegrate.api.nvidia.com\u002Fv1\"\n  },\n  \"large-model\": {\n    \"service\": \"OpenAI\",\n    \"model\": \"gpt-4o\",\n    \"api_endpoint\": \"https:\u002F\u002Fapi.openai.com\u002Fv1\"\n  }\n}\n```\n\n### 第三步：运行路由推理\n\n使用统一的 `llmrouter` CLI 工具进行推理。以下示例展示了如何使用预训练的 `knnrouter` 对单个查询进行路由：\n\n```bash\nllmrouter infer \\\n    --router knnrouter \\\n    --config_path path\u002Fto\u002Frouter_config.yaml \\\n    --llm_candidates path\u002Fto\u002Fmy_models.json \\\n    --query \"How to optimize a neural network?\"\n```\n\n**参数说明：**\n*   `--router`: 指定路由算法（如 `knnrouter`, `svmrouter`, `elorouter` 等）。\n*   `--config_path`: 路由器的配置文件路径（包含训练好的权重或超参数）。\n*   `--llm_candidates`: 上一步创建的候选模型 JSON 文件路径。\n*   `--query`: 用户输入的具体问题。\n\n### 进阶：启动交互式聊天界面\n\nLLMRouter 内置了基于 Gradio 的 Web UI，方便实时测试路由效果：\n\n```bash\nllmrouter chat \\\n    --router knnrouter \\\n    --config_path path\u002Fto\u002Frouter_config.yaml \\\n    --llm_candidates path\u002Fto\u002Fmy_models.json\n```\n\n运行后，终端会输出一个本地网址（通常是 `http:\u002F\u002F127.0.0.1:7860`），在浏览器打开即可体验智能路由对话。","某电商平台的智能客服团队每天需处理数万条用户咨询，涵盖简单的订单查询到复杂的售后纠纷，团队希望在保证回答质量的同时大幅降低大模型调用成本。\n\n### 没有 LLMRouter 时\n- **成本浪费严重**：无论问题难易，系统一律调用最昂贵的高端模型（如 GPT-4），导致简单查询（如“物流到哪了”）也产生高额费用。\n- **响应速度不稳定**：高端模型在高峰期推理延迟高，用户等待时间过长，影响购物体验。\n- **策略调整困难**：想要根据任务复杂度切换模型，需要人工编写大量硬编码规则，维护成本高且无法动态适应新场景。\n- **缺乏数据支撑**：难以量化不同模型在具体业务场景下的表现，优化决策全靠经验猜测。\n\n### 使用 LLMRouter 后\n- **智能降本增效**：LLMRouter 自动识别简单意图并路由至轻量级模型，仅将复杂纠纷交给高端模型，整体 API 成本降低 60%。\n- **延迟显著优化**：通过动态匹配最优模型，简单问题的平均响应时间从 3 秒缩短至 0.5 秒，大幅提升用户满意度。\n- **灵活策略部署**：利用内置的 16+ 种路由算法（如基于 KNN 或 BERT 的分类器），无需硬编码即可实现基于任务复杂度的自动分流。\n- **数据驱动迭代**：借助完整的数据生成流水线，团队能快速基于真实业务数据训练专属路由模型，持续优化分配策略。\n\nLLMRouter 通过智能化的动态路由机制，帮助企业在不牺牲服务质量的前提下，实现了大模型应用成本与性能的最佳平衡。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fulab-uiuc_LLMRouter_30b3b7ec.png","ulab-uiuc","U Lab @UIUC","https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002Fulab-uiuc_c3ce2979.png","U Lab @UIUC. PI: Jiaxuan You",null,"youjiaxuan","https:\u002F\u002Fgithub.com\u002Fulab-uiuc",[81,85,89],{"name":82,"color":83,"percentage":84},"Python","#3572A5",77.6,{"name":86,"color":87,"percentage":88},"Jupyter Notebook","#DA5B0B",21.1,{"name":90,"color":91,"percentage":92},"Shell","#89e051",1.3,1686,153,"2026-04-18T20:44:39","MIT","未说明","可选。基础功能未强制要求 GPU；若使用 Router-R1 路由模型则必须配备 NVIDIA GPU（具体型号和显存未说明，需配合 vLLM 使用）。",{"notes":100,"python":101,"dependencies":102},"1. 推荐使用 Conda 创建虚拟环境进行安装。2. 必须配置 API_KEYS 环境变量以支持推理、聊天和数据生成功能，支持 NVIDIA、OpenAI 等多个服务商的密钥轮询负载均衡。3. 若需启用 Router-R1 功能，需安装额外依赖 '[router-r1]'，这将固定 vLLM 和 Torch 的特定版本。4. 提供 ComfyUI 可视化界面和 OpenClaw 集成以支持多模态及社交平台部署。","3.10",[103,104,105,106],"vllm==0.6.3 (仅 Router-R1 模式)","torch==2.4.0 (仅 Router-R1 模式)","gradio","llmrouter-lib",[35,14,13],"2026-03-27T02:49:30.150509","2026-04-20T04:05:09.765054",[],[]]