The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
[Feat-Router] Allow setting which environment to use a model on (#5892)
Ishaan Jaff4ec4d02474c7
diff --git a/docs/my-website/docs/proxy/configs.md b/docs/my-website/docs/proxy/configs.mdindex 980a781ac5f..3e2d1f8602f 100644--- a/docs/my-website/docs/proxy/configs.md+++ b/docs/my-website/docs/proxy/configs.md@@ -94,43 +94,23 @@ Run with `--detailed_debug` if you need detailed debug logs```shell$ litellm --config /path/to/config.yaml --detailed_debug-:::+```-### Using Proxy - Curl Request, OpenAI Package, Langchain, Langchain JS-Calling a model group+:::-<Tabs>-<TabItem value="Curl" label="Curl Request">+#### Step 3: Test itSends request to model where `model_name=gpt-3.5-turbo` on config.yaml.If multiple with `model_name=gpt-3.5-turbo` does [Load Balancing](https://docs.litellm.ai/docs/proxy/load_balancing)-```shell-curl --location 'http://0.0.0.0:4000/chat/completions' \---header 'Content-Type: application/json' \---data ' {- "model": "gpt-3.5-turbo",- "messages": [- {- "role": "user",- "content": "what llm are you"- }- ],- }-'-```-</TabItem>--<TabItem value="Curl2" label="Curl Request: Bedrock">--Sends this request to model where `model_name=bedrock-claude-v1` on config.yaml+**[Langchain, OpenAI SDK Usage Examples](../proxy/user_keys#request-format)**```shellcurl --location 'http://0.0.0.0:4000/chat/completions' \--header 'Content-Type: application/json' \--data ' {- "model": "bedrock-claude-v1",+ "model": "gpt-3.5-turbo","messages": [{"role": "user",@@ -140,85 +120,10 @@ curl --location 'http://0.0.0.0:4000/chat/completions' \}'```-</TabItem>-<TabItem value="openai" label="OpenAI v1.0.0+">--```python-import openai-client = openai.OpenAI(- api_key="anything",- base_url="http://0.0.0.0:4000"-)--# Sends request to model where `model_name=gpt-3.5-turbo` on config.yaml.-response = client.chat.completions.create(model="gpt-3.5-turbo", messages = [- {- "role": "user",- "content": "this is a test request, write a short poem"- }-])--print(response)--# Sends this request to model where `model_name=bedrock-claude-v1` on config.yaml-response = client.chat.completions.create(model="bedrock-claude-v1", messages = [- {- "role": "user",- "content": "this is a test request, write a short poem"- }-])--print(response)--```--</TabItem>-<TabItem value="langchain" label="Langchain Python">--```python-from langchain.chat_models import ChatOpenAI-from langchain.prompts.chat import (- ChatPromptTemplate,- HumanMessagePromptTemplate,- SystemMessagePromptTemplate,-)-from langchain.schema import HumanMessage, SystemMessage--messages = [- SystemMessage(- content="You are a helpful assistant that im using to make a test request to."- ),- HumanMessage(- content="test from litellm. tell me why it's amazing in 1 sentence"- ),-]--# Sends request to model where `model_name=gpt-3.5-turbo` on config.yaml.-chat = ChatOpenAI(- openai_api_base="http://0.0.0.0:4000", # set openai base to the proxy- model = "gpt-3.5-turbo",- temperature=0.1-)--response = chat(messages)-print(response)--# Sends request to model where `model_name=bedrock-claude-v1` on config.yaml.-claude_chat = ChatOpenAI(- openai_api_base="http://0.0.0.0:4000", # set openai base to the proxy- model = "bedrock-claude-v1",- temperature=0.1-)--response = claude_chat(messages)-print(response)-```--</TabItem>-</Tabs>+## LLM configs `model_list`-## Save Model-specific params (API Base, Keys, Temperature, Max Tokens, Organization, Headers etc.)+### Model-specific params (API Base, Keys, Temperature, Max Tokens, Organization, Headers etc.)You can use the config to save model-specific information like api_base, api_key, temperature, max_tokens, etc.[**All input params**](https://docs.litellm.ai/docs/completion/input#input-params-1)@@ -259,40 +164,175 @@ model_list:$ litellm --config /path/to/config.yaml```-## Use CONFIG_FILE_PATH for proxy (Easier Azure container deployment)+**Expected Logs:**-1. Setup config.yaml+Look for this line in your console logs to confirm the config.yaml was loaded in correctly.+```+LiteLLM: Proxy initialized with Config, Set models:+```++### Embedding Models - Use Sagemaker, Bedrock, Azure, OpenAI, XInference++See supported Embedding Providers & Models [here](https://docs.litellm.ai/docs/embedding/supported_embedding)+++<Tabs>+<TabItem value="bedrock" label="Bedrock Completion/Chat">```yamlmodel_list:- - model_name: gpt-3.5-turbo+ - model_name: bedrock-coherelitellm_params:- model: gpt-3.5-turbo- api_key: os.environ/OPENAI_API_KEY+ model: "bedrock/cohere.command-text-v14"+ aws_region_name: "us-west-2"+ - model_name: bedrock-cohere+ litellm_params:+ model: "bedrock/cohere.command-text-v14"+ aws_region_name: "us-east-2"+ - model_name: bedrock-cohere+ litellm_params:+ model: "bedrock/cohere.command-text-v14"+ aws_region_name: "us-east-1"+```-2. Store filepath as env var+</TabItem>-```bash-CONFIG_FILE_PATH="/path/to/config.yaml"+<TabItem value="sagemaker" label="Sagemaker, Bedrock Embeddings">++Here's how to route between GPT-J embedding (sagemaker endpoint), Amazon Titan embedding (Bedrock) and Azure OpenAI embedding on the proxy server:++```yaml+model_list:+ - model_name: sagemaker-embeddings+ litellm_params:+ model: "sagemaker/berri-benchmarking-gpt-j-6b-fp16"+ - model_name: amazon-embeddings+ litellm_params:+ model: "bedrock/amazon.titan-embed-text-v1"+ - model_name: azure-embeddings+ litellm_params:+ model: "azure/azure-embedding-model"+ api_base: "os.environ/AZURE_API_BASE" # os.getenv("AZURE_API_BASE")+ api_key: "os.environ/AZURE_API_KEY" # os.getenv("AZURE_API_KEY")+ api_version: "2023-07-01-preview"++general_settings:+ master_key: sk-1234 # [OPTIONAL] if set all calls to proxy will require either this key or a valid generated token```-3. Start Proxy+</TabItem>-```bash-$ litellm+<TabItem value="Hugging Face emb" label="Hugging Face Embeddings">+LiteLLM Proxy supports all <a href="https://huggingface.co/models?pipeline_tag=feature-extraction">Feature-Extraction Embedding models</a>.++```yaml+model_list:+ - model_name: deployed-codebert-base+ litellm_params:+ # send request to deployed hugging face inference endpoint+ model: huggingface/microsoft/codebert-base # add huggingface prefix so it routes to hugging face+ api_key: hf_LdS # api key for hugging face inference endpoint+ api_base: https://uysneno1wv2wd4lw.us-east-1.aws.endpoints.huggingface.cloud # your hf inference endpoint+ - model_name: codebert-base+ litellm_params:+ # no api_base set, sends request to hugging face free inference api https://api-inference.huggingface.co/models/+ model: huggingface/microsoft/codebert-base # add huggingface prefix so it routes to hugging face+ api_key: hf_LdS # api key for hugging face-# RUNNING on http://0.0.0.0:4000```-**Expected Logs:**+</TabItem>-Look for this line in your console logs to confirm the config.yaml was loaded in correctly.+<TabItem value="azure" label="Azure OpenAI Embeddings">++```yaml+model_list:+ - model_name: azure-embedding-model # model group+ litellm_params:+ model: azure/azure-embedding-model # model name for litellm.embedding(model=azure/azure-embedding-model) call+ api_base: your-azure-api-base+ api_key: your-api-key+ api_version: 2023-07-01-preview```-LiteLLM: Proxy initialized with Config, Set models:++</TabItem>++<TabItem value="openai" label="OpenAI Embeddings">++```yaml+model_list:+- model_name: text-embedding-ada-002 # model group+ litellm_params:+ model: text-embedding-ada-002 # model name for litellm.embedding(model=text-embedding-ada-002)+ api_key: your-api-key-1+- model_name: text-embedding-ada-002+ litellm_params:+ model: text-embedding-ada-002+ api_key: your-api-key-2+```++</TabItem>+++<TabItem value="xinf" label="XInference">++https://docs.litellm.ai/docs/providers/xinference++**Note add `xinference/` prefix to `litellm_params`: `model` so litellm knows to route to OpenAI**++```yaml+model_list:+- model_name: embedding-model # model group+ litellm_params:+ model: xinference/bge-base-en # model name for litellm.embedding(model=xinference/bge-base-en)+ api_base: http://0.0.0.0:9997/v1```-## Multiple OpenAI Organizations+</TabItem>++<TabItem value="openai emb" label="OpenAI Compatible Embeddings">++<p>Use this for calling <a href="https://github.com/xorbitsai/inference">/embedding endpoints on OpenAI Compatible Servers</a>.</p>++**Note add `openai/` prefix to `litellm_params`: `model` so litellm knows to route to OpenAI**++```yaml+model_list:+- model_name: text-embedding-ada-002 # model group+ litellm_params:+ model: openai/<your-model-name> # model name for litellm.embedding(model=text-embedding-ada-002)+ api_base: <model-api-base>+```++</TabItem>+</Tabs>++#### Start Proxy++```shell+litellm --config config.yaml+```++#### Make Request+Sends Request to `bedrock-cohere`++```shell+curl --location 'http://0.0.0.0:4000/chat/completions' \+ --header 'Content-Type: application/json' \+ --data ' {+ "model": "bedrock-cohere",+ "messages": [+ {+ "role": "user",+ "content": "gm"+ }+ ]+}'+```+++### Multiple OpenAI OrganizationsAdd all openai models across all OpenAI organizations with just 1 model definition@@ -318,7 +358,7 @@ curl --location 'http://0.0.0.0:4000/v1/model/info' \```-## Provider specific wildcard routing+### Provider specific wildcard routing**Proxy all models from a provider**Use this if you want to **proxy all models from a specific provider without defining them on the config.yaml**@@ -371,7 +411,7 @@ curl http://localhost:4000/v1/chat/completions \}'```-## Load Balancing+### Load Balancing:::infoFor more on this, go to [this page](https://docs.litellm.ai/docs/proxy/load_balancing)@@ -439,7 +479,6 @@ router_settings: # router_settings are optionalYou can view your cost once you set up [Virtual keys](https://docs.litellm.ai/docs/proxy/virtual_keys) or [custom_callbacks](https://docs.litellm.ai/docs/proxy/logging)-## Load API Keys### Load API Keys / config values from Environment@@ -463,39 +502,47 @@ model_list:s/o to [@David Manouchehri](https://www.linkedin.com/in/davidmanouchehri/) for helping with this.-### Load API Keys from Azure Vault+### Load API Keys from Secret Managers (Azure Vault, etc)-1. Install Proxy dependencies-```bash-$ pip install 'litellm[proxy]' 'litellm[extra_proxy]'-```+[**Using Secret Managers with LiteLLM Proxy**](../secret)-2. Save Azure details in your environment-```bash-export["AZURE_CLIENT_ID"]="your-azure-app-client-id"-export["AZURE_CLIENT_SECRET"]="your-azure-app-client-secret"-export["AZURE_TENANT_ID"]="your-azure-tenant-id"-export["AZURE_KEY_VAULT_URI"]="your-azure-key-vault-uri"-```-3. Add to proxy config.yaml-```yaml-model_list:- - model_name: "my-azure-models" # model alias- litellm_params:- model: "azure/<your-deployment-name>"- api_key: "os.environ/AZURE-API-KEY" # reads from key vault - get_secret("AZURE_API_KEY")- api_base: "os.environ/AZURE-API-BASE" # reads from key vault - get_secret("AZURE_API_BASE")+### Set Supported Environments for a model - `production`, `staging`, `development`-general_settings:- use_azure_key_vault: True-```+Use this if you want to control which model is exposed on a specific litellm environment-You can now test this by starting your proxy:-```bash-litellm --config /path/to/config.yaml+Supported Environments:+- `production`+- `staging`+- `development`++1. Set `LITELLM_ENVIRONMENT="<environment>"` in your environment. Can be one of `production`, `staging` or `development`+++2. For each model set the list of supported environments in `model_info.supported_environments`+```yaml+model_list:+ - model_name: gpt-3.5-turbo+ litellm_params:+ model: openai/gpt-3.5-turbo+ api_key: os.environ/OPENAI_API_KEY+ model_info:+ supported_environments: ["development", "production", "staging"]+ - model_name: gpt-4+ litellm_params:+ model: openai/gpt-4+ api_key: os.environ/OPENAI_API_KEY+ model_info:+ supported_environments: ["production", "staging"]+ - model_name: gpt-4o+ litellm_params:+ model: openai/gpt-4o+ api_key: os.environ/OPENAI_API_KEY+ model_info:+ supported_environments: ["production"]```+### Set Custom Prompt TemplatesLiteLLM by default checks if a model has a [prompt template and applies it](../completion/prompt_formatting.md) (e.g. if a huggingface model has a saved chat template in it's tokenizer_config.json). However, you can also set a custom prompt template on your proxy in the `config.yaml`:@@ -523,210 +570,9 @@ model_list:$ litellm --config /path/to/config.yaml```-## Setting Embedding Models--See supported Embedding Providers & Models [here](https://docs.litellm.ai/docs/embedding/supported_embedding)+## General Settings `general_settings` (DB Connection, etc)-### Use Sagemaker, Bedrock, Azure, OpenAI, XInference-#### Create Config.yaml--<Tabs>-<TabItem value="bedrock" label="Bedrock Completion/Chat">--```yaml-model_list:- - model_name: bedrock-cohere- litellm_params:- model: "bedrock/cohere.command-text-v14"- aws_region_name: "us-west-2"- - model_name: bedrock-cohere- litellm_params:- model: "bedrock/cohere.command-text-v14"- aws_region_name: "us-east-2"- - model_name: bedrock-cohere- litellm_params:- model: "bedrock/cohere.command-text-v14"- aws_region_name: "us-east-1"--```--</TabItem>--<TabItem value="sagemaker" label="Sagemaker, Bedrock Embeddings">--Here's how to route between GPT-J embedding (sagemaker endpoint), Amazon Titan embedding (Bedrock) and Azure OpenAI embedding on the proxy server:--```yaml-model_list:- - model_name: sagemaker-embeddings- litellm_params:- model: "sagemaker/berri-benchmarking-gpt-j-6b-fp16"- - model_name: amazon-embeddings- litellm_params:- model: "bedrock/amazon.titan-embed-text-v1"- - model_name: azure-embeddings- litellm_params:- model: "azure/azure-embedding-model"- api_base: "os.environ/AZURE_API_BASE" # os.getenv("AZURE_API_BASE")- api_key: "os.environ/AZURE_API_KEY" # os.getenv("AZURE_API_KEY")- api_version: "2023-07-01-preview"--general_settings:- master_key: sk-1234 # [OPTIONAL] if set all calls to proxy will require either this key or a valid generated token-```--</TabItem>--<TabItem value="Hugging Face emb" label="Hugging Face Embeddings">-LiteLLM Proxy supports all <a href="https://huggingface.co/models?pipeline_tag=feature-extraction">Feature-Extraction Embedding models</a>.--```yaml-model_list:- - model_name: deployed-codebert-base- litellm_params:- # send request to deployed hugging face inference endpoint- model: huggingface/microsoft/codebert-base # add huggingface prefix so it routes to hugging face- api_key: hf_LdS # api key for hugging face inference endpoint- api_base: https://uysneno1wv2wd4lw.us-east-1.aws.endpoints.huggingface.cloud # your hf inference endpoint- - model_name: codebert-base- litellm_params:- # no api_base set, sends request to hugging face free inference api https://api-inference.huggingface.co/models/- model: huggingface/microsoft/codebert-base # add huggingface prefix so it routes to hugging face- api_key: hf_LdS # api key for hugging face--```--</TabItem>--<TabItem value="azure" label="Azure OpenAI Embeddings">--```yaml-model_list:- - model_name: azure-embedding-model # model group- litellm_params:- model: azure/azure-embedding-model # model name for litellm.embedding(model=azure/azure-embedding-model) call- api_base: your-azure-api-base- api_key: your-api-key- api_version: 2023-07-01-preview-```--</TabItem>--<TabItem value="openai" label="OpenAI Embeddings">--```yaml-model_list:-- model_name: text-embedding-ada-002 # model group- litellm_params:- model: text-embedding-ada-002 # model name for litellm.embedding(model=text-embedding-ada-002)- api_key: your-api-key-1-- model_name: text-embedding-ada-002- litellm_params:- model: text-embedding-ada-002- api_key: your-api-key-2-```--</TabItem>---<TabItem value="xinf" label="XInference">--https://docs.litellm.ai/docs/providers/xinference--**Note add `xinference/` prefix to `litellm_params`: `model` so litellm knows to route to OpenAI**--```yaml-model_list:-- model_name: embedding-model # model group- litellm_params:- model: xinference/bge-base-en # model name for litellm.embedding(model=xinference/bge-base-en)- api_base: http://0.0.0.0:9997/v1-```--</TabItem>--<TabItem value="openai emb" label="OpenAI Compatible Embeddings">--<p>Use this for calling <a href="https://github.com/xorbitsai/inference">/embedding endpoints on OpenAI Compatible Servers</a>.</p>--**Note add `openai/` prefix to `litellm_params`: `model` so litellm knows to route to OpenAI**--```yaml-model_list:-- model_name: text-embedding-ada-002 # model group- litellm_params:- model: openai/<your-model-name> # model name for litellm.embedding(model=text-embedding-ada-002)- api_base: <model-api-base>-```--</TabItem>-</Tabs>--#### Start Proxy--```shell-litellm --config config.yaml-```--#### Make Request-Sends Request to `bedrock-cohere`--```shell-curl --location 'http://0.0.0.0:4000/chat/completions' \- --header 'Content-Type: application/json' \- --data ' {- "model": "bedrock-cohere",- "messages": [- {- "role": "user",- "content": "gm"- }- ]-}'-```--## ✨ IP Address Filtering--:::info--You need a LiteLLM License to unlock this feature. [Grab time](https://calendly.com/d/4mp-gd3-k5k/litellm-1-1-onboarding-chat), to get one today!--:::--Restrict which IP's can call the proxy endpoints.--```yaml-general_settings:- allowed_ips: ["192.168.1.1"]-```--**Expected Response** (if IP not listed)--```bash-{- "error": {- "message": "Access forbidden: IP address not allowed.",- "type": "auth_error",- "param": "None",- "code": 403- }-}-```----## Disable Swagger UI--To disable the Swagger docs from the base url, set--```env-NO_DOCS="True"-```--in your environment, and restart the proxy.---## Configure DB Pool Limits + Connection Timeouts+### Configure DB Pool Limits + Connection Timeouts```yamlgeneral_settings:@@ -812,3 +658,43 @@ general_settings:}```+## Extras+++### Disable Swagger UI++To disable the Swagger docs from the base url, set++```env+NO_DOCS="True"+```++in your environment, and restart the proxy.++### Use CONFIG_FILE_PATH for proxy (Easier Azure container deployment)++1. Setup config.yaml++```yaml+model_list:+ - model_name: gpt-3.5-turbo+ litellm_params:+ model: gpt-3.5-turbo+ api_key: os.environ/OPENAI_API_KEY+```++2. Store filepath as env var++```bash+CONFIG_FILE_PATH="/path/to/config.yaml"+```++3. Start Proxy++```bash+$ litellm++# RUNNING on http://0.0.0.0:4000+```++diff --git a/docs/my-website/docs/proxy/ip_address.md b/docs/my-website/docs/proxy/ip_address.mdnew file mode 100644index 00000000000..31ffd98a460--- /dev/null+++ b/docs/my-website/docs/proxy/ip_address.md@@ -0,0 +1,28 @@++# ✨ IP Address Filtering++:::info++You need a LiteLLM License to unlock this feature. [Grab time](https://calendly.com/d/4mp-gd3-k5k/litellm-1-1-onboarding-chat), to get one today!++:::++Restrict which IP's can call the proxy endpoints.++```yaml+general_settings:+ allowed_ips: ["192.168.1.1"]+```++**Expected Response** (if IP not listed)++```bash+{+ "error": {+ "message": "Access forbidden: IP address not allowed.",+ "type": "auth_error",+ "param": "None",+ "code": 403+ }+}+```\ No newline at end of filediff --git a/docs/my-website/docs/proxy/prometheus.md b/docs/my-website/docs/proxy/prometheus.mdindex 1a042271428..4cd9002e06c 100644--- a/docs/my-website/docs/proxy/prometheus.md+++ b/docs/my-website/docs/proxy/prometheus.md@@ -1,7 +1,7 @@import Tabs from '@theme/Tabs';import TabItem from '@theme/TabItem';-# 📈 [BETA] Prometheus metrics+# 📈 Prometheus metrics:::infodiff --git a/docs/my-website/docs/proxy/token_auth.md b/docs/my-website/docs/proxy/token_auth.mdindex 87d1b524338..d8e28b2babe 100644--- a/docs/my-website/docs/proxy/token_auth.md+++ b/docs/my-website/docs/proxy/token_auth.md@@ -1,7 +1,7 @@import Tabs from '@theme/Tabs';import TabItem from '@theme/TabItem';-# [BETA] JWT-based Auth+# JWT-based AuthUse JWT's to auth admins / projects into the proxy.diff --git a/docs/my-website/sidebars.js b/docs/my-website/sidebars.jsindex f1549da0a69..e0512f0804f 100644--- a/docs/my-website/sidebars.js+++ b/docs/my-website/sidebars.js@@ -50,7 +50,7 @@ const sidebars = {{type: "category",label: "🔑 Authentication",- items: ["proxy/virtual_keys", "proxy/token_auth", "proxy/oauth2"],+ items: ["proxy/virtual_keys", "proxy/token_auth", "proxy/oauth2", "proxy/ip_address"],},{type: "category",diff --git a/litellm/proxy/proxy_config.yaml b/litellm/proxy/proxy_config.yamlindex 82913114602..4601d498055 100644--- a/litellm/proxy/proxy_config.yaml+++ b/litellm/proxy/proxy_config.yaml@@ -2,22 +2,21 @@ model_list:- model_name: gpt-3.5-turbolitellm_params:model: openai/gpt-3.5-turbo- api_key: fake-key- api_base: https://exampleopenaiendpoint-production.up.railway.app/- tags: ["teamB"]+ api_key: os.environ/OPENAI_API_KEYmodel_info:- id: "team-b-model"- - model_name: rerank-english-v3.0+ supported_environments: ["development", "production", "staging"]+ - model_name: gpt-4litellm_params:- model: cohere/rerank-english-v3.0- api_key: os.environ/COHERE_API_KEY- - model_name: llava-hf+ model: openai/gpt-4+ api_key: os.environ/OPENAI_API_KEY+ model_info:+ supported_environments: ["production", "staging"]+ - model_name: gpt-4olitellm_params:- model: openai/llava-hf/llava-v1.6-vicuna-7b-hf- api_base: http://localhost:8000- api_key: fake-key+ model: openai/gpt-4o+ api_key: os.environ/OPENAI_API_KEYmodel_info:- supports_vision: True+ supported_environments: ["production"]litellm_settings:diff --git a/litellm/router.py b/litellm/router.pyindex b3a07ad4e56..2a177a2a20f 100644--- a/litellm/router.py+++ b/litellm/router.py@@ -90,6 +90,7 @@ from litellm.types.llms.openai import ()from litellm.types.router import (SPECIAL_MODEL_INFO_PARAMS,+ VALID_LITELLM_ENVIRONMENTS,AlertingConfig,AllowedFailsPolicy,AssistantsTypedDict,@@ -3973,12 +3974,55 @@ class Router:})+ ## Check if LLM Deployment is allowed for this deployment+ if deployment.model_info and "supported_environments" in deployment.model_info:+ if (+ self.deployment_is_active_for_environment(deployment=deployment)+ is not True+ ):+ return+deployment = self._add_deployment(deployment=deployment)model = deployment.to_json(exclude_none=True)self.model_list.append(model)+ def deployment_is_active_for_environment(self, deployment: Deployment) -> bool:+ """+ Function to check if a llm deployment is active for a given environment. Allows using the same config.yaml across multople environments++ Requires `LITELLM_ENVIRONMENT` to be set in .env. Valid values for environment:+ - development+ - staging+ - production++ Raises:+ - ValueError: If LITELLM_ENVIRONMENT is not set in .env or not one of the valid values+ - ValueError: If supported_environments is not set in model_info or not one of the valid values+ """+ litellm_environment = litellm.get_secret_str(secret_name="LITELLM_ENVIRONMENT")+ if litellm_environment is None:+ raise ValueError(+ f"Set 'supported_environments' for model but not 'LITELLM_ENVIRONMENT' set in .env"+ )++ if litellm_environment not in VALID_LITELLM_ENVIRONMENTS:+ raise ValueError(+ f"LITELLM_ENVIRONMENT must be one of {VALID_LITELLM_ENVIRONMENTS}. but set as: {litellm_environment}"+ )++ for _env in deployment.model_info["supported_environments"]:+ if _env not in VALID_LITELLM_ENVIRONMENTS:+ raise ValueError(+ f"supported_environments must be one of {VALID_LITELLM_ENVIRONMENTS}. but set as: {_env} for deployment: {deployment}"+ )++ # validate litellm_environment is one of LiteLLMEnvironment+ if litellm_environment in deployment.model_info["supported_environments"]:+ return True+ return False+def set_model_list(self, model_list: list):original_model_list = copy.deepcopy(model_list)self.model_list = []diff --git a/litellm/tests/test_router_init.py b/litellm/tests/test_router_init.pyindex 13167c10f08..3733af252be 100644--- a/litellm/tests/test_router_init.py+++ b/litellm/tests/test_router_init.py@@ -636,3 +636,63 @@ def test_init_clients_async_mode():assert router.cache.get_cache(f"{model_id}_stream_async_client") is not Noneexcept Exception as e:pytest.fail(f"Error occurred: {e}")+++ "environment,expected_models",+ [+ ("development", ["gpt-3.5-turbo"]),+ ("production", ["gpt-4", "gpt-3.5-turbo", "gpt-4o"]),+ ],+)+def test_init_router_with_supported_environments(environment, expected_models):+ """+ Tests that the correct models are setup on router when LITELLM_ENVIRONMENT is set+ """+ os.environ["LITELLM_ENVIRONMENT"] = environment+ model_list = [+ {+ "model_name": "gpt-3.5-turbo",+ "litellm_params": {+ "model": "azure/chatgpt-v-2",+ "api_key": os.getenv("AZURE_API_KEY"),+ "api_version": os.getenv("AZURE_API_VERSION"),+ "api_base": os.getenv("AZURE_API_BASE"),+ "timeout": 0.01,+ "stream_timeout": 0.000_001,+ "max_retries": 7,+ },+ "model_info": {"supported_environments": ["development", "production"]},+ },+ {+ "model_name": "gpt-4",+ "litellm_params": {+ "model": "openai/gpt-4",+ "api_key": os.getenv("OPENAI_API_KEY"),+ "timeout": 0.01,+ "stream_timeout": 0.000_001,+ "max_retries": 7,+ },+ "model_info": {"supported_environments": ["production"]},+ },+ {+ "model_name": "gpt-4o",+ "litellm_params": {+ "model": "openai/gpt-4o",+ "api_key": os.getenv("OPENAI_API_KEY"),+ "timeout": 0.01,+ "stream_timeout": 0.000_001,+ "max_retries": 7,+ },+ "model_info": {"supported_environments": ["production"]},+ },+ ]+ router = Router(model_list=model_list, set_verbose=True)+ _model_list = router.get_model_names()++ print("model_list: ", _model_list)+ print("expected_models: ", expected_models)++ assert set(_model_list) == set(expected_models)++ os.environ.pop("LITELLM_ENVIRONMENT")diff --git a/litellm/types/router.py b/litellm/types/router.pyindex 306dfcba1be..cfb90814bc6 100644--- a/litellm/types/router.py+++ b/litellm/types/router.py@@ -596,3 +596,10 @@ class RouterRateLimitError(ValueError):class RouterModelGroupAliasItem(TypedDict):model: strhidden: bool # if 'True', don't return on `.get_model_list`+++VALID_LITELLM_ENVIRONMENTS = [+ "development",+ "staging",+ "production",+]