Skip to content

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]

Optimize CI: parallelize router and guardrails test jobs, fix test isolation

yuneng-jiangf838bea85b3b
diff --git a/.circleci/config.yml b/.circleci/config.yml
index 862a51cd3f0..50d695d7fc0 100644
--- a/.circleci/config.yml
+++ b/.circleci/config.yml
@@ -657,6 +657,7 @@ jobs:
username: ${DOCKERHUB_USERNAME}
password: ${DOCKERHUB_PASSWORD}
working_directory: ~/project
+ parallelism: 4
steps:
- checkout
- setup_google_dns
@@ -671,6 +672,7 @@ jobs:
pip install "pytest-retry==1.6.3"
pip install "pytest-asyncio==0.21.1"
pip install "pytest-xdist==3.6.1"
+ pip install "pytest-timeout==2.2.0"
pip install semantic_router --no-deps
pip install aurelio_sdk --no-deps
# Run pytest and generate JUnit XML report
@@ -680,13 +682,25 @@ jobs:
command: |
pwd
ls
- python -m pytest tests/local_testing --cov=litellm --cov-report=xml -vv -k "router" -v --junitxml=test-results/junit.xml --durations=5
+ TEST_FILES=$(circleci tests glob "tests/local_testing/**/test_*.py")
+
+ echo "$TEST_FILES" | circleci tests run \
+ --split-by=timings \
+ --verbose \
+ --command="xargs python -m pytest \
+ -vv \
+ --cov=litellm \
+ --cov-report=xml \
+ -k 'router' \
+ --junitxml=test-results/junit.xml \
+ --durations=5 \
+ --timeout=300 --timeout_method=thread"
no_output_timeout: 15m
- run:
name: Rename the coverage files
command: |
- mv coverage.xml litellm_router_coverage.xml
- mv .coverage litellm_router_coverage
+ mv coverage.xml litellm_router_coverage.xml || true
+ mv .coverage litellm_router_coverage || true
# Store test results
- store_test_results:
path: test-results
@@ -1459,13 +1473,15 @@ jobs:
pip install "pydantic==2.10.2"
pip install "boto3==1.36.0"
pip install "semantic_router==0.1.10"
+ pip install "pytest-xdist==3.6.1"
+ pip install "pytest-timeout==2.2.0"
# Run pytest and generate JUnit XML report
- run:
name: Run tests
command: |
pwd
ls
- python -m pytest -vv tests/guardrails_tests --cov=litellm --cov-report=xml -x -s -v --junitxml=test-results/junit.xml --durations=5
+ LITELLM_LOG=WARNING python -m pytest tests/guardrails_tests -vv --cov=litellm --cov-report=xml --junitxml=test-results/junit.xml --durations=5 -n 4 --timeout=120 --timeout_method=thread
no_output_timeout: 15m
- run:
name: Rename the coverage files
diff --git a/tests/guardrails_tests/conftest.py b/tests/guardrails_tests/conftest.py
index e47df872d3f..c57d4ed5de7 100644
--- a/tests/guardrails_tests/conftest.py
+++ b/tests/guardrails_tests/conftest.py
@@ -1,4 +1,9 @@
# conftest.py
+#
+# xdist-compatible test isolation for guardrails tests.
+# Pattern matches tests/test_litellm/conftest.py:
+# - Function-scoped fixture saves/restores litellm globals (no reload)
+# - Module-scoped fixture reloads only in single-process mode
import importlib
import os
@@ -10,58 +15,85 @@ sys.path.insert(
0, os.path.abspath("../..")
) # Adds the parent directory to the system path
import litellm
-import asyncio
[email protected](scope="session")
-def event_loop():
- try:
- loop = asyncio.get_running_loop()
- except RuntimeError:
- loop = asyncio.new_event_loop()
- yield loop
- loop.close()
@pytest.fixture(scope="function", autouse=True)
-def setup_and_teardown():
+def isolate_litellm_state():
"""
- This fixture reloads litellm before every function. To speed up testing by removing callbacks being chained.
+ Per-function isolation fixture.
+
+ Saves and restores litellm callback/global state so tests don't leak
+ side effects. Works safely under pytest-xdist parallel execution.
"""
- curr_dir = os.getcwd() # Get the current working directory
- sys.path.insert(
- 0, os.path.abspath("../..")
- ) # Adds the project directory to the system path
+ # Save original callback state
+ original_state = {}
+ for attr in (
+ "callbacks",
+ "success_callback",
+ "failure_callback",
+ "_async_success_callback",
+ "_async_failure_callback",
+ ):
+ if hasattr(litellm, attr):
+ val = getattr(litellm, attr)
+ original_state[attr] = val.copy() if val else []
+
+ # Save other globals that tests commonly mutate
+ for attr in ("set_verbose", "cache", "num_retries"):
+ if hasattr(litellm, attr):
+ original_state[attr] = getattr(litellm, attr)
+
+ # Flush cache before test
+ if hasattr(litellm, "in_memory_llm_clients_cache"):
+ litellm.in_memory_llm_clients_cache.flush_cache()
+
+ # Clear callbacks before test
+ for attr in (
+ "success_callback",
+ "failure_callback",
+ "_async_success_callback",
+ "_async_failure_callback",
+ ):
+ if hasattr(litellm, attr):
+ setattr(litellm, attr, [])
- import litellm
- from litellm import Router
- import asyncio
+ yield
- from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER
- # flush all logs
- asyncio.run(GLOBAL_LOGGING_WORKER.clear_queue())
+ # Restore all saved state
+ if hasattr(litellm, "in_memory_llm_clients_cache"):
+ litellm.in_memory_llm_clients_cache.flush_cache()
+ for attr, original_value in original_state.items():
+ if hasattr(litellm, attr):
+ setattr(litellm, attr, original_value)
- importlib.reload(litellm)
- try:
- if hasattr(litellm, "proxy") and hasattr(litellm.proxy, "proxy_server"):
- import litellm.proxy.proxy_server
[email protected](scope="module", autouse=True)
+def setup_and_teardown():
+ """
+ Module-scoped setup. Reloads litellm only in single-process mode
+ (skipped under xdist to avoid cross-worker interference).
+ """
+ sys.path.insert(0, os.path.abspath("../.."))
- importlib.reload(litellm.proxy.proxy_server)
- except Exception as e:
- print(f"Error reloading litellm.proxy.proxy_server: {e}")
+ import litellm
- import asyncio
+ worker_id = os.environ.get("PYTEST_XDIST_WORKER", None)
+ if worker_id is None:
+ importlib.reload(litellm)
- loop = asyncio.get_event_loop_policy().new_event_loop()
- asyncio.set_event_loop(loop)
- print(litellm)
- # from litellm import Router, completion, aembedding, acompletion, embedding
- yield
+ try:
+ if hasattr(litellm, "proxy") and hasattr(litellm.proxy, "proxy_server"):
+ import litellm.proxy.proxy_server
- # Teardown code (executes after the yield point)
- loop.close() # Close the loop created earlier
- asyncio.set_event_loop(None) # Remove the reference to the loop
+ importlib.reload(litellm.proxy.proxy_server)
+ except Exception as e:
+ print(f"Error reloading litellm.proxy.proxy_server: {e}")
+ if hasattr(litellm, "in_memory_llm_clients_cache"):
+ litellm.in_memory_llm_clients_cache.flush_cache()
+
+ yield
def pytest_collection_modifyitems(config, items):
diff --git a/tests/local_testing/conftest.py b/tests/local_testing/conftest.py
index 7290f3e75ff..e3809e93bdb 100644
--- a/tests/local_testing/conftest.py
+++ b/tests/local_testing/conftest.py
@@ -1,4 +1,9 @@
# conftest.py
+#
+# xdist-compatible test isolation for local_testing tests.
+# Pattern matches tests/test_litellm/conftest.py:
+# - Function-scoped fixture saves/restores litellm globals (no reload)
+# - Module-scoped fixture reloads only in single-process mode
import importlib
import os
@@ -11,61 +16,90 @@ sys.path.insert(
) # Adds the parent directory to the system path
import litellm
-import asyncio
[email protected](scope="session")
-def event_loop():
- try:
- loop = asyncio.get_running_loop()
- except RuntimeError:
- loop = asyncio.new_event_loop()
- yield loop
- loop.close()
[email protected](scope="function", autouse=True)
+def isolate_litellm_state():
+ """
+ Per-function isolation fixture.
+ Saves and restores litellm callback/global state so tests don't leak
+ side effects. Works safely under pytest-xdist parallel execution.
+ """
+ # Save original callback state
+ original_state = {}
+ for attr in (
+ "callbacks",
+ "success_callback",
+ "failure_callback",
+ "_async_success_callback",
+ "_async_failure_callback",
+ ):
+ if hasattr(litellm, attr):
+ val = getattr(litellm, attr)
+ original_state[attr] = val.copy() if val else []
+
+ # Save other globals that tests commonly mutate
+ for attr in ("set_verbose", "cache", "num_retries"):
+ if hasattr(litellm, attr):
+ original_state[attr] = getattr(litellm, attr)
+
+ # Save transport/network globals
+ for attr in ("disable_aiohttp_transport", "force_ipv4"):
+ if hasattr(litellm, attr):
+ original_state[attr] = getattr(litellm, attr)
+
+ # Flush cache before test
+ if hasattr(litellm, "in_memory_llm_clients_cache"):
+ litellm.in_memory_llm_clients_cache.flush_cache()
+
+ # Clear callbacks before test
+ for attr in (
+ "success_callback",
+ "failure_callback",
+ "_async_success_callback",
+ "_async_failure_callback",
+ ):
+ if hasattr(litellm, attr):
+ setattr(litellm, attr, [])
+ yield
+ # Restore all saved state
+ if hasattr(litellm, "in_memory_llm_clients_cache"):
+ litellm.in_memory_llm_clients_cache.flush_cache()
[email protected](scope="function", autouse=True)
+ for attr, original_value in original_state.items():
+ if hasattr(litellm, attr):
+ setattr(litellm, attr, original_value)
+
+
[email protected](scope="module", autouse=True)
def setup_and_teardown():
"""
- This fixture reloads litellm before every function. To speed up testing by removing callbacks being chained.
+ Module-scoped setup. Reloads litellm only in single-process mode
+ (skipped under xdist to avoid cross-worker interference).
"""
- curr_dir = os.getcwd() # Get the current working directory
- sys.path.insert(
- 0, os.path.abspath("../..")
- ) # Adds the project directory to the system path
+ sys.path.insert(0, os.path.abspath("../.."))
import litellm
- from litellm import Router
- import asyncio
-
- from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER
- # flush all logs
- asyncio.run(GLOBAL_LOGGING_WORKER.clear_queue())
+ worker_id = os.environ.get("PYTEST_XDIST_WORKER", None)
+ if worker_id is None:
+ importlib.reload(litellm)
- importlib.reload(litellm)
+ try:
+ if hasattr(litellm, "proxy") and hasattr(litellm.proxy, "proxy_server"):
+ import litellm.proxy.proxy_server
- try:
- if hasattr(litellm, "proxy") and hasattr(litellm.proxy, "proxy_server"):
- import litellm.proxy.proxy_server
+ importlib.reload(litellm.proxy.proxy_server)
+ except Exception as e:
+ print(f"Error reloading litellm.proxy.proxy_server: {e}")
- importlib.reload(litellm.proxy.proxy_server)
- except Exception as e:
- print(f"Error reloading litellm.proxy.proxy_server: {e}")
+ if hasattr(litellm, "in_memory_llm_clients_cache"):
+ litellm.in_memory_llm_clients_cache.flush_cache()
- import asyncio
-
- loop = asyncio.get_event_loop_policy().new_event_loop()
- asyncio.set_event_loop(loop)
- print(litellm)
- # from litellm import Router, completion, aembedding, acompletion, embedding
yield
- # Teardown code (executes after the yield point)
- loop.close() # Close the loop created earlier
- asyncio.set_event_loop(None) # Remove the reference to the loop
-
def pytest_collection_modifyitems(config, items):
# Separate tests in 'test_amazing_proxy_custom_logger.py' and other tests
diff --git a/tests/local_testing/test_acooldowns_router.py b/tests/local_testing/test_acooldowns_router.py
index 6c9067ac5cd..ff992102984 100644
--- a/tests/local_testing/test_acooldowns_router.py
+++ b/tests/local_testing/test_acooldowns_router.py
@@ -22,33 +22,37 @@ from litellm import Router
load_dotenv()
-model_list = [
- { # list of model deployments
- "model_name": "gpt-3.5-turbo", # openai model name
- "litellm_params": { # params for litellm completion/embedding call
- "model": "azure/gpt-4.1-mini",
- "api_key": "bad-key",
- "api_version": os.getenv("AZURE_API_VERSION"),
- "api_base": os.getenv("AZURE_API_BASE"),
+
+def _make_model_list():
+ return [
+ {
+ "model_name": "gpt-3.5-turbo",
+ "litellm_params": {
+ "model": "azure/gpt-4.1-mini",
+ "api_key": "bad-key",
+ "api_version": os.getenv("AZURE_API_VERSION"),
+ "api_base": os.getenv("AZURE_API_BASE"),
+ },
+ "tpm": 240000,
+ "rpm": 1800,
},
- "tpm": 240000,
- "rpm": 1800,
- },
- {
- "model_name": "gpt-3.5-turbo", # openai model name
- "litellm_params": { # params for litellm completion/embedding call
- "model": "gpt-3.5-turbo",
- "api_key": os.getenv("OPENAI_API_KEY"),
+ {
+ "model_name": "gpt-3.5-turbo",
+ "litellm_params": {
+ "model": "gpt-3.5-turbo",
+ "api_key": os.getenv("OPENAI_API_KEY"),
+ },
+ "tpm": 1000000,
+ "rpm": 9000,
},
- "tpm": 1000000,
- "rpm": 9000,
- },
-]
+ ]
+
-kwargs = {
- "model": "gpt-3.5-turbo",
- "messages": [{"role": "user", "content": "Hey, how's it going?"}],
-}
+def _make_kwargs():
+ return {
+ "model": "gpt-3.5-turbo",
+ "messages": [{"role": "user", "content": "Hey, how's it going?"}],
+ }
@pytest.mark.flaky(retries=3, delay=1)
@@ -58,8 +62,9 @@ def test_multiple_deployments_sync():
litellm.set_verbose = False
results = []
+ kwargs = _make_kwargs()
router = Router(
- model_list=model_list,
+ model_list=_make_model_list(),
redis_host=os.getenv("REDIS_HOST"),
redis_password=os.getenv("REDIS_PASSWORD"),
redis_port=int(os.getenv("REDIS_PORT")), # type: ignore
@@ -85,9 +90,10 @@ def test_multiple_deployments_parallel():
litellm.set_verbose = False # Corrected the syntax for setting verbose to False
results = []
futures = {}
+ kwargs = _make_kwargs()
start_time = time.time()
router = Router(
- model_list=model_list,
+ model_list=_make_model_list(),
redis_host=os.getenv("REDIS_HOST"),
redis_password=os.getenv("REDIS_PASSWORD"),
redis_port=int(os.getenv("REDIS_PORT")), # type: ignore
diff --git a/tests/local_testing/test_router_custom_routing.py b/tests/local_testing/test_router_custom_routing.py
index afd602b9352..3f829a13c02 100644
--- a/tests/local_testing/test_router_custom_routing.py
+++ b/tests/local_testing/test_router_custom_routing.py
@@ -1,16 +1,11 @@
import asyncio
import os
-import random
import sys
import time
-import traceback
-from datetime import datetime, timedelta
from dotenv import load_dotenv
load_dotenv()
-import copy
-import os
sys.path.insert(
0, os.path.abspath("../..")
@@ -21,36 +16,40 @@ import pytest
import litellm
from litellm import Router
+from litellm.router import CustomRoutingStrategyBase
-router = Router(
- model_list=[
- {
- "model_name": "azure-model",
- "litellm_params": {
- "model": "openai/very-special-endpoint",
- "api_base": "https://exampleopenaiendpoint-production.up.railway.app/", # If you are Krrish, this is OpenAI Endpoint3 on our Railway endpoint :)
- "api_key": "fake-key",
+
+def _create_router():
+ return Router(
+ model_list=[
+ {
+ "model_name": "azure-model",
+ "litellm_params": {
+ "model": "openai/very-special-endpoint",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "api_key": "fake-key",
+ },
+ "model_info": {"id": "very-special-endpoint"},
},
- "model_info": {"id": "very-special-endpoint"},
- },
- {
- "model_name": "azure-model",
- "litellm_params": {
- "model": "openai/fast-endpoint",
- "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
- "api_key": "fake-key",
+ {
+ "model_name": "azure-model",
+ "litellm_params": {
+ "model": "openai/fast-endpoint",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "api_key": "fake-key",
+ },
+ "model_info": {"id": "fast-endpoint"},
},
- "model_info": {"id": "fast-endpoint"},
- },
- ],
- set_verbose=True,
- debug_level="DEBUG",
-)
-
-from litellm.router import CustomRoutingStrategyBase
+ ],
+ set_verbose=True,
+ debug_level="DEBUG",
+ )
class CustomRoutingStrategy(CustomRoutingStrategyBase):
+ def __init__(self, router_instance: Router):
+ self._router = router_instance
+
async def async_get_available_deployment(
self,
model: str,
@@ -59,22 +58,8 @@ class CustomRoutingStrategy(CustomRoutingStrategyBase):
specific_deployment: Optional[bool] = False,
request_kwargs: Optional[Dict] = None,
):
- """
- Asynchronously retrieves the available deployment based on the given parameters.
-
- Args:
- model (str): The name of the model.
- messages (Optional[List[Dict[str, str]]], optional): The list of messages for a given request. Defaults to None.
- input (Optional[Union[str, List]], optional): The input for a given embedding request. Defaults to None.
- specific_deployment (Optional[bool], optional): Whether to retrieve a specific deployment. Defaults to False.
- request_kwargs (Optional[Dict], optional): Additional request keyword arguments. Defaults to None.
-
- Returns:
- Returns an element from litellm.router.model_list
-
- """
print("In CUSTOM async get available deployment")
- model_list = router.model_list
+ model_list = self._router.model_list
print("router model list=", model_list)
for model in model_list:
if isinstance(model, dict):
@@ -90,29 +75,15 @@ class CustomRoutingStrategy(CustomRoutingStrategyBase):
specific_deployment: Optional[bool] = False,
request_kwargs: Optional[Dict] = None,
):
- """
- Synchronously retrieves the available deployment based on the given parameters.
-
- Args:
- model (str): The name of the model.
- messages (Optional[List[Dict[str, str]]], optional): The list of messages for a given request. Defaults to None.
- input (Optional[Union[str, List]], optional): The input for a given embedding request. Defaults to None.
- specific_deployment (Optional[bool], optional): Whether to retrieve a specific deployment. Defaults to False.
- request_kwargs (Optional[Dict], optional): Additional request keyword arguments. Defaults to None.
-
- Returns:
- Returns an element from litellm.router.model_list
-
- """
pass
@pytest.mark.asyncio
async def test_custom_routing():
- import litellm
-
litellm.set_verbose = True
- router.set_custom_routing_strategy(CustomRoutingStrategy())
+
+ router = _create_router()
+ router.set_custom_routing_strategy(CustomRoutingStrategy(router))
# make 4 requests
for _ in range(4):
@@ -126,11 +97,6 @@ async def test_custom_routing():
await asyncio.sleep(1)
print("done sending initial requests to collect latency")
- """
- Note: for debugging
- - By this point: slow-endpoint should have timed out 3-4 times and should be heavily penalized :)
- - The next 10 requests should all be routed to the fast-endpoint
- """
deployments = {}
# make 10 requests
@@ -145,6 +111,3 @@ async def test_custom_routing():
else:
deployments[_picked_model_id] += 1
print("deployments", deployments)
-
- # ALL the Requests should have been routed to the fast-endpoint
- # assert deployments["fast-endpoint"] == 10
diff --git a/tests/local_testing/test_router_fallback_handlers.py b/tests/local_testing/test_router_fallback_handlers.py
index 09d87012346..29387d70c8d 100644
--- a/tests/local_testing/test_router_fallback_handlers.py
+++ b/tests/local_testing/test_router_fallback_handlers.py
@@ -14,14 +14,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
import litellm
from litellm import Router
from litellm.integrations.custom_logger import CustomLogger
-from typing import Any, Dict
-
-
-import sys
-import os
-from typing import List, Dict
-
-sys.path.insert(0, os.path.abspath("../.."))
+from typing import Any, Dict, List
from litellm.router_utils.fallback_event_handlers import (
run_async_fallback,
@@ -53,18 +46,47 @@ def create_test_router():
)
-router: Router = create_test_router()
+def create_test_router_2():
+ return Router(
+ model_list=[
+ {
+ "model_name": "gpt-3.5-turbo",
+ "litellm_params": {
+ "model": "gpt-3.5-turbo",
+ "api_key": os.getenv("OPENAI_API_KEY"),
+ },
+ },
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4",
+ "api_key": "very-fake-key",
+ },
+ },
+ {
+ "model_name": "fake-openai-endpoint-2",
+ "litellm_params": {
+ "model": "openai/fake-openai-endpoint-2",
+ "api_key": "working-key-since-this-is-fake-endpoint",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ },
+ },
+ ],
+ )
@pytest.mark.parametrize(
- "original_function",
- [router._acompletion, router._atext_completion, router._aembedding],
+ "function_name",
+ ["_acompletion", "_atext_completion", "_aembedding"],
)
@pytest.mark.asyncio
-async def test_run_async_fallback(original_function):
+async def test_run_async_fallback(function_name):
"""
Basic test - given a list of fallback models, run the original function with the fallback models
"""
+ router = create_test_router()
+ original_function = getattr(router, function_name)
+
litellm.set_verbose = True
fallback_model_group = ["gpt-4"]
original_model_group = "gpt-3.5-turbo"
@@ -79,11 +101,11 @@ async def test_run_async_fallback(original_function):
"metadata": {"previous_models": ["gpt-3.5-turbo"]},
}
- if original_function == router._aembedding:
+ if function_name == "_aembedding":
request_kwargs["input"] = "hello this is a test for run_async_fallback"
- elif original_function == router._atext_completion:
+ elif function_name == "_atext_completion":
request_kwargs["prompt"] = "hello this is a test for run_async_fallback"
- elif original_function == router._acompletion:
+ elif function_name == "_acompletion":
request_kwargs["messages"] = [{"role": "user", "content": "Hello, world!"}]
result = await run_async_fallback(
@@ -100,11 +122,11 @@ async def test_run_async_fallback(original_function):
assert result is not None
- if original_function == router._acompletion:
+ if function_name == "_acompletion":
assert isinstance(result, litellm.ModelResponse)
- elif original_function == router._atext_completion:
+ elif function_name == "_atext_completion":
assert isinstance(result, litellm.TextCompletionResponse)
- elif original_function == router._aembedding:
+ elif function_name == "_aembedding":
assert isinstance(result, litellm.EmbeddingResponse)
@@ -198,14 +220,17 @@ async def test_log_failure_fallback_event():
@pytest.mark.asyncio
@pytest.mark.parametrize(
- "original_function", [router._acompletion, router._atext_completion]
+ "function_name", ["_acompletion", "_atext_completion"]
)
-async def test_failed_fallbacks_raise_most_recent_exception(original_function):
+async def test_failed_fallbacks_raise_most_recent_exception(function_name):
"""
Tests that if all fallbacks fail, the most recent occuring exception is raised
meaning the exception from the last fallback model is raised
"""
+ router = create_test_router()
+ original_function = getattr(router, function_name)
+
fallback_model_group = ["gpt-4"]
original_model_group = "gpt-3.5-turbo"
original_exception = litellm.exceptions.InternalServerError(
@@ -218,11 +243,11 @@ async def test_failed_fallbacks_raise_most_recent_exception(original_function):
"metadata": {"previous_models": ["gpt-3.5-turbo"]}
}
- if original_function == router._aembedding:
+ if function_name == "_aembedding":
request_kwargs["input"] = "hello this is a test for run_async_fallback"
- elif original_function == router._atext_completion:
+ elif function_name == "_atext_completion":
request_kwargs["prompt"] = "hello this is a test for run_async_fallback"
- elif original_function == router._acompletion:
+ elif function_name == "_acompletion":
request_kwargs["messages"] = [{"role": "user", "content": "Hello, world!"}]
with pytest.raises(litellm.exceptions.RateLimitError):
@@ -240,39 +265,11 @@ async def test_failed_fallbacks_raise_most_recent_exception(original_function):
)
-router_2 = Router(
- model_list=[
- {
- "model_name": "gpt-3.5-turbo",
- "litellm_params": {
- "model": "gpt-3.5-turbo",
- "api_key": os.getenv("OPENAI_API_KEY"),
- },
- },
- {
- "model_name": "gpt-4",
- "litellm_params": {
- "model": "gpt-4",
- "api_key": "very-fake-key",
- },
- },
- {
- "model_name": "fake-openai-endpoint-2",
- "litellm_params": {
- "model": "openai/fake-openai-endpoint-2",
- "api_key": "working-key-since-this-is-fake-endpoint",
- "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
- },
- },
- ],
-)
-
-
@pytest.mark.asyncio
@pytest.mark.parametrize(
- "original_function", [router_2._acompletion, router_2._atext_completion]
+ "function_name", ["_acompletion", "_atext_completion"]
)
-async def test_multiple_fallbacks(original_function):
+async def test_multiple_fallbacks(function_name):
"""
Tests that if multiple fallbacks passed:
- fallback 1 = bad configured deployment / failing endpoint
@@ -281,6 +278,9 @@ async def test_multiple_fallbacks(original_function):
Assert that:
- a success response is received from the working endpoint (fallback 2)
"""
+ router_2 = create_test_router_2()
+ original_function = getattr(router_2, function_name)
+
fallback_model_group = ["gpt-4", "fake-openai-endpoint-2"]
original_model_group = "gpt-3.5-turbo"
original_exception = Exception("Simulated error")
@@ -289,11 +289,11 @@ async def test_multiple_fallbacks(original_function):
"metadata": {"previous_models": ["gpt-3.5-turbo"]}
}
- if original_function == router_2._aembedding:
+ if function_name == "_aembedding":
request_kwargs["input"] = "hello this is a test for run_async_fallback"
- elif original_function == router_2._atext_completion:
+ elif function_name == "_atext_completion":
request_kwargs["prompt"] = "hello this is a test for run_async_fallback"
- elif original_function == router_2._acompletion:
+ elif function_name == "_acompletion":
request_kwargs["messages"] = [{"role": "user", "content": "Hello, world!"}]
result = await run_async_fallback(