RouteLLM
repository·main·Indexed 24 days ago
https://github.com/lm-sys/routellmA framework for serving and evaluating large language model routers, version 0.2.0. RouteLLM enables routing simpler queries to cheaper models to reduce costs while maintaining high performance. It includes a Controller for OpenAI-compatible workflows, an OpenAI-compatible server, and tools for calibrating router thresholds and evaluating performance across benchmarks such as MMLU, GSM8K, and MT-Bench. Supported routers include mf, sw_ranking, bert, causal_llm, and random.
What's inside RouteLLM
- RouteLLM benchmarks its performance against commercial routers like Martian and Unify AI using MT Bench. The benchmarks are conducted using the FastChat repository by replacing model calls with OpenAI-compatible servers for the commercial providers. RouteLLM aims to achieve comparable performance to commercial offerings while routing a lower percentage of calls to expensive models like GPT-4.
Quickstart: Replace OpenAI client with RouteLLM Controller
mainTo route queries between a strong model and a weak model using the Python SDK, initialize a
Controllerwith your desired routers and model pairs. Note thatOPENAI_API_KEYis required for embeddings even when using other providers.import os from routellm.controller import Controller os.environ["OPENAI_API_KEY"] = "sk-XXXXXX" # Example using Anyscale's Mixtral os.environ["ANYSCALE_API_KEY"] = "esecret_XXXXXX" client = Controller( routers=["mf"], strong_model="gpt-4-1106-preview", weak_model="anyscale/mistralai/Mixtral-8x7B-Instruct-v0.1", ) # To use the router, specify the model name in the format: router-[ROUTER_NAME]-[THRESHOLD] response = client.chat.completions.create( model="router-mf-0.11593", messages=[ {"role": "user", "content": "Hello!"} ] )import os from routellm.controller import Controller os.environ["OPENAI_API_KEY"] = "sk-XXXXXX" os.environ["ANYSCALE_API_KEY"] = "esecret_XXXXXX" client = Controller( routers=["mf"], strong_model="gpt-4-1106-preview", weak_model="anyscale/mistralai/Mixtral-8x7B-Instruct-v0.1", ) response = client.chat.completions.create( model="router-mf-0.11593", messages=[ {"role": "user", "content": "Hello!"} ] )Calibrate Router Thresholds
mainThe cost threshold controls the tradeoff between cost and quality. You can calibrate this threshold using a sample of your queries to achieve a specific percentage of calls to the strong model.
Use the
routellm.calibrate_thresholdmodule. For example, to calibrate themfrouter so that 50% of calls go to the strong model:python -m routellm.calibrate_threshold --routers mf --strong-model-pct 0.5 --config config.example.yamlThe output will provide the recommended threshold value (e.g.,
0.11593) to use in yourmodelfield.python -m routellm.calibrate_threshold --routers mf --strong-model-pct 0.5 --config config.example.yamlImplement a new router
mainTo add a new router to RouteLLM, follow these steps:
- Implement the abstract
Routerclass inrouters.py. - You must implement the
calculate_strong_win_ratemethod. This method takes a user prompt and returns the win rate for the strong model conditioned on that prompt. If the returned win rate is greater than the user-specified cost threshold, the request is routed to the strong model; otherwise, it goes to the weak model. - Add the new router to the
ROUTER_CLSdictionary inrouters.py.
Once implemented, the router can be used immediately in the server or evaluation framework.
- Implement the abstract
Launch an OpenAI-compatible RouteLLM Server
mainYou can run an OpenAI-compatible server that allows any existing OpenAI client to use RouteLLM routing. Set your provider API keys as environment variables before launching.
export OPENAI_API_KEY=sk-XXXXXX export ANYSCALE_API_KEY=esecret_XXXXXX python -m routellm.openai_server --routers mf --strong-model gpt-4-1106-preview --weak-model anyscale/mistralai/Mixtral-8x7B-Instruct-v0.1Once running, clients can request routing by setting the
modelfield torouter-[ROUTER_NAME]-[THRESHOLD](e.g.,router-mf-0.5).python -m routellm.openai_server --routers mf --strong-model gpt-4-1106-preview --weak-model anyscale/mistralai/Mixtral-8x7B-Instruct-v0.1Implement a new benchmark
mainTo add a new benchmark to RouteLLM:
- Implement the abstract
Benchmarkclass inbenchmarks.py. - Update the
evaluate.pymodule to properly initialize your new benchmark class.
Best Practice: Ideally, benchmark results should be precomputed to avoid regenerating them during every evaluation run. Refer to existing benchmarks in the repository for implementation patterns.
- Implement the abstract
Install RouteLLM
mainYou can install RouteLLM either via PyPI or from the source code.
From PyPI
pip install "routellm[serve,eval]"From source
git clone https://github.com/lm-sys/RouteLLM.git cd RouteLLM pip install -e .[serve,eval]pip install "routellm[serve,eval]"Configure RouteLLM routers
mainRouter configurations can be specified in two ways:
- Via the
configargument when initializing aController. - Via a YAML file using the
--configflag in the CLI.
The configuration is a top-level mapping where the keys are the router names and the values are the keyword arguments used to initialize those routers. Example configurations for routers trained on Arena data can be found in
config.example.yaml.- Via the
Route requests using the model name format
mainThe RouteLLM server uses the
modelfield in the Chat Completion request to determine routing parameters. The model name must follow the format:router-[router name]-[threshold]For example,
router-bert-0.7tells the server to use thebertrouter with a cost/quality threshold of0.7. The router type and threshold are extracted from this string to process that specific request.Integrate with Unify AI via OpenAI API
mainTo use Unify AI as a router in an OpenAI-compatible workflow, set the
base_urltohttps://api.unify.ai/v0/and provide yourUNIFY_API_KEY. You must specify the desired router and the supported models in themodelstring.client = openai.OpenAI( base_url="https://api.unify.ai/v0/", api_key="UNIFY_API_KEY" ) response = client.chat.completions.create( model="router@q:1|c:1.71e-03|t:1.10e-05|i:1.09e-03|models:gpt-4-turbo,mixtral-8x7b-instruct-v0.1", ... )Integrate with Martian via OpenAI API
mainTo use Martian as a router, set the
base_urltohttps://withmartian.com/api/openai/v1and provide yourMARTIAN_API_KEY. When calling theroutermodel, use theextra_bodyparameter to pass a list ofmodelsand amax_cost_per_million_tokensvalue to control the routing cost threshold.client = openai.OpenAI( base_url="https://withmartian.com/api/openai/v1", api_key="MARTIAN_API_KEY", ) response = client.chat.completions.create( model="router", extra_body={ "models": ["gpt-4-turbo-128k", "llama-2-70b-chat"], "max_cost_per_million_tokens": 10.45, }, ... )Reference: Supported Routers
mainRouteLLM supports the following trained routers (optimized for the
gpt-4-1106-previewandmixtral-8x7b-instruct-v0.1pair, but generalizable to others):mf: Matrix factorization model trained on preference data (recommended).sw_ranking: Weighted Elo calculation based on prompt similarity.bert: BERT classifier trained on preference data.causal_llm: LLM-based classifier tuned on preference data.random: Randomly routes to either model.