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]

test: migrate legacy unit dirs and unrun folders into tests/unit, tests/integration and tests/e2e (#45940)

devin-ai-integration[bot]a7a3a6b3750f
diff --git a/.circleci/scripts/classify_changes.sh b/.circleci/scripts/classify_changes.sh
index 9fe2e99fb93..321664e18c1 100755
--- a/.circleci/scripts/classify_changes.sh
+++ b/.circleci/scripts/classify_changes.sh
@@ -41,7 +41,7 @@ while IFS= read -r file || [ -n "$file" ]; do
case "$file" in
model_prices_and_context_window.json | litellm/model_prices_and_context_window_backup.json | model_prices_and_context_window.schema.json)
has_cost_map=true ;;
- tests/test_litellm/* | tests/proxy_unit_tests/* | tests/unit/proxy/*) : ;;
+ tests/unit/proxy/*) : ;;
*) outside_cost_map_set=true ;;
esac
done
diff --git a/.github/ci-coverage-allowlist.yml b/.github/ci-coverage-allowlist.yml
index 85c8dcb1ab2..db2f652b877 100644
--- a/.github/ci-coverage-allowlist.yml
+++ b/.github/ci-coverage-allowlist.yml
@@ -23,18 +23,6 @@ test_paths:
and that pull request gives it a new home
paths:
- tests/test_rust_python_harness.py
- - reason: >-
- Live-provider caching cases in tests/local_testing that remain outside CI. No CircleCI job
- globs that directory anymore, and the legacy jobs that did always deselected these files.
- The two Redis Cluster IAM authentication tests moved to tests/integration/sdk and remain
- selected by node ID in redis_compat, where redis-server is installed.
- The five keyless files now run in the caching-local shard, leaving live cases in these two.
- Measured 2026-08-21 with no provider credentials: test_disk_cache_unit_tests.py needs
- OPENAI_API_KEY for 2 of its 4 tests, and test_gcs_cache_unit_tests.py needs GCS credentials
- for all 4. Keep these live cases outside PR CI rather than making a job red by construction
- paths:
- - tests/local_testing/test_disk_cache_unit_tests.py
- - tests/local_testing/test_gcs_cache_unit_tests.py
- reason: >-
The end-to-end suite runs against a deployed proxy from its own in-cluster rig rather than
from a pull request; it needs a live gateway and provider credentials no PR job holds
@@ -60,48 +48,6 @@ test_paths:
choice it informed is settled
paths:
- tests/code_coverage_tests/test_aio_http_image_conversion.py
- - reason: >-
- No job invokes this suite and its files mix pure transformation tests with ones driving live
- vendor vector stores, so assigning them needs a per-file decision
- paths:
- - tests/vector_store_tests/rag/test_rag_bedrock.py
- - tests/vector_store_tests/rag/test_rag_openai.py
- - tests/vector_store_tests/rag/test_rag_s3_vectors.py
- - tests/vector_store_tests/rag/test_rag_vertex_ai.py
- - tests/vector_store_tests/test_azure_ai_vector_store.py
- - tests/vector_store_tests/test_azure_vector_store.py
- - tests/vector_store_tests/test_bedrock_vector_store.py
- - tests/vector_store_tests/test_gemini_vector_store.py
- - tests/vector_store_tests/test_milvus_vector_store.py
- - tests/vector_store_tests/test_openai_vector_store.py
- - tests/vector_store_tests/test_ragflow_vector_store.py
- - tests/vector_store_tests/test_s3_vectors_vector_store.py
- - tests/vector_store_tests/test_vertex_ai_search_api_vector_store.py
- - tests/vector_store_tests/test_vertex_ai_vector_store.py
- - reason: >-
- Throughput and memory-growth measurements whose runtime and variance make them unsuitable for
- a per-pull-request job
- paths:
- - tests/load_tests/test_datadog_load_test.py
- - tests/load_tests/test_langsmith_load_test.py
- - tests/load_tests/test_linear_memory_growth.py
- - tests/load_tests/test_memory_usage.py
- - tests/load_tests/test_otel_load_test.py
- - tests/load_tests/test_vertex_embeddings_load_test.py
- - tests/load_tests/test_vertex_load_tests.py
- - reason: >-
- Env-gated saturation benchmark requires a live proxy and provider credentials, so it is run
- locally rather than in pull-request jobs
- paths:
- - tests/load_tests/test_granian_admission_saturation.py
- - reason: >-
- A local-only agent rig: test_a2a_completion_bridge.py needs a LangGraph server on
- localhost:2024 and test_a2a.py drives a live A2A endpoint, so neither can run in a
- pull request job. Until 2026-08-20 the CircleCI agent job hid them behind a grep -v
- that this census could not see; the glob now excludes them structurally and this entry
- is the decision on the record. Revisit when the A2A bridge gets a recorded-wire fixture
- paths:
- - tests/agent_tests/local_only_agent_tests
- reason: >-
Third-party integration tests that skip themselves without OCI configuration or sandbox
credentials, neither of which a pull request job holds
diff --git a/.github/scripts/assert_ci_coverage.py b/.github/scripts/assert_ci_coverage.py
index 5c581c99d12..fbdbfafa66d 100644
--- a/.github/scripts/assert_ci_coverage.py
+++ b/.github/scripts/assert_ci_coverage.py
@@ -37,7 +37,6 @@ GLOB_CHARS = frozenset("*?")
# tests has to be named by some shard or it runs nowhere. A child listed here is
# itself decomposed one level deeper and is checked through its own entry.
SHARDED_ROOTS: tuple[str, ...] = (
- "tests/test_litellm",
"tests/unit",
"tests/unit/enterprise",
"tests/unit/enterprise/enterprise_callbacks",
diff --git a/.github/workflows/test-rust.yml b/.github/workflows/test-rust.yml
index fe1d2c025b3..f8a7c38ef79 100644
--- a/.github/workflows/test-rust.yml
+++ b/.github/workflows/test-rust.yml
@@ -18,7 +18,6 @@ on:
- "litellm/ocr/**"
- "litellm/llms/base_llm/ocr/**"
- "litellm/llms/custom_httpx/llm_http_handler.py"
- - "tests/test_litellm/conftest.py"
- "Makefile"
- ".cargo/**"
- "pyproject.toml"
@@ -49,7 +48,6 @@ on:
- "litellm/ocr/**"
- "litellm/llms/base_llm/ocr/**"
- "litellm/llms/custom_httpx/llm_http_handler.py"
- - "tests/test_litellm/conftest.py"
- "Makefile"
- ".cargo/**"
- "pyproject.toml"
diff --git a/.github/workflows/test-unit.yml b/.github/workflows/test-unit.yml
index 1dc9db0a0c7..23a340cd436 100644
--- a/.github/workflows/test-unit.yml
+++ b/.github/workflows/test-unit.yml
@@ -174,8 +174,6 @@ jobs:
- shard: integrations
test-path: |-
- tests/test_litellm/integrations
- tests/test_litellm/tracing
tests/unit/integrations
python-version: "3.12"
workers: 4
@@ -292,6 +290,7 @@ jobs:
tests/unit/llms/manus
tests/unit/llms/meta_llama
tests/unit/llms/microsoft_365_copilot
+ tests/unit/llms/milvus
tests/unit/llms/minimax
tests/unit/llms/mistral
tests/unit/llms/modelscope
@@ -376,7 +375,6 @@ jobs:
- shard: root
test-path: >-
- tests/test_litellm/test_*.py
tests/unit/test_*.py
python-version: "3.12"
workers: 4
@@ -395,16 +393,6 @@ jobs:
job-timeout-minutes: 60
dist: loadscope
- - shard: router-unit-tests
- test-path: >-
- tests/router_unit_tests
- python-version: "3.12"
- workers: 0
- reruns: 0
- timeout-minutes: 10
- job-timeout-minutes: 60
- dist: loadscope
-
- shard: endpoints
test-path: >-
tests/unit/a2a_protocol
@@ -775,7 +763,7 @@ jobs:
- shard: proxy-server-core
test-path: |-
- tests/proxy_unit_tests/test_proxy_server_gemini_pass_through.py
+ tests/unit/proxy/pass_through_endpoints/test_llm_passthrough_endpoints.py
tests/unit/proxy/test__lazy_features.py
tests/unit/proxy/test_aproxy_startup.py
tests/unit/proxy/test_proxy_server.py
@@ -816,7 +804,7 @@ jobs:
- shard: custom-logging
test-path: |-
- tests/proxy_unit_tests/test_proxy_custom_logger.py
+ tests/unit/proxy/test_proxy_server_custom_logger.py
tests/unit/proxy/test_custom_callback_input.py
tests/unit/proxy/test_custom_logger_s3_gcs.py
python-version: "3.12"
@@ -880,7 +868,7 @@ jobs:
- shard: endpoints-and-responses
test-path: |-
- tests/proxy_unit_tests/test_proxy_exception_mapping.py
+ tests/unit/proxy/test_proxy_server_exception_mapping.py
tests/unit/proxy/lens
tests/unit/proxy/auth/test_models_fallback_endpoint.py
tests/unit/proxy/common_utils/test_check_batch_cost.py
diff --git a/Makefile b/Makefile
index 2a96a8a5e93..1552187e906 100644
--- a/Makefile
+++ b/Makefile
@@ -39,7 +39,7 @@ help:
@echo " make check-circular-imports - Check for circular imports"
@echo " make check-import-safety - Check import safety"
@echo " make test - Run all tests"
- @echo " make test-unit - Run unit tests (tests/unit and tests/test_litellm)"
+ @echo " make test-unit - Run unit tests (tests/unit)"
@echo " make test-unit-llms - Run LLM provider tests (~225 files)"
@echo " make test-unit-proxy-guardrails - Run proxy guardrails+mgmt tests (~51 files)"
@echo " make test-unit-proxy-core - Run proxy auth+client+db+hooks tests (~52 files)"
@@ -300,7 +300,7 @@ test: install-test-deps
$(UV_RUN) pytest tests/
test-unit: install-test-deps
- $(UV_RUN) pytest tests/unit tests/test_litellm -x -vv -n 4
+ $(UV_RUN) pytest tests/unit -x -vv -n 4
# Matrix test targets (matching CI workflow groups)
test-unit-llms: install-test-deps
@@ -328,7 +328,7 @@ test-unit-other: install-test-deps
$(UV_RUN) pytest tests/unit/caching tests/unit/responses tests/unit/secret_managers tests/unit/vector_stores tests/unit/a2a_protocol tests/unit/completion_extras tests/unit/containers tests/unit/enterprise tests/unit/experimental_mcp_client tests/unit/google_genai tests/unit/images tests/unit/interactions tests/unit/router_strategy tests/unit/router_utils tests/unit/types --tb=short -vv -n 4 --durations=20
test-unit-root: install-test-deps
- $(UV_RUN) pytest tests/unit/test_*.py tests/test_litellm/test_*.py --tb=short -vv -n 4 --durations=20
+ $(UV_RUN) pytest tests/unit/test_*.py --tb=short -vv -n 4 --durations=20
# Proxy unit tests (tests/unit/proxy split alphabetically)
test-proxy-unit-a: install-test-deps
@@ -338,7 +338,7 @@ test-proxy-unit-b: install-test-deps
$(UV_RUN) pytest tests/unit/proxy/test_[p-z]*.py tests/unit/skills --tb=short -vv -n 2 --durations=20
test-integration: install-test-deps
- $(UV_RUN) pytest tests/ -k "not test_litellm"
+ $(UV_RUN) pytest tests/
test-unit-helm: install-helm-unittest
helm unittest -f 'tests/*.yaml' helm/litellm-helm
diff --git a/tests/agent_tests/local_only_agent_tests/local_vertex_agent.py b/tests/agent_tests/local_only_agent_tests/local_vertex_agent.py
deleted file mode 100644
index d31db00d234..00000000000
--- a/tests/agent_tests/local_only_agent_tests/local_vertex_agent.py
+++ /dev/null
@@ -1,157 +0,0 @@
-"""
-Test script for Vertex AI Reasoning Engine.
-
-This script demonstrates how to:
-1. Authenticate with Google Cloud
-2. Send queries to a Vertex AI Reasoning Engine using the :query endpoint
-
-Usage:
- python local_vertex_agent.py
-
-Requirements:
- pip install httpx google-auth
-"""
-
-import asyncio
-import json
-from uuid import uuid4
-
-from google.auth import default
-from google.auth.transport.requests import Request
-import httpx
-
-# Configuration - update these for your agent
-PROJECT_ID = "test-gcp-project-id-123" # Your GCP project ID (test value)
-LOCATION = "us-central1" # Your agent's location
-
-# For Reasoning Engines, use just the numeric ID at the end
-REASONING_ENGINE_ID = "8263861224643493888"
-
-# The project number from the resource name
-PROJECT_NUMBER = "1060139831167"
-
-
-async def main():
- """Main function to test Vertex AI Reasoning Engine."""
-
- # Step 1: Authenticate with Google Cloud
- print("Step 1: Authenticating with Google Cloud...")
- credentials, project = default(
- scopes=["https://www.googleapis.com/auth/cloud-platform"]
- )
- credentials.refresh(Request())
- print(f"Authenticated! Project: {project}")
- print(f"Token (first 20 chars): {credentials.token[:20]}...")
-
- # Step 2: Build the endpoint URL
- base_url = f"https://{LOCATION}-aiplatform.googleapis.com"
- resource_path = f"projects/{PROJECT_NUMBER}/locations/{LOCATION}/reasoningEngines/{REASONING_ENGINE_ID}"
-
- # The Reasoning Engine uses :query endpoint with specific format
- query_url = f"{base_url}/v1beta1/{resource_path}:query"
- stream_url = f"{base_url}/v1beta1/{resource_path}:streamQuery"
-
- print(f"\nQuery URL: {query_url}")
- print(f"Stream URL: {stream_url}")
-
- # Step 3: Create authenticated httpx client
- print("\nStep 2: Creating authenticated HTTP client...")
- client = httpx.AsyncClient(
- headers={
- "Authorization": f"Bearer {credentials.token}",
- "Content-Type": "application/json",
- },
- timeout=120.0,
- )
-
- # Step 4: Build the query request (non-streaming)
- # Note: For non-streaming, we need to:
- # 1. Create a session
- # 2. Use the streaming endpoint with stream_query method
- # The :query endpoint only supports session management methods
-
- user_id = f"test-user-{uuid4().hex[:8]}"
-
- # First create a session
- create_session_request = {
- "class_method": "async_create_session",
- "input": {
- "user_id": user_id,
- },
- }
-
- print(f"\nStep 3: Creating session...")
- print(f"User ID: {user_id}")
-
- async with client:
- # Create session
- print(f"\nSending to: {query_url}")
- response = await client.post(query_url, json=create_session_request)
- print(f"Create session status: {response.status_code}")
-
- if response.status_code == 200:
- session_data = response.json()
- print(f"Session created:\n{json.dumps(session_data, indent=2)}")
-
- # Extract session_id from response
- session_id = session_data.get("output", {}).get("id") or session_data.get(
- "output", {}
- ).get("session_id")
- print(f"\nSession ID: {session_id}")
-
- # Now send the actual query via streamQuery
- query_request = {
- "class_method": "stream_query",
- "input": {
- "message": "Hello! What can you do?",
- "user_id": user_id,
- "session_id": session_id,
- },
- }
-
- print(f"\nStep 4: Sending query via streamQuery...")
- print(f"Request:\n{json.dumps(query_request, indent=2)}")
-
- # Use streaming endpoint but collect full response
- async with client.stream(
- "POST", stream_url, json=query_request
- ) as stream_response:
- print(f"Query status: {stream_response.status_code}")
-
- if stream_response.status_code == 200:
- print("\nResponse:")
- full_response = ""
- async for line in stream_response.aiter_lines():
- if line:
- full_response = line # Keep last line (full response)
-
- # Parse and display
- try:
- data = json.loads(full_response)
- # Extract the text from the response
- content = data.get("content", {})
- parts = content.get("parts", [])
- for part in parts:
- if "text" in part:
- print(f"\nAgent response:\n{part['text']}")
- except:
- print(full_response)
- else:
- content = await stream_response.aread()
- print(f"Error: {content.decode()}")
- else:
- print(f"Error creating session: {response.text}")
-
-
-if __name__ == "__main__":
- print("=" * 60)
- print("Vertex AI Reasoning Engine Test Script")
- print("=" * 60)
- print(f"\nConfiguration:")
- print(f" PROJECT_ID: {PROJECT_ID}")
- print(f" PROJECT_NUMBER: {PROJECT_NUMBER}")
- print(f" LOCATION: {LOCATION}")
- print(f" REASONING_ENGINE_ID: {REASONING_ENGINE_ID}")
- print()
-
- asyncio.run(main())
diff --git a/tests/agent_tests/local_only_agent_tests/test_a2a.py b/tests/agent_tests/local_only_agent_tests/test_a2a.py
deleted file mode 100644
index eb0c4ddfc50..00000000000
--- a/tests/agent_tests/local_only_agent_tests/test_a2a.py
+++ /dev/null
@@ -1,353 +0,0 @@
-"""
-Test for LiteLLM A2A module.
-
-Run with:
- pytest tests/agent_tests/test_a2a.py -v -s
-"""
-
-import asyncio
-import json
-from typing import Optional
-from uuid import uuid4
-
-import pytest
-
-import litellm
-from litellm.integrations.custom_logger import CustomLogger
-from litellm.types.utils import StandardLoggingPayload
-
-from a2a.types import MessageSendParams, SendMessageRequest
-
-
-async def test_asend_message_with_client_decorator():
- """
- Test asend_message standalone function with @client decorator.
- This tests the LiteLLM logging integration.
- """
- litellm.turn_on_debug()
- from litellm.a2a_protocol import asend_message, create_a2a_client
-
- # Create the A2A client first
- a2a_client = await create_a2a_client(base_url="http://localhost:10001")
-
- # Build the request matching A2A SDK spec
- send_message_payload = {
- "message": {
- "role": "user",
- "parts": [
- {
- "kind": "text",
- "text": "Hello from @client decorated function!",
- }
- ],
- "messageId": uuid4().hex,
- },
- }
-
- request = SendMessageRequest(
- id=str(uuid4()),
- params=MessageSendParams(**send_message_payload),
- )
-
- # Send message using standalone function with @client decorator
- response = await asend_message(a2a_client=a2a_client, request=request)
-
- # Print response for debugging
- print("\n=== A2A Response (standalone with @client) ===")
- print(response.model_dump(mode="json", exclude_none=True))
-
- # Basic assertions
- assert response is not None
-
-
-class TestA2ALogger(CustomLogger):
- """Custom logger to capture A2A logging payloads for testing."""
-
- def __init__(self):
- self.standard_logging_payload: Optional[StandardLoggingPayload] = None
- self.logged_kwargs: Optional[dict] = None
- self.log_success_called = False
- super().__init__()
-
- async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
- print("TestA2ALogger: async_log_success_event called")
- self.log_success_called = True
- self.logged_kwargs = kwargs
- self.standard_logging_payload = kwargs.get("standard_logging_object", None)
- print(f"Captured standard_logging_payload: {self.standard_logging_payload}")
-
-
-async def test_a2a_logging_payload():
- """
- Test that A2A calls create a standard logging payload.
- Validates the @client decorator integration with LiteLLM logging.
- """
- # Reset callbacks and set up custom logger
- litellm.logging_callback_manager._reset_all_callbacks()
- test_logger = TestA2ALogger()
- litellm.callbacks = [test_logger]
-
- from litellm.a2a_protocol import asend_message, create_a2a_client
-
- # Create the A2A client first
- a2a_client = await create_a2a_client(base_url="http://localhost:10001")
-
- # Build the request
- send_message_payload = {
- "message": {
- "role": "user",
- "parts": [
- {
- "kind": "text",
- "text": "Hello! Testing logging payload.",
- }
- ],
- "messageId": uuid4().hex,
- },
- }
-
- request = SendMessageRequest(
- id=str(uuid4()),
- params=MessageSendParams(**send_message_payload),
- )
-
- # Send message
- response = await asend_message(a2a_client=a2a_client, request=request)
-
- # Give async logging time to complete
- await asyncio.sleep(1)
-
- # Print debug info
- print("\n=== Logging Validation ===")
- print(f"log_success_called: {test_logger.log_success_called}")
- print(f"standard_logging_payload: {test_logger.standard_logging_payload}")
- print(
- f"logged kwargs: {json.dumps(test_logger.logged_kwargs, indent=4, default=str)}"
- )
-
- # Verify logging was called
- assert test_logger.log_success_called is True
- assert test_logger.standard_logging_payload is not None
-
- # Verify standard_logging_payload exists
- slp = test_logger.standard_logging_payload
- assert slp is not None
-
- # Get values from standard logging payload
- logged_model = (
- slp.get("model") if isinstance(slp, dict) else getattr(slp, "model", None)
- )
- logged_provider = (
- slp.get("custom_llm_provider")
- if isinstance(slp, dict)
- else getattr(slp, "custom_llm_provider", None)
- )
- call_type = (
- slp.get("call_type")
- if isinstance(slp, dict)
- else getattr(slp, "call_type", None)
- )
- response_cost = (
- slp.get("response_cost")
- if isinstance(slp, dict)
- else getattr(slp, "response_cost", None)
- )
-
- print(f"\n=== Standard Logging Payload Validation ===")
- print(f"model: {logged_model}")
- print(f"custom_llm_provider: {logged_provider}")
- print(f"call_type: {call_type}")
- print(f"response_cost: {response_cost}")
-
- # Verify model and custom_llm_provider are set correctly
- assert logged_model is not None, "model should be set"
- assert (
- "a2a_agent/" in logged_model
- ), f"model should contain 'a2a_agent/', got: {logged_model}"
- assert (
- logged_provider == "a2a_agent"
- ), f"custom_llm_provider should be 'a2a_agent', got: {logged_provider}"
-
- # Verify call_type is correct for A2A
- assert (
- call_type == "asend_message"
- ), f"call_type should be 'asend_message', got: {call_type}"
-
- # Verify response_cost is set to 0.0 (not None, not an error)
- # This confirms the A2A cost calculator is working
- assert response_cost is not None, "response_cost should not be None"
- assert (
- response_cost == 0.0
- ), f"response_cost should be 0.0 for A2A, got: {response_cost}"
-
-
-async def test_pydantic_ai_non_streaming():
- """
- Test non-streaming requests to Pydantic AI agents.
-
- Pydantic AI agents follow A2A protocol but don't support streaming.
- This test validates non-streaming requests work correctly.
- """
- litellm.turn_on_debug()
- from litellm.a2a_protocol import asend_message
-
- # Build the request
- send_message_payload = {
- "message": {
- "role": "user",
- "parts": [
- {
- "kind": "text",
- "text": "Hello from Pydantic AI test!",
- }
- ],
- "messageId": uuid4().hex,
- },
- }
-
- request = SendMessageRequest(
- id=str(uuid4()),
- params=MessageSendParams(**send_message_payload),
- )
-
- # Send message using Pydantic AI provider
- response = await asend_message(
- request=request,
- api_base="http://localhost:9999",
- litellm_params={"custom_llm_provider": "pydantic_ai_agents"},
- )
-
- # Print response for debugging
- print("\n=== Pydantic AI Non-Streaming Response ===")
- print(response.model_dump(mode="json", exclude_none=True))
-
- # Basic assertions
- assert response is not None
- assert hasattr(response, "result")
-
- # Verify result structure
- result = response.result
- assert result is not None
-
- # Pydantic AI returns a task with history/artifacts, not a direct message
- # Check for either format
- result_dict = (
- result
- if isinstance(result, dict)
- else result.model_dump(mode="python", exclude_none=True)
- )
- has_message = "message" in result_dict
- has_history = "history" in result_dict
- has_artifacts = "artifacts" in result_dict
-
- assert (
- has_message or has_history or has_artifacts
- ), f"Result should contain 'message', 'history', or 'artifacts'. Got: {list(result_dict.keys())}"
-
- # If it's a task response (Pydantic AI style), verify we got agent response
- if has_history:
- history = result_dict.get("history", [])
- agent_messages = [m for m in history if m.get("role") == "agent"]
- assert (
- len(agent_messages) > 0
- ), "Should have at least one agent message in history"
-
- # Verify agent message has text content
- agent_msg = agent_messages[-1]
- parts = agent_msg.get("parts", [])
- text_parts = [p for p in parts if p.get("kind") == "text"]
- assert len(text_parts) > 0, "Agent message should have text content"
- print(f"\nAgent response: {text_parts[0].get('text')}")
-
-
-async def test_pydantic_ai_fake_streaming():
- """
- Test fake streaming for Pydantic AI agents.
-
- Pydantic AI agents don't support streaming natively.
- This test validates that fake streaming works by converting
- non-streaming responses into streaming chunks.
- """
- litellm.turn_on_debug()
- from litellm.a2a_protocol import asend_message_streaming
-
- # Build the request
- from a2a.types import SendStreamingMessageRequest
-
- send_message_payload = {
- "message": {
- "role": "user",
- "parts": [
- {
- "kind": "text",
- "text": "Hello from Pydantic AI streaming test!",
- }
- ],
- "messageId": uuid4().hex,
- },
- }
-
- request = SendStreamingMessageRequest(
- id=str(uuid4()),
- params=MessageSendParams(**send_message_payload),
- )
-
- # Send streaming message using Pydantic AI provider
- print("\n=== Pydantic AI Fake Streaming Response ===")
- chunks_received = 0
- task_event_received = False
- working_event_received = False
- artifact_event_received = False
- completed_event_received = False
-
- async for chunk in asend_message_streaming(
- request=request,
- api_base="http://localhost:9999",
- litellm_params={"custom_llm_provider": "pydantic_ai_agents"},
- ):
- chunks_received += 1
- print(f"\nChunk {chunks_received}:")
-
- # Convert chunk to dict for inspection
- chunk_dict = (
- chunk.model_dump(mode="json", exclude_none=True)
- if hasattr(chunk, "model_dump")
- else chunk
- )
- print(json.dumps(chunk_dict, indent=2))
-
- # Check event types
- result = chunk_dict.get("result", {})
- kind = result.get("kind")
-
- if kind == "task":
- task_event_received = True
- elif kind == "status-update":
- status = result.get("status", {})
- state = status.get("state")
- if state == "working":
- working_event_received = True
- elif state == "completed":
- completed_event_received = True
- elif kind == "artifact-update":
- artifact_event_received = True
-
- print(f"\n=== Streaming Summary ===")
- print(f"Total chunks received: {chunks_received}")
- print(f"Task event received: {task_event_received}")
- print(f"Working event received: {working_event_received}")
- print(f"Artifact event received: {artifact_event_received}")
- print(f"Completed event received: {completed_event_received}")
-
- # Verify we received chunks
- assert chunks_received > 0, "Should receive at least one chunk"
-
- # Verify all required event types were received
- assert task_event_received, "Should receive task event"
- assert working_event_received, "Should receive working status event"
- assert artifact_event_received, "Should receive artifact update event"
- assert completed_event_received, "Should receive completed status event"
diff --git a/tests/agent_tests/local_only_agent_tests/test_a2a_completion_bridge.py b/tests/agent_tests/local_only_agent_tests/test_a2a_completion_bridge.py
deleted file mode 100644
index fb2f19bde2a..00000000000
--- a/tests/agent_tests/local_only_agent_tests/test_a2a_completion_bridge.py
+++ /dev/null
@@ -1,287 +0,0 @@
-"""
-Test for A2A to LiteLLM Completion Bridge.
-
-Tests the SDK-level functions that route A2A requests through litellm.acompletion.
-
-Run with:
- pytest tests/agent_tests/test_a2a_completion_bridge.py -v -s
-
-Prerequisites:
- - LangGraph server running on localhost:2024
-"""
-
-from uuid import uuid4
-
-import pytest
-
-
-import litellm
-from a2a.types import MessageSendParams, SendMessageRequest, SendStreamingMessageRequest
-
-
-async def test_a2a_completion_bridge_non_streaming():
- """
- Test non-streaming A2A request via the completion bridge with LangGraph provider.
- """
- from litellm.a2a_protocol import asend_message
-
- litellm.turn_on_debug()
-
- send_message_payload = {
- "message": {
- "role": "user",
- "parts": [{"kind": "text", "text": "What is 2 + 2?"}],
- "messageId": uuid4().hex,
- }
- }
-
- request = SendMessageRequest(
- id=str(uuid4()),
- params=MessageSendParams(**send_message_payload), # type: ignore
- )
-
- response = await asend_message(
- request=request,
- api_base="http://localhost:2024",
- litellm_params={"custom_llm_provider": "langgraph", "model": "agent"},
- )
-
- # Validate response is LiteLLMSendMessageResponse
- assert response.jsonrpc == "2.0"
- assert response.id is not None
- assert response.result is not None
- assert response.result.get("kind") == "message"
-
- message = response.result
- assert "role" in message
- assert message["role"] == "agent"
- assert "parts" in message
- assert len(message["parts"]) > 0
- assert message["parts"][0]["kind"] == "text"
- assert len(message["parts"][0]["text"]) > 0
-
- print(f"Response: {response.model_dump(mode='json', exclude_none=True)}")
-
-
-async def test_a2a_completion_bridge_streaming():
- """
- Test streaming A2A request via the completion bridge with LangGraph provider.
-
- Validates proper A2A streaming format with events:
- 1. Task event (kind: "task") - Initial task with status "submitted"
- 2. Status update (kind: "status-update") - Status "working"
- 3. Artifact update (kind: "artifact-update") - Content delivery
- 4. Status update (kind: "status-update") - Final "completed" status
- """
- from litellm.a2a_protocol import asend_message_streaming
-
- litellm.turn_on_debug()
-
- send_message_payload = {
- "message": {
- "role": "user",
- "parts": [{"kind": "text", "text": "Count from 1 to 5."}],
- "messageId": uuid4().hex,
- }
- }
-
- request = SendStreamingMessageRequest(
- id=str(uuid4()),
- params=MessageSendParams(**send_message_payload), # type: ignore
- )
-
- chunks = []
- async for chunk in asend_message_streaming(
- request=request,
- api_base="http://localhost:2024",
- litellm_params={"custom_llm_provider": "langgraph", "model": "agent"},
- ):
- chunks.append(chunk)
- print(f"Chunk: {chunk}")
-
- # Validate we received proper A2A streaming events
- assert (
- len(chunks) >= 4
- ), f"Expected at least 4 chunks (task, working, artifact, completed), got {len(chunks)}"
-
- # Validate chunk structure follows A2A spec
- for chunk in chunks:
- assert "jsonrpc" in chunk
- assert chunk["jsonrpc"] == "2.0"
- assert "id" in chunk
- assert "result" in chunk
-
- # Validate first chunk is task event
- task_chunk = chunks[0]
- assert task_chunk["result"]["kind"] == "task", "First chunk should be task event"
- assert task_chunk["result"]["status"]["state"] == "submitted"
- assert "contextId" in task_chunk["result"]
- assert "id" in task_chunk["result"] # task id
- assert "history" in task_chunk["result"]
-
- # Validate second chunk is working status update
- working_chunk = chunks[1]
- assert (
- working_chunk["result"]["kind"] == "status-update"
- ), "Second chunk should be status-update"
- assert working_chunk["result"]["status"]["state"] == "working"
- assert "taskId" in working_chunk["result"]
- assert "contextId" in working_chunk["result"]
- assert working_chunk["result"]["final"] is False
-
- # Validate artifact update chunk
- artifact_chunk = chunks[2]
- assert (
- artifact_chunk["result"]["kind"] == "artifact-update"
- ), "Third chunk should be artifact-update"
- assert "artifact" in artifact_chunk["result"]
- assert "artifactId" in artifact_chunk["result"]["artifact"]
- assert "parts" in artifact_chunk["result"]["artifact"]
- assert len(artifact_chunk["result"]["artifact"]["parts"]) > 0
- assert artifact_chunk["result"]["artifact"]["parts"][0]["kind"] == "text"
-
- # Validate final chunk is completed status update
- final_chunk = chunks[-1]
- assert (
- final_chunk["result"]["kind"] == "status-update"
- ), "Last chunk should be status-update"
- assert final_chunk["result"]["status"]["state"] == "completed"
- assert final_chunk["result"]["final"] is True
-
- print(f"Received {len(chunks)} chunks with proper A2A streaming format")
-
-
-async def test_a2a_completion_bridge_bedrock_agentcore():
- """
- Test A2A request via the completion bridge with Bedrock AgentCore provider.
-
- Uses the AgentCore runtime ARN to call a hosted agent.
- """
- from litellm.a2a_protocol import asend_message_streaming
-
- litellm.turn_on_debug()
-
- # Bedrock AgentCore ARN (streaming-capable runtime)
- agentcore_arn = "arn:aws:bedrock-agentcore:us-west-2:888602223428:runtime/hosted_agent_r9jvp-3ySZuRHjLC"
-
- send_message_payload = {
- "message": {
- "role": "user",
- "parts": [
- {"kind": "text", "text": "Explain machine learning in simple terms"}
- ],
- "messageId": uuid4().hex,
- }
- }
-
- request = SendStreamingMessageRequest(
- id=str(uuid4()),
- params=MessageSendParams(**send_message_payload), # type: ignore
- )
-
- chunks = []
- async for chunk in asend_message_streaming(
- request=request,
- api_base=None, # Not needed for Bedrock AgentCore
- litellm_params={
- "custom_llm_provider": "bedrock",
- "model": f"bedrock/agentcore/{agentcore_arn}",
- },
- ):
- chunks.append(chunk)
- print(f"Chunk: {chunk}")
-
- # Validate we received proper A2A streaming events
- assert len(chunks) >= 4, f"Expected at least 4 chunks, got {len(chunks)}"
-
- # Validate first chunk is task event
- assert chunks[0]["result"]["kind"] == "task"
- assert chunks[0]["result"]["status"]["state"] == "submitted"
-
- # Validate final chunk is completed status
- assert chunks[-1]["result"]["kind"] == "status-update"
- assert chunks[-1]["result"]["status"]["state"] == "completed"
- assert chunks[-1]["result"]["final"] is True
-
- print(f"Received {len(chunks)} chunks from Bedrock AgentCore")
-
-
-# ============================================================
-# Vertex AI Agent Engine Tests
-# ============================================================
-
-# Configuration - update these for your Vertex AI Reasoning Engine
-VERTEX_AGENT_RESOURCE_NAME = (
- "projects/1060139831167/locations/us-central1/reasoningEngines/8263861224643493888"
-)
-
-
-async def test_vertex_agent_engine_non_streaming():
- """
- Test non-streaming request to Vertex AI Agent Engine via litellm.acompletion.
-
- Uses the Reasoning Engine resource ID to call a hosted agent.
- """
-
- litellm.turn_on_debug()
-
- # Call via litellm.acompletion with vertex_ai/agent_engine/ prefix
- response = await litellm.acompletion(
- model=f"vertex_ai/agent_engine/{VERTEX_AGENT_RESOURCE_NAME}",
- messages=[{"role": "user", "content": "Hello! What can you do?"}],
- stream=False,
- )
-
- print(f"\n=== Vertex Agent Engine Non-Streaming Response ===")
- print(f"Response: {response}")
-
- # Basic assertions
- assert response is not None
- assert hasattr(response, "choices")
- assert len(response.choices) > 0
- assert response.choices[0].message is not None
- assert response.choices[0].message.content is not None
- assert len(response.choices[0].message.content) > 0
-
- print(f"Agent response: {response.choices[0].message.content[:200]}...")
-
-
-async def test_vertex_agent_engine_streaming():
- """
- Test streaming request to Vertex AI Agent Engine via litellm.acompletion.
-
- Uses the Reasoning Engine resource ID to call a hosted agent with streaming.
- """
- # litellm.turn_on_debug()
-
- # Call via litellm.acompletion with streaming
- response = await litellm.acompletion(
- model=f"vertex_ai/agent_engine/{VERTEX_AGENT_RESOURCE_NAME}",
- messages=[{"role": "user", "content": "Hello! What can you do?"}],
- stream=True,
- )
-
- print(f"\n=== Vertex Agent Engine Streaming Response ===")
-
- chunks = []
- full_content = ""
- async for chunk in response:
- print(f"Chunk: {chunk}")
- # chunks.append(chunk)
- # if hasattr(chunk, "choices") and len(chunk.choices) > 0:
- # delta = chunk.choices[0].delta
- # if hasattr(delta, "content") and delta.content:
- # full_content += delta.content
- # print(f"Chunk: {delta.content}", end="", flush=True)
-
- # # print(f"\n\nReceived {len(chunks)} chunks")
- # print(f"Full content: {full_content[:200]}...")
-
- # # Basic assertions
- # assert len(chunks) > 0
- # assert len(full_content) > 0
diff --git a/tests/code_coverage_tests/code_qa_check_tests.py b/tests/code_coverage_tests/code_qa_check_tests.py
index 6c620a02522..17e7466ab71 100644
--- a/tests/code_coverage_tests/code_qa_check_tests.py
+++ b/tests/code_coverage_tests/code_qa_check_tests.py
@@ -174,7 +174,7 @@ def main():
f"This can cause import issues and test failures. Files: {problematic_files}"
)
else:
- print("✓ No litellm module deletion patterns found in tests/test_litellm or tests/unit.")
+ print("✓ No litellm module deletion patterns found in tests/unit.")
if __name__ == "__main__":
diff --git a/tests/code_coverage_tests/router_code_coverage.py b/tests/code_coverage_tests/router_code_coverage.py
index 9b9206194b4..e7c2e4234f5 100644
--- a/tests/code_coverage_tests/router_code_coverage.py
+++ b/tests/code_coverage_tests/router_code_coverage.py
@@ -27,11 +27,11 @@ def get_function_names_from_file(file_path):
def get_all_functions_called_in_tests(base_dir):
"""
Returns a set of function names that are called in test functions
- inside 'local_testing' and 'router_unit_test' directories,
+ inside the unit test directories,
specifically in files containing the word 'router'.
"""
called_functions = set()
- test_dirs = ["local_testing", "router_unit_tests", "test_litellm", "unit"]
+ test_dirs = ["unit"]
for test_dir in test_dirs:
dir_path = os.path.join(base_dir, test_dir)
diff --git a/tests/load_tests/test_granian_admission_saturation.py b/tests/integration/compatibility/test_granian_admission_saturation.py
similarity index 56%
rename from tests/load_tests/test_granian_admission_saturation.py
rename to tests/integration/compatibility/test_granian_admission_saturation.py
index b55d75ee9f1..9f7cec44d89 100644
--- a/tests/load_tests/test_granian_admission_saturation.py
+++ b/tests/integration/compatibility/test_granian_admission_saturation.py
@@ -12,10 +12,9 @@ import pytest
from tests._master_key import MASTER_KEY
-pytestmark = pytest.mark.skipif(
- os.environ.get("LITELLM_RUN_SATURATION_BENCHMARK") != "1",
- reason="set LITELLM_RUN_SATURATION_BENCHMARK=1 to run the saturation benchmark",
-)
+MAX_IN_FLIGHT: Final = 8
+MAX_QUEUED: Final = 8
+REQUESTS: Final = 200
def _free_port() -> int:
@@ -24,27 +23,24 @@ def _free_port() -> int:
return int(listener.getsockname()[1])
-def _percentile(values: list[float], percentile: float) -> float:
- return sorted(values)[min(int(len(values) * percentile), len(values) - 1)]
-
-
@pytest.mark.asyncio
async def test_granian_admission_control_saturation(tmp_path: Path) -> None:
fake_port: Final = _free_port()
proxy_port: Final = _free_port()
- fake_script: Final = Path(__file__).parents[1] / "_fake_openai_endpoint_server.py"
+ fake_script: Final = Path(__file__).parents[2] / "_fake_openai_endpoint_server.py"
config_path: Final = tmp_path / "saturation_config.yaml"
- proxy_env: Final = {**os.environ, "LITELLM_MASTER_KEY": MASTER_KEY}
+ proxy_env: Final = {**{k: v for k, v in os.environ.items() if k != "DATABASE_URL"}, "LITELLM_MASTER_KEY": MASTER_KEY}
config_path.write_text(
f"""model_list:
- model_name: slow-endpoint
litellm_params:
model: openai/slow-endpoint
api_base: http://127.0.0.1:{fake_port}/v1
+ api_key: fake-upstream-key
general_settings:
master_key: os.environ/LITELLM_MASTER_KEY
- max_in_flight_requests_per_worker: 8
- max_queued_requests_per_worker: 8
+ max_in_flight_requests_per_worker: {MAX_IN_FLIGHT}
+ max_queued_requests_per_worker: {MAX_QUEUED}
admission_queue_timeout_seconds: 0.5
"""
)
@@ -85,22 +81,7 @@ general_settings:
else:
raise AssertionError("Granian proxy did not become healthy")
- liveness_latencies: Final[list[float]] = []
- stop_sampling: Final = asyncio.Event()
-
- async def sample_liveness() -> None:
- while not stop_sampling.is_set():
- start: Final = time.perf_counter()
- try:
- response = await client.get("/health/liveliness", timeout=2)
- response.raise_for_status()
- liveness_latencies.append(time.perf_counter() - start)
- except httpx.HTTPError:
- pass
- await asyncio.sleep(0.05)
-
- async def send_completion() -> tuple[int, float, bool]:
- start: Final = time.perf_counter()
+ async def send_completion() -> tuple[int, bool]:
response = await client.post(
"/chat/completions",
headers={"Authorization": f"Bearer {MASTER_KEY}"},
@@ -110,34 +91,16 @@ general_settings:
},
timeout=10,
)
- return response.status_code, time.perf_counter() - start, "retry-after" in response.headers
+ return response.status_code, "retry-after" in response.headers
- sampler: Final = asyncio.create_task(sample_liveness())
- results: Final = await asyncio.gather(*(send_completion() for _ in range(200)))
- stop_sampling.set()
- await sampler
+ results: Final = await asyncio.gather(*(send_completion() for _ in range(REQUESTS)))
statuses: Final = [result[0] for result in results]
- latencies: Final = [result[1] for result in results]
rejected: Final = [result for result in results if result[0] == 503]
- assert set(statuses) <= {200, 503}
- assert rejected
- assert all(result[2] for result in rejected)
- assert _percentile(latencies, 0.99) < 5
- assert liveness_latencies
- assert _percentile(liveness_latencies, 0.95) < 0.5
-
- duration: Final = max(latencies)
- print(
- "\nmetric value\n"
- f"rps {len(results) / duration:.2f}\n"
- f"200 count {statuses.count(200)}\n"
- f"503 count {statuses.count(503)}\n"
- f"p50 {_percentile(latencies, 0.50):.3f}s\n"
- f"p95 {_percentile(latencies, 0.95):.3f}s\n"
- f"p99 {_percentile(latencies, 0.99):.3f}s\n"
- f"liveness p95 {_percentile(liveness_latencies, 0.95):.3f}s"
- )
+ assert set(statuses) <= {200, 503}, statuses
+ assert 1 <= statuses.count(200) <= MAX_IN_FLIGHT + MAX_QUEUED, statuses
+ assert len(rejected) >= REQUESTS - MAX_IN_FLIGHT - MAX_QUEUED, statuses
+ assert all(result[1] for result in rejected), rejected
finally:
proxy_process.terminate()
try:
diff --git a/tests/test_litellm/test_conftest.py b/tests/integration/configuration/test_unit_conftest_isolation.py
similarity index 95%
rename from tests/test_litellm/test_conftest.py
rename to tests/integration/configuration/test_unit_conftest_isolation.py
index 6be9e8f5a20..4c8736f0cf9 100644
--- a/tests/test_litellm/test_conftest.py
+++ b/tests/integration/configuration/test_unit_conftest_isolation.py
@@ -4,7 +4,7 @@ import sys
from pathlib import Path
from typing import Final
-REPO_ROOT: Final = Path(__file__).resolve().parents[2]
+REPO_ROOT: Final = Path(__file__).resolve().parents[3]
PROXY_BASE_URL_SENSITIVE_NODE: Final = (
"tests/unit/proxy/management_endpoints/test_mcp_management_endpoints.py"
diff --git a/tests/integration/observability/test_datadog_logging_delivery.py b/tests/integration/observability/test_datadog_logging_delivery.py
new file mode 100644
index 00000000000..40853f3e613
--- /dev/null
+++ b/tests/integration/observability/test_datadog_logging_delivery.py
@@ -0,0 +1,85 @@
+"""Datadog success callback delivers one log payload per completion.
+
+Deterministic rewrite of the legacy load test: fixed request count, scripted
+Datadog intake upstream, asserts the outbound posts arrive rather than a wall
+clock overhead ratio.
+"""
+
+import asyncio
+import json
+import zlib
+from typing import Final
+
+import pytest
+
+import litellm
+from tests._wait_helpers import await_until
+from tests.integration._support.wire import Reply, Request, wire_server
+
+REQUEST_COUNT: Final = 20
+
+
+def _datadog_upstream(request: Request, captured: list) -> Reply:
+ assert request.method == "POST"
+ body = request.body
+ try:
+ payload = zlib.decompress(body, zlib.MAX_WBITS | 16)
+ except zlib.error:
+ payload = body
+ captured.append(payload)
+ return Reply(status=202, body=b"{}")
+
+
+def _delivered_logs(captured: list) -> list:
+ return [entry for payload in captured for entry in json.loads(payload)]
+
+
+async def test_datadog_logging_async_delivers_logs(monkeypatch: pytest.MonkeyPatch):
+ captured: list = []
+
+ def upstream(request: Request) -> Reply:
+ return _datadog_upstream(request, captured)
+
+ monkeypatch.setenv("DD_API_KEY", "unit-dd-key")
+ monkeypatch.setenv("DD_SITE", "us5.datadoghq.com")
+
+ litellm.logging_callback_manager._reset_all_callbacks()
+
+ with wire_server(upstream) as wire:
+ monkeypatch.setenv("DD_BASE_URL", wire.url)
+ litellm.success_callback = ["datadog"]
+ try:
+ responses = await asyncio.gather(
+ *(
+ litellm.acompletion(
+ model="openai/chatgpt-v-3",
+ messages=[{"role": "user", "content": "This is a test"}],
+ max_tokens=5,
+ user="datadog_latency_test_user",
+ mock_response="hello from my load test",
+ )
+ for _ in range(REQUEST_COUNT)
+ )
+ )
+ assert len(responses) == REQUEST_COUNT
+
+ from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER
+
+ await asyncio.wait_for(GLOBAL_LOGGING_WORKER.flush(), timeout=30)
+
+ await await_until(
+ lambda: len(_delivered_logs(captured)) >= REQUEST_COUNT,
+ message=f"{REQUEST_COUNT} Datadog log entries delivered",
+ timeout_s=30,
+ )
+ finally:
+ litellm.success_callback = []
+ litellm.logging_callback_manager._reset_all_callbacks()
+
+ logs = _delivered_logs(captured)
+ assert len(logs) == REQUEST_COUNT
+ assert {log["ddsource"] for log in logs} == {"litellm"}
+ payloads = [json.loads(log["message"]) for log in logs]
+ assert len({payload["id"] for payload in payloads}) == REQUEST_COUNT
+ assert {(payload["status"], payload["model"]) for payload in payloads} == {("success", "chatgpt-v-3")}
diff --git a/tests/integration/observability/test_langsmith_logging_delivery.py b/tests/integration/observability/test_langsmith_logging_delivery.py
new file mode 100644
index 00000000000..8ece3eb9aa2
--- /dev/null
+++ b/tests/integration/observability/test_langsmith_logging_delivery.py
@@ -0,0 +1,81 @@
+"""Langsmith success callback delivers run payloads for each completion.
+
+Deterministic rewrite of the legacy load test: fixed request count, scripted
+Langsmith upstream, asserts outbound posts arrive rather than a wall clock
+overhead ratio.
+"""
+
+import asyncio
+import gzip
+import json
+from typing import Final
+
+import pytest
+
+import litellm
+from tests._wait_helpers import await_until
+from tests.integration._support.wire import Reply, Request, wire_server
+
+REQUEST_COUNT: Final = 20
+
+
+def _posted_runs(captured: list) -> list:
+ return [run for payload in captured for run in json.loads(payload).get("post", [])]
+
+
+async def test_langsmith_logging_async_delivers_runs(monkeypatch: pytest.MonkeyPatch):
+ captured: list = []
+
+ def upstream(request: Request) -> Reply:
+ assert request.method in ("POST", "PATCH")
+ body = request.body
+ try:
+ payload = gzip.decompress(body)
+ except OSError:
+ payload = body
+ captured.append(payload)
+ return Reply(status=202, body=b"{}")
+
+ monkeypatch.setenv("LANGSMITH_API_KEY", "lsv2_unit_key")
+ monkeypatch.setenv("LANGSMITH_PROJECT", "pr-b")
+
+ litellm.logging_callback_manager._reset_all_callbacks()
+
+ with wire_server(upstream) as wire:
+ monkeypatch.setenv("LANGSMITH_BASE_URL", wire.url)
+ monkeypatch.setenv("LANGSMITH_ENDPOINT", wire.url)
+ litellm.success_callback = ["langsmith"]
+ try:
+ responses = await asyncio.gather(
+ *(
+ litellm.acompletion(
+ model="openai/chatgpt-v-2",
+ messages=[{"role": "user", "content": "This is a test"}],
+ max_tokens=5,
+ user="langfuse_latency_test_user",
+ mock_response="hello from my load test",
+ )
+ for _ in range(REQUEST_COUNT)
+ )
+ )
+ assert len(responses) == REQUEST_COUNT
+
+ from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER
+
+ await asyncio.wait_for(GLOBAL_LOGGING_WORKER.flush(), timeout=30)
+
+ await await_until(
+ lambda: len(_posted_runs(captured)) >= REQUEST_COUNT,
+ message=f"{REQUEST_COUNT} LangSmith runs posted",
+ timeout_s=30,
+ )
+ finally:
+ litellm.success_callback = []
+ litellm.logging_callback_manager._reset_all_callbacks()
+
+ runs = _posted_runs(captured)
+ assert len(runs) == REQUEST_COUNT
+ assert {(run["run_type"], run["session_name"]) for run in runs} == {("llm", "pr-b")}
+ assert len({run["inputs"]["id"] for run in runs}) == REQUEST_COUNT
+ assert {run["inputs"]["model"] for run in runs} == {"chatgpt-v-2"}
diff --git a/tests/integration/providers/test_a2a_sdk_upstream_wire.py b/tests/integration/providers/test_a2a_sdk_upstream_wire.py
new file mode 100644
index 00000000000..098d1b742b5
--- /dev/null
+++ b/tests/integration/providers/test_a2a_sdk_upstream_wire.py
@@ -0,0 +1,335 @@
+"""A2A SDK paths against a scripted upstream agent.
+
+Ports the legacy agent_tests coverage: asend_message with an explicit A2A
+client, the LiteLLM logging payload for A2A calls, the pydantic_ai_agents
+provider's send-and-poll flow, and the completion bridge driving LangGraph
+/runs/wait and /runs/stream endpoints.
+"""
+
+import asyncio
+import json
+from typing import Final
+from uuid import uuid4
+
+import pytest
+from a2a.compat.v0_3.types import (
+ MessageSendParams,
+ SendMessageRequest,
+ SendStreamingMessageRequest,
+)
+
+import litellm
+from tests.integration._support.wire import Reply, Request, wire_server
+
+
+def _agent_card(wire_url: str) -> dict:
+ return {
+ "protocolVersion": "0.3",
+ "name": "scripted-a2a-agent",
+ "description": "scripted upstream",
+ "version": "1.0.0",
+ "url": wire_url + "/",
+ "capabilities": {"streaming": True},
+ "defaultInputModes": ["text"],
+ "defaultOutputModes": ["text"],
+ "skills": [],
+ }
+
+
+def _a2a_message_response(request: Request, text: str) -> Reply:
+ body = json.loads(request.body)
+ return Reply(
+ body=json.dumps(
+ {
+ "jsonrpc": "2.0",
+ "id": body["id"],
+ "result": {
+ "kind": "message",
+ "role": "agent",
+ "messageId": uuid4().hex,
+ "parts": [{"kind": "text", "text": text}],
+ },
+ }
+ ).encode()
+ )
+
+
+def _send_request() -> SendMessageRequest:
+ send_message_payload = {
+ "message": {
+ "role": "user",
+ "parts": [{"kind": "text", "text": "Hello from the test"}],
+ "messageId": uuid4().hex,
+ },
+ }
+ return SendMessageRequest(id=str(uuid4()), params=MessageSendParams(**send_message_payload))
+
+
+async def test_asend_message_with_client_decorator():
+ """asend_message over an explicit A2A client returns the agent message."""
+ from litellm.a2a_protocol import asend_message, create_a2a_client
+
+ def upstream(request: Request) -> Reply:
+ if request.method == "GET":
+ assert request.target in ("/.well-known/agent-card.json", "/.well-known/agent.json")
+ return Reply(body=json.dumps(_agent_card(wire.url)).encode())
+ return _a2a_message_response(request, "scripted agent reply")
+
+ with wire_server(upstream) as wire:
+ a2a_client = await create_a2a_client(base_url=wire.url)
+ response = await asend_message(a2a_client=a2a_client, request=_send_request())
+
+ assert response is not None
+ result = response.result if hasattr(response, "result") else response
+ result_dict = result if isinstance(result, dict) else result.model_dump(mode="python", exclude_none=True)
+ assert result_dict["kind"] == "message"
+ assert result_dict["role"] == "agent"
+ assert result_dict["parts"][0]["text"] == "scripted agent reply"
+
+
+async def test_a2a_logging_payload():
+ """A2A calls produce a standard logging payload with provider and zero cost."""
+ from litellm.integrations.custom_logger import CustomLogger
+
+ class TestA2ALogger(CustomLogger):
+ def __init__(self):
+ self.standard_logging_payload = None
+ self.log_success_called = False
+ super().__init__()
+
+ async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
+ self.log_success_called = True
+ self.standard_logging_payload = kwargs.get("standard_logging_object", None)
+
+ litellm.logging_callback_manager._reset_all_callbacks()
+ test_logger = TestA2ALogger()
+ litellm.callbacks = [test_logger]
+
+ def upstream(request: Request) -> Reply:
+ if request.method == "GET":
+ return Reply(body=json.dumps(_agent_card(wire.url)).encode())
+ return _a2a_message_response(request, "scripted agent reply")
+
+ try:
+ from litellm.a2a_protocol import asend_message, create_a2a_client
+
+ with wire_server(upstream) as wire:
+ a2a_client = await create_a2a_client(base_url=wire.url)
+ await asend_message(a2a_client=a2a_client, request=_send_request())
+
+ deadline = asyncio.get_event_loop().time() + 10
+ while not test_logger.log_success_called and asyncio.get_event_loop().time() < deadline:
+ await asyncio.sleep(0.05)
+ finally:
+ litellm.logging_callback_manager._reset_all_callbacks()
+
+ assert test_logger.log_success_called is True
+ slp = test_logger.standard_logging_payload
+ assert slp is not None
+
+ logged_model = slp.get("model") if isinstance(slp, dict) else getattr(slp, "model", None)
+ logged_provider = (
+ slp.get("custom_llm_provider") if isinstance(slp, dict) else getattr(slp, "custom_llm_provider", None)
+ )
+ call_type = slp.get("call_type") if isinstance(slp, dict) else getattr(slp, "call_type", None)
+ response_cost = (
+ slp.get("response_cost") if isinstance(slp, dict) else getattr(slp, "response_cost", None)
+ )
+
+ assert logged_model is not None and "a2a_agent/" in logged_model
+ assert logged_provider == "a2a_agent"
+ assert call_type == "asend_message"
+ assert response_cost == 0.0
+
+
+def _pydantic_task_response(request: Request) -> Reply:
+ body = json.loads(request.body)
+ assert body["method"] in ("message/send", "tasks/get"), body["method"]
+ return Reply(
+ body=json.dumps(
+ {
+ "jsonrpc": "2.0",
+ "id": body["id"],
+ "result": {
+ "id": "task-1",
+ "kind": "task",
+ "status": {"state": "completed"},
+ "history": [
+ body["params"]["message"] if body["method"] == "message/send" else {},
+ {
+ "role": "agent",
+ "kind": "message",
+ "messageId": "agent-msg-1",
+ "parts": [{"kind": "text", "text": "pydantic agent reply"}],
+ },
+ ],
+ "artifacts": [
+ {
+ "artifactId": "artifact-1",
+ "parts": [{"kind": "text", "text": "pydantic agent reply"}],
+ }
+ ],
+ },
+ }
+ ).encode()
+ )
+
+
+async def test_pydantic_ai_non_streaming():
+ """pydantic_ai_agents send returns the completed task with agent text."""
+ from litellm.a2a_protocol import asend_message
+
+ with wire_server(_pydantic_task_response) as wire:
+ response = await asend_message(
+ request=_send_request(),
+ api_base=wire.url,
+ litellm_params={"custom_llm_provider": "pydantic_ai_agents"},
+ )
+
+ assert response is not None
+ result = response.result
+ assert result is not None
+ result_dict = result if isinstance(result, dict) else result.model_dump(mode="python", exclude_none=True)
+ assert result_dict["kind"] == "message"
+ assert result_dict["role"] == "agent"
+ assert result_dict["parts"][0]["kind"] == "text"
+ assert result_dict["parts"][0]["text"] == "pydantic agent reply"
+
+
+async def test_pydantic_ai_fake_streaming():
+ """pydantic_ai_agents fake streaming emits task, working, artifact, completed."""
+ from litellm.a2a_protocol import asend_message_streaming
+
+ send_message_payload = {
+ "message": {
+ "role": "user",
+ "parts": [{"kind": "text", "text": "Hello from Pydantic AI streaming test!"}],
+ "messageId": uuid4().hex,
+ },
+ }
+ request = SendStreamingMessageRequest(id=str(uuid4()), params=MessageSendParams(**send_message_payload))
+
+ with wire_server(_pydantic_task_response) as wire:
+ chunks = []
+ async for chunk in asend_message_streaming(
+ request=request,
+ api_base=wire.url,
+ litellm_params={"custom_llm_provider": "pydantic_ai_agents"},
+ ):
+ chunk_dict = chunk.model_dump(mode="json", exclude_none=True) if hasattr(chunk, "model_dump") else chunk
+ chunks.append(chunk_dict)
+
+ kinds = [c.get("result", {}).get("kind") for c in chunks]
+ states = [c.get("result", {}).get("status", {}).get("state") for c in chunks]
+ assert len(chunks) > 0
+ assert "task" in kinds
+ assert "artifact-update" in kinds
+ assert "working" in states
+ assert "completed" in states
+
+
+def _langgraph_upstream(request: Request) -> Reply:
+ assert request.method == "POST"
+ body = json.loads(request.body)
+ messages = body["input"]["messages"]
+ assert messages[0]["role"] == "human"
+ if request.target == "/runs/wait":
+ return Reply(
+ body=json.dumps(
+ {"messages": [{"type": "ai", "role": "assistant", "content": "2 + 2 = 4."}]}
+ ).encode()
+ )
+ assert request.target == "/runs/stream"
+ sse = (
+ 'data: {"content":"1, "}\n\n'
+ 'data: {"content":"2, 3, 4, 5."}\n\n'
+ )
+ return Reply(body=sse.encode(), content_type="text/event-stream")
+
+
+async def test_a2a_completion_bridge_non_streaming():
+ """Completion bridge non-streaming returns the LangGraph text as an A2A message."""
+ from litellm.a2a_protocol import asend_message
+
+ send_message_payload = {
+ "message": {
+ "role": "user",
+ "parts": [{"kind": "text", "text": "What is 2 + 2?"}],
+ "messageId": uuid4().hex,
+ },
+ }
+ request = SendMessageRequest(id=str(uuid4()), params=MessageSendParams(**send_message_payload))
+
+ with wire_server(_langgraph_upstream) as wire:
+ response = await asend_message(
+ request=request,
+ api_base=wire.url,
+ litellm_params={"custom_llm_provider": "langgraph", "model": "agent"},
+ )
+
+ assert response.jsonrpc == "2.0"
+ assert response.id is not None
+ assert response.result is not None
+ assert response.result.get("kind") == "message"
+
+ message = response.result
+ assert message["role"] == "agent"
+ assert len(message["parts"]) > 0
+ assert message["parts"][0]["kind"] == "text"
+ assert message["parts"][0]["text"] == "2 + 2 = 4."
+
+
+async def test_a2a_completion_bridge_streaming():
+ """Completion bridge streaming emits task, working, artifact, completed events."""
+ from litellm.a2a_protocol import asend_message_streaming
+
+ send_message_payload = {
+ "message": {
+ "role": "user",
+ "parts": [{"kind": "text", "text": "Count from 1 to 5."}],
+ "messageId": uuid4().hex,
+ },
+ }
+ request = SendStreamingMessageRequest(id=str(uuid4()), params=MessageSendParams(**send_message_payload))
+
+ with wire_server(_langgraph_upstream) as wire:
+ chunks = []
+ async for chunk in asend_message_streaming(
+ request=request,
+ api_base=wire.url,
+ litellm_params={"custom_llm_provider": "langgraph", "model": "agent"},
+ ):
+ chunks.append(chunk)
+
+ assert len(chunks) >= 4, f"Expected at least 4 chunks, got {len(chunks)}"
+
+ for chunk in chunks:
+ assert chunk["jsonrpc"] == "2.0"
+ assert "id" in chunk
+ assert "result" in chunk
+
+ task_chunk = chunks[0]
+ assert task_chunk["result"]["kind"] == "task"
+ assert task_chunk["result"]["status"]["state"] == "submitted"
+
+ working_chunk = chunks[1]
+ assert working_chunk["result"]["kind"] == "status-update"
+ assert working_chunk["result"]["status"]["state"] == "working"
+ assert working_chunk["result"]["final"] is False
+
+ artifact_chunk = chunks[2]
+ assert artifact_chunk["result"]["kind"] == "artifact-update"
+ parts = artifact_chunk["result"]["artifact"]["parts"]
+ assert len(parts) > 0
+ assert parts[0]["kind"] == "text"
+
+ final_chunk = chunks[-1]
+ assert final_chunk["result"]["kind"] == "status-update"
+ assert final_chunk["result"]["status"]["state"] == "completed"
+ assert final_chunk["result"]["final"] is True
diff --git a/tests/load_tests/conftest.py b/tests/load_tests/conftest.py
deleted file mode 100644
index 48a98663e4e..00000000000
--- a/tests/load_tests/conftest.py
+++ /dev/null
@@ -1,5 +0,0 @@
-from tests.load_tests.memory_leak_utils import ( # noqa: F401 # re-exported so pytest resolves these fixtures by name
- limit_memory,
- mock_server,
- test_router,
-)
diff --git a/tests/load_tests/memory_leak_utils.py b/tests/load_tests/memory_leak_utils.py
deleted file mode 100644
index fae294e5a2c..00000000000
--- a/tests/load_tests/memory_leak_utils.py
+++ /dev/null
@@ -1,328 +0,0 @@
-"""
-Memory Leak Testing Utilities
-
-This module provides reusable utilities, fixtures, and helpers for memory leak
-and OOM (Out of Memory) detection tests. It includes:
-- Mock server setup for local testing
-- Memory tracking fixtures
-- Router fixtures configured for testing
-- Helper functions for running memory baseline tests
-
-Usage:
- from tests.load_tests.memory_leak_utils import (
- mock_server,
- limit_memory,
- test_router,
- run_memory_baseline_test,
- )
-"""
-
-import gc
-import os
-import socket
-import sys
-import time
-from threading import Thread
-
-# Add parent directory to path to import litellm (same pattern as other tests)
-filepath = os.path.dirname(os.path.abspath(__file__))
-sys.path.insert(0, os.path.abspath(os.path.join(filepath, "../..")))
-
-import httpx
-import pytest
-import psutil
-from fastapi import FastAPI, Request
-from fastapi.responses import JSONResponse
-from litellm.router import Router
-
-# Test Configuration Constants
-TEST_API_KEY = "sk-9876"
-TEST_MODEL_NAME = "gpt-3.5-turbo"
-
-# Timing Constants (seconds)
-GC_STABILIZATION_DELAY = 0.05
-
-
-# Mock OpenAI-compatible server
-def create_mock_server():
- """Create a simple FastAPI mock server that mimics OpenAI API responses."""
- app = FastAPI()
-
- @app.post("/v1/chat/completions")
- @app.post("/chat/completions")
- async def chat_completions(request: Request):
- """Mock OpenAI chat completions endpoint."""
- request_data = await request.json()
- # Return a simple mock response
- return JSONResponse(
- {
- "id": "chatcmpl-mock",
- "object": "chat.completion",
- "created": int(time.time()),
- "model": request_data.get("model", TEST_MODEL_NAME),
- "choices": [
- {
- "index": 0,
- "message": {"role": "assistant", "content": "Mock response"},
- "finish_reason": "stop",
- }
- ],
- "usage": {
- "prompt_tokens": 10,
- "completion_tokens": 5,
- "total_tokens": 15,
- },
- }
- )
-
- # Catch-all route to see what URLs are being requested
- @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH"])
- async def catch_all(request: Request, path: str):
- """Catch-all route to debug what URLs are being requested."""
- print(f"[Mock Server] Received request: {request.method} {request.url.path}")
- # For non-chat-completions, return 404
- return JSONResponse({"detail": "Not Found"}, status_code=404)
-
- return app
-
-
-def run_server(app, port):
- """Run uvicorn server in a thread."""
- import uvicorn
-
- # Use uvicorn.run which blocks - this is fine in a daemon thread
- uvicorn.run(app, host="127.0.0.1", port=port, log_level="error", access_log=False)
-
-
[email protected](scope="session")
-def mock_server():
- """Start a mock server in a separate thread for the test session.
-
- Yields the server URL (with trailing slash) for use in router configuration.
- """
- app = create_mock_server()
- port = 18888
-
- # Check if port is already in use
- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- try:
- sock.bind(("127.0.0.1", port))
- sock.close()
- except OSError:
- # Port already in use, try next port
- port = 18889
- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- try:
- sock.bind(("127.0.0.1", port))
- sock.close()
- except OSError:
- pytest.fail(
- f"Could not find available port for mock server (tried 18888, 18889)"
- )
-
- # Start server in background thread
- thread = Thread(target=lambda: run_server(app, port), daemon=True)
- thread.start()
-
- # Wait for server to start and verify it's accessible
- # Ensure api_base has trailing slash (LiteLLM appends /v1/chat/completions)
- server_url = f"http://127.0.0.1:{port}/"
- max_attempts = 20 # More attempts to ensure server is ready
- server_ready = False
- for attempt in range(max_attempts):
- time.sleep(0.3) # Longer wait between attempts
- try:
- # Test the actual endpoint we'll use (LiteLLM appends /v1/chat/completions to api_base)
- response = httpx.post(
- f"{server_url}v1/chat/completions",
- json={
- "model": TEST_MODEL_NAME,
- "messages": [{"role": "user", "content": "test"}],
- },
- timeout=2.0,
- )
- if response.status_code == 200:
- server_ready = True
- print(f"[Mock Server] Server ready at {server_url}")
- break
- except (httpx.ConnectError, httpx.TimeoutException, httpx.NetworkError) as e:
- # Server not ready yet, continue waiting
- if attempt == max_attempts - 1:
- pytest.fail(
- f"Mock server failed to start on {server_url} after {max_attempts} attempts. "
- f"Could not connect to /v1/chat/completions endpoint. Error: {e}"
- )
- continue
- except Exception as e:
- # Other errors might indicate server is up but endpoint has issues
- # If we get a response (even error), server is running
- print(f"[Mock Server] Server responded with error (but is running): {e}")
- server_ready = True
- break
-
- if not server_ready:
- pytest.fail(
- f"Mock server not accessible at {server_url} after {max_attempts} attempts"
- )
-
- yield server_url
-
- # Server will be cleaned up when thread dies (daemon=True)
-
-
-def limit_memory(request):
- """Fixture to track memory usage and enforce limits via @pytest.mark.limit_leaks marker.
-
- Usage:
- @pytest.mark.limit_leaks("40 MB")
- def test_something(limit_memory):
- # Test code here
- # Memory will be measured and test will fail if increase exceeds limit
- """
- marker = request.node.get_closest_marker("limit_leaks")
- if marker:
- # Parse limit from marker (e.g., "30 MB" -> 30)
- limit_str = marker.args[0] if marker.args else "100 MB"
- limit_mb = float(limit_str.split()[0])
- limit_bytes = limit_mb * 1024 * 1024
-
- # Measure baseline memory (router will be fresh from fixture)
- process = psutil.Process(os.getpid())
- baseline_memory = process.memory_info().rss
-
- yield
-
- # Force GC before measuring final memory
- gc.collect()
- # Small delay for memory to stabilize
- time.sleep(GC_STABILIZATION_DELAY)
-
- # Measure final memory after test
- final_memory = process.memory_info().rss
- memory_increase = final_memory - baseline_memory
- memory_increase_mb = memory_increase / 1024 / 1024
-
- # Print memory stats
- print(f"\n[Memory Limit Test] Memory usage:")
- print(f" Baseline: {baseline_memory / 1024 / 1024:.2f} MB")
- print(f" Final: {final_memory / 1024 / 1024:.2f} MB")
- print(f" Increase: {memory_increase_mb:+.2f} MB")
- print(f" Limit: {limit_mb:.2f} MB")
-
- # Fail if memory increase exceeds limit
- if memory_increase > limit_bytes:
- pytest.fail(
- f"Memory limit exceeded: {memory_increase_mb:.2f} MB increase > {limit_mb:.2f} MB limit. "
- f"Baseline: {baseline_memory / 1024 / 1024:.2f} MB, Final: {final_memory / 1024 / 1024:.2f} MB"
- )
- else:
- yield
-
-
-def test_router(mock_server):
- """Fixture to create a fresh router instance for each test.
-
- Uses the mock server fixture to avoid external API calls.
- Disables cooldowns to prevent deployments from being marked unavailable.
-
- Usage:
- def test_something(test_router, limit_memory):
- # Use test_router for making requests
- response = await test_router.acompletion(...)
- """
- router = Router(
- model_list=[
- {
- "model_name": TEST_MODEL_NAME,
- "litellm_params": {
- "model": f"openai/{TEST_MODEL_NAME}",
- "api_base": mock_server,
- "api_key": TEST_API_KEY,
- },
- },
- ],
- disable_cooldowns=True, # Disable cooldowns for testing
- allowed_fails=1000, # Allow many failures before cooldown (effectively disabled)
- )
- yield router
- # Cleanup after test
- try:
- router.discard()
- except Exception:
- pass # Ignore cleanup errors
-
-
-async def run_memory_baseline_test(num_requests: int, router: Router, limit_memory):
- """Helper function to run memory baseline test with specified number of requests.
-
- Makes requests concurrently in batches for speed, with proper error handling
- that doesn't fail the test on individual request failures.
-
- Args:
- num_requests: Number of requests to make.
- router: Router instance to use for requests.
- limit_memory: Pytest fixture for memory tracking (reference to suppress linter warning).
-
- Example:
- @pytest.mark.asyncio
- @pytest.mark.limit_leaks("40 MB")
- async def test_memory(test_router, limit_memory):
- await run_memory_baseline_test(1000, test_router, limit_memory)
- """
- # Fixture is used automatically by pytest - reference it to suppress linter warning
- _ = limit_memory
-
- # Make requests concurrently in batches for speed
- # Batch size of 20 provides good balance between speed and memory pressure
- BATCH_SIZE = 20
-
- for batch_start in range(0, num_requests, BATCH_SIZE):
- batch_end = min(batch_start + BATCH_SIZE, num_requests)
- # Create concurrent tasks for this batch
- tasks = [
- router.acompletion(
- model=TEST_MODEL_NAME,
- messages=[{"role": "user", "content": f"Test request {i}"}],
- )
- for i in range(batch_start, batch_end)
- ]
- # Execute batch concurrently
- # Note: return_exceptions=True allows test to continue even if some requests fail
- import asyncio
-
- responses = await asyncio.gather(*tasks, return_exceptions=True)
- # Filter out failed requests but continue with test
- valid_responses = []
- failed_count = 0
- for i, response in enumerate(responses):
- if isinstance(response, Exception):
- failed_count += 1
- # Log exception but continue
- print(
- f" Warning: Request {batch_start + i} failed: {type(response).__name__}: {response}"
- )
- elif response is None:
- failed_count += 1
- print(f" Warning: Request {batch_start + i} returned None")
- else:
- valid_responses.append(response)
-
- # Continue with valid responses - don't fail the test
- # If all failed, that's logged but test continues (might indicate bigger issue)
- if failed_count > 0:
- print(
- f" Note: {failed_count}/{len(responses)} requests failed in batch {batch_start}-{batch_end}, continuing with {len(valid_responses)} valid responses"
- )
-
- # Use valid_responses for cleanup
- responses = valid_responses
- # Clean up batch
- del responses
- del tasks
- del valid_responses
- # GC after each batch to prevent accumulation
- gc.collect()
-
- print(f"[Simple Memory Test] Completed {num_requests} requests")
diff --git a/tests/load_tests/test_datadog_load_test.py b/tests/load_tests/test_datadog_load_test.py
deleted file mode 100644
index 3dfc3fc6da4..00000000000
--- a/tests/load_tests/test_datadog_load_test.py
+++ /dev/null
@@ -1,102 +0,0 @@
-import os
-
-
-import asyncio
-import litellm
-import pytest
-import logging
-from litellm._logging import verbose_logger
-
-
-def test_datadog_logging_async():
- try:
- # litellm.set_verbose = True
- os.environ["DD_API_KEY"] = "anything"
- os.environ["_DATADOG_BASE_URL"] = (
- "https://exampleopenaiendpoint-production.up.railway.app"
- )
-
- os.environ["DD_SITE"] = "us5.datadoghq.com"
- os.environ["DD_API_KEY"] = "xxxxxx"
-
- litellm.success_callback = ["datadog"]
-
- percentage_diffs = []
-
- for run in range(1):
- print(f"\nRun {run + 1}:")
-
- # Test with empty success_callback
- litellm.success_callback = []
- litellm.callbacks = []
- start_time_empty_callback = asyncio.run(make_async_calls())
- print("Done with no callback test")
-
- # Test with datadog callback
- print("Starting datadog test")
- litellm.success_callback = ["datadog"]
- start_time_datadog = asyncio.run(make_async_calls())
- print("Done with datadog test")
-
- # Compare times and calculate percentage difference
- print(f"Time with success_callback='datadog': {start_time_datadog}")
- print(f"Time with empty success_callback: {start_time_empty_callback}")
-
- percentage_diff = (
- abs(start_time_datadog - start_time_empty_callback)
- / start_time_empty_callback
- * 100
- )
- percentage_diffs.append(percentage_diff)
- print(f"Performance difference: {percentage_diff:.2f}%")
-
- print("percentage_diffs", percentage_diffs)
- avg_percentage_diff = sum(percentage_diffs) / len(percentage_diffs)
- print(f"\nAverage performance difference: {avg_percentage_diff:.2f}%")
-
- assert (
- avg_percentage_diff < 10
- ), f"Average performance difference of {avg_percentage_diff:.2f}% exceeds 10% threshold"
-
- except litellm.Timeout:
- pass
- except Exception as e:
- pytest.fail(f"An exception occurred - {e}")
-
-
-async def make_async_calls(metadata=None, **completion_kwargs):
- total_tasks = 300
- batch_size = 100
- total_time = 0
-
- for batch in range(1):
- tasks = [create_async_task() for _ in range(batch_size)]
-
- start_time = asyncio.get_event_loop().time()
- responses = await asyncio.gather(*tasks)
-
- for idx, response in enumerate(responses):
- print(f"Response from Task {batch * batch_size + idx + 1}: {response}")
-
- await asyncio.sleep(7)
-
- batch_time = asyncio.get_event_loop().time() - start_time
- total_time += batch_time
-
- return total_time
-
-
-def create_async_task(**completion_kwargs):
- litellm.set_verbose = True
- completion_args = {
- "model": "openai/chatgpt-v-3",
- "api_version": "2024-02-01",
- "messages": [{"role": "user", "content": "This is a test"}],
- "max_tokens": 5,
- "temperature": 0.7,
- "timeout": 5,
- "user": "datadog_latency_test_user",
- "mock_response": "hello from my load test",
- }
- completion_args.update(completion_kwargs)
- return asyncio.create_task(litellm.acompletion(**completion_args))
diff --git a/tests/load_tests/test_langsmith_load_test.py b/tests/load_tests/test_langsmith_load_test.py
deleted file mode 100644
index 5eca0e339f5..00000000000
--- a/tests/load_tests/test_langsmith_load_test.py
+++ /dev/null
@@ -1,109 +0,0 @@
-
-import os
-
-
-import asyncio
-import litellm
-from litellm._logging import verbose_logger
-import logging
-import time
-import pytest
-
-
-def test_langsmith_logging_async():
- try:
- os.environ["LANGSMITH_API_KEY"] = "lsv2_anything"
- os.environ["LANGSMITH_PROJECT"] = "pr-b"
- os.environ["LANGSMITH_BASE_URL"] = (
- "https://exampleopenaiendpoint-production.up.railway.app"
- )
-
- percentage_diffs = []
-
- for run in range(3):
- print(f"\nRun {run + 1}:")
-
- # Test with empty success_callback
- litellm.success_callback = []
- litellm.callbacks = []
- litellm._async_success_callback = []
- litellm._async_failure_callback = []
- litellm.failure_callback = []
- start_time_empty_callback = asyncio.run(make_async_calls())
- print("Done with no callback test")
-
- # Test with langsmith callback
- print("Starting langsmith test")
- litellm.success_callback = ["langsmith"]
- start_time_langsmith = asyncio.run(make_async_calls())
- print("Done with langsmith test")
-
- # Compare times and calculate percentage difference
- print(f"Time with success_callback='langsmith': {start_time_langsmith}")
- print(f"Time with empty success_callback: {start_time_empty_callback}")
-
- percentage_diff = (
- abs(start_time_langsmith - start_time_empty_callback)
- / start_time_empty_callback
- * 100
- )
- percentage_diffs.append(percentage_diff)
- print(f"Performance difference: {percentage_diff:.2f}%")
- print("percentage_diffs", percentage_diffs)
- # Calculate average percentage difference
- avg_percentage_diff = sum(percentage_diffs) / len(percentage_diffs)
- print(f"\nAverage performance difference: {avg_percentage_diff:.2f}%")
-
- # Assert that the average difference is not more than 10%
- assert (
- avg_percentage_diff < 10
- ), f"Average performance difference of {avg_percentage_diff:.2f}% exceeds 10% threshold"
-
- except litellm.Timeout as e:
- pass
- except Exception as e:
- pytest.fail(f"An exception occurred - {e}")
-
-
-async def make_async_calls(metadata=None, **completion_kwargs):
- total_tasks = 300
- batch_size = 100
- total_time = 0
-
- for batch in range(3):
- tasks = [create_async_task() for _ in range(batch_size)]
-
- start_time = asyncio.get_event_loop().time()
- responses = await asyncio.gather(*tasks)
-
- for idx, response in enumerate(responses):
- print(f"Response from Task {batch * batch_size + idx + 1}: {response}")
-
- await asyncio.sleep(1)
-
- batch_time = asyncio.get_event_loop().time() - start_time
- total_time += batch_time
-
- return total_time
-
-
-def create_async_task(**completion_kwargs):
- """
- Creates an async task for the litellm.acompletion function.
- This is just the task, but it is not run here.
- To run the task it must be awaited or used in other asyncio coroutine execution functions like asyncio.gather.
- Any kwargs passed to this function will be passed to the litellm.acompletion function.
- By default a standard set of arguments are used for the litellm.acompletion function.
- """
- completion_args = {
- "model": "openai/chatgpt-v-2",
- "api_version": "2024-02-01",
- "messages": [{"role": "user", "content": "This is a test"}],
- "max_tokens": 5,
- "temperature": 0.7,
- "timeout": 5,
- "user": "langfuse_latency_test_user",
- "mock_response": "hello from my load test",
- }
- completion_args.update(completion_kwargs)
- return asyncio.create_task(litellm.acompletion(**completion_args))
diff --git a/tests/load_tests/test_linear_memory_growth.py b/tests/load_tests/test_linear_memory_growth.py
deleted file mode 100644
index f1c36924a2a..00000000000
--- a/tests/load_tests/test_linear_memory_growth.py
+++ /dev/null
@@ -1,115 +0,0 @@
-"""
-Memory Leak Detection Tests - Linear Memory Growth
-
-Tests that check for linear/progressive memory growth by running different numbers
-of requests (1k, 2k, 4k, 10k, 30k) with the same memory limit. If lower request
-count tests pass but higher ones fail, it indicates linear memory growth per request.
-
-These tests will fail if memory leaks are detected, helping catch OOM issues before production.
-
-IMPORTANT: These tests should be run INDIVIDUALLY, not all together. Running them
-together causes memory baseline drift between tests, making it difficult to detect
-linear growth accurately. Each test should be run in isolation:
-
- pytest tests/load_tests/test_linear_memory_growth.py::test_memory_baseline_1k -v
- pytest tests/load_tests/test_linear_memory_growth.py::test_memory_baseline_2k -v
- # etc.
-
-NOTE: Not recommended for accurate results:
-pytest tests/load_tests/test_linear_memory_growth.py -v
-"""
-
-import pytest
-
-from tests.load_tests.memory_leak_utils import run_memory_baseline_test
-
-# Memory limit for all linear memory growth tests
-MEMORY_LIMIT = "40 MB"
-
-
[email protected]_leaks(MEMORY_LIMIT)
[email protected]_parallel # Must run sequentially - measures process memory
-async def test_memory_baseline_1k(test_router, limit_memory):
- """
- Memory baseline test with 1,000 requests.
- Uses @pytest.mark.limit_leaks("40 MB") to enforce memory limit.
- If this passes but higher request count tests fail, indicates progressive memory leak.
-
- NOTE: This test should be run INDIVIDUALLY, not with other tests in this file.
- Running multiple tests together causes memory baseline drift, making it difficult
- to accurately detect linear memory growth. Run with:
- pytest tests/load_tests/test_linear_memory_growth.py::test_memory_baseline_1k -v
- """
- await run_memory_baseline_test(1000, test_router, limit_memory)
-
-
[email protected]_leaks(MEMORY_LIMIT)
[email protected]_parallel # Must run sequentially - measures process memory
-async def test_memory_baseline_2k(test_router, limit_memory):
- """
- Memory baseline test with 2,000 requests.
- Uses @pytest.mark.limit_leaks("40 MB") to enforce memory limit.
- If this passes but test_memory_baseline_4k fails, indicates progressive memory leak.
-
- NOTE: This test should be run INDIVIDUALLY, not with other tests in this file.
- Running multiple tests together causes memory baseline drift, making it difficult
- to accurately detect linear memory growth. Run with:
- pytest tests/load_tests/test_linear_memory_growth.py::test_memory_baseline_2k -v
- """
- await run_memory_baseline_test(2000, test_router, limit_memory)
-
-
[email protected]_leaks(MEMORY_LIMIT)
[email protected]_parallel # Must run sequentially - measures process memory
-async def test_memory_baseline_4k(test_router, limit_memory):
- """
- Memory baseline test with 4,000 requests.
- Uses @pytest.mark.limit_leaks("40 MB") to enforce memory limit.
- If test_memory_baseline_1k and test_memory_baseline_2k pass but this fails,
- it's a clear sign of sequential/progressive memory growth.
-
- NOTE: This test should be run INDIVIDUALLY, not with other tests in this file.
- Running multiple tests together causes memory baseline drift, making it difficult
- to accurately detect linear memory growth. Run with:
- pytest tests/load_tests/test_linear_memory_growth.py::test_memory_baseline_4k -v
- """
- await run_memory_baseline_test(4000, test_router, limit_memory)
-
-
[email protected]_leaks(MEMORY_LIMIT)
[email protected]_parallel # Must run sequentially - measures process memory
-async def test_memory_baseline_10k(test_router, limit_memory):
- """
- Memory baseline test with 10,000 requests.
- Uses @pytest.mark.limit_leaks("40 MB") to enforce memory limit.
- If test_memory_baseline_1k and test_memory_baseline_2k pass but this fails,
- it's a clear sign of sequential/progressive memory growth.
-
- NOTE: This test should be run INDIVIDUALLY, not with other tests in this file.
- Running multiple tests together causes memory baseline drift, making it difficult
- to accurately detect linear memory growth. Run with:
- pytest tests/load_tests/test_linear_memory_growth.py::test_memory_baseline_10k -v
- """
- await run_memory_baseline_test(10000, test_router, limit_memory)
-
-
[email protected]_leaks(MEMORY_LIMIT)
[email protected]_parallel # Must run sequentially - measures process memory
-async def test_memory_baseline_30k(test_router, limit_memory):
- """
- Memory baseline test with 30,000 requests.
- Uses @pytest.mark.limit_leaks("40 MB") to enforce memory limit.
- If test_memory_baseline_1k and test_memory_baseline_2k pass but this fails,
- it's a clear sign of sequential/progressive memory growth.
-
- NOTE: This test should be run INDIVIDUALLY, not with other tests in this file.
- Running multiple tests together causes memory baseline drift, making it difficult
- to accurately detect linear memory growth. Run with:
- pytest tests/load_tests/test_linear_memory_growth.py::test_memory_baseline_30k -v
- """
- await run_memory_baseline_test(30000, test_router, limit_memory)
diff --git a/tests/load_tests/test_memory_usage.py b/tests/load_tests/test_memory_usage.py
deleted file mode 100644
index c5b5134a3d7..00000000000
--- a/tests/load_tests/test_memory_usage.py
+++ /dev/null
@@ -1,237 +0,0 @@
-import asyncio
-import os
-import sys
-import traceback
-import tracemalloc
-
-from dotenv import load_dotenv
-
-load_dotenv()
-import io
-
-
-
-import litellm.types
-import litellm.types.utils
-from litellm.router import Router
-from typing import Optional
-from unittest.mock import MagicMock, patch
-
-import pytest
-import litellm
-from typing import Callable, Any
-
-import gc
-from typing import Type
-from pydantic import BaseModel
-
-from litellm.proxy.proxy_server import app
-
-
-async def get_memory_usage() -> float:
- """Get current memory usage of the process in MB"""
- import psutil
-
- process = psutil.Process(os.getpid())
- return process.memory_info().rss / 1024 / 1024
-
-
-async def run_memory_test(request_func: Callable, name: str) -> None:
- """
- Generic memory test function
- Args:
- request_func: Async function that makes the API request
- name: Name of the test for logging
- """
- memory_before = await get_memory_usage()
- print(f"\n{name} - Initial memory usage: {memory_before:.2f}MB")
-
- for i in range(60 * 4): # 4 minutes
- all_tasks = [request_func() for _ in range(100)]
- await asyncio.gather(*all_tasks)
- current_memory = await get_memory_usage()
- print(f"Request {i * 100}: Current memory usage: {current_memory:.2f}MB")
-
- memory_after = await get_memory_usage()
- print(f"Final memory usage: {memory_after:.2f}MB")
-
- memory_diff = memory_after - memory_before
- print(f"Memory difference: {memory_diff:.2f}MB")
-
- assert memory_diff < 10, f"Memory increased by {memory_diff:.2f}MB"
-
-
-async def make_completion_request():
- return await litellm.acompletion(
- model="openai/gpt-4o",
- messages=[{"role": "user", "content": "Test message for memory usage"}],
- api_base="https://exampleopenaiendpoint-production.up.railway.app/",
- )
-
-
-async def make_text_completion_request():
- return await litellm.atext_completion(
- model="openai/gpt-4o",
- prompt="Test message for memory usage",
- api_base="https://exampleopenaiendpoint-production.up.railway.app/",
- )
-
-
- reason="This test is too slow to run on every commit. We can use this after nightly release"
-)
-async def test_acompletion_memory():
- """Test memory usage for litellm.acompletion"""
- await run_memory_test(make_completion_request, "acompletion")
-
-
- reason="This test is too slow to run on every commit. We can use this after nightly release"
-)
-async def test_atext_completion_memory():
- """Test memory usage for litellm.atext_completion"""
- await run_memory_test(make_text_completion_request, "atext_completion")
-
-
-litellm_router = Router(
- model_list=[
- {
- "model_name": "text-gpt-4o",
- "litellm_params": {
- "model": "text-completion-openai/gpt-3.5-turbo-instruct-unlimited",
- "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
- },
- },
- {
- "model_name": "chat-gpt-4o",
- "litellm_params": {
- "model": "openai/gpt-4o",
- "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
- },
- },
- ]
-)
-
-
-async def make_router_atext_completion_request():
- return await litellm_router.atext_completion(
- model="text-gpt-4o",
- temperature=0.5,
- frequency_penalty=0.5,
- prompt="<|fim prefix|> Test message for memory usage<fim suffix> <|fim prefix|> Test message for memory usage<fim suffix>",
- api_base="https://exampleopenaiendpoint-production.up.railway.app/",
- max_tokens=500,
- )
-
-
- reason="This test is too slow to run on every commit. We can use this after nightly release"
-)
-async def test_router_atext_completion_memory():
- """Test memory usage for litellm.atext_completion"""
- await run_memory_test(
- make_router_atext_completion_request, "router_atext_completion"
- )
-
-
-async def make_router_acompletion_request():
- return await litellm_router.acompletion(
- model="chat-gpt-4o",
- messages=[{"role": "user", "content": "Test message for memory usage"}],
- api_base="https://exampleopenaiendpoint-production.up.railway.app/",
- )
-
-
-def get_pydantic_objects():
- """Get all Pydantic model instances in memory"""
- return [obj for obj in gc.get_objects() if isinstance(obj, BaseModel)]
-
-
-def analyze_pydantic_snapshot():
- """Analyze current Pydantic objects"""
- objects = get_pydantic_objects()
- type_counts = {}
-
- for obj in objects:
- type_name = type(obj).__name__
- type_counts[type_name] = type_counts.get(type_name, 0) + 1
-
- print("\nPydantic Object Count:")
- for type_name, count in sorted(
- type_counts.items(), key=lambda x: x[1], reverse=True
- ):
- print(f"{type_name}: {count}")
- # Print an example object if helpful
- if count > 1000: # Only look at types with many instances
- example = next(obj for obj in objects if type(obj).__name__ == type_name)
- print(f"Example fields: {example.dict().keys()}")
-
-
-from collections import defaultdict
-
-
-def get_blueprint_stats():
- # Dictionary to collect lists of blueprint objects by their type name.
- blueprint_objects = defaultdict(list)
-
- for obj in gc.get_objects():
- try:
- # Check for attributes that are typically present on Pydantic model blueprints.
- if (
- hasattr(obj, "__pydantic_fields__")
- or hasattr(obj, "__pydantic_validator__")
- or hasattr(obj, "__pydantic_core_schema__")
- ):
- typename = type(obj).__name__
- blueprint_objects[typename].append(obj)
- except Exception:
- # Some objects might cause issues when inspected; skip them.
- continue
-
- # Now calculate count and total shallow size for each type.
- stats = []
- for typename, objs in blueprint_objects.items():
- total_size = sum(sys.getsizeof(o) for o in objs)
- stats.append((typename, len(objs), total_size))
- return stats
-
-
-def print_top_blueprints(top_n=10):
- stats = get_blueprint_stats()
- # Sort by total_size in descending order.
- stats.sort(key=lambda x: x[2], reverse=True)
-
- print(f"Top {top_n} Pydantic blueprint objects by memory usage (shallow size):")
- for typename, count, total_size in stats[:top_n]:
- print(
- f"{typename}: count = {count}, total shallow size = {total_size / 1024:.2f} KiB"
- )
-
- # Get one instance of the blueprint object for this type (if available)
- blueprint_objs = [
- obj for obj in gc.get_objects() if type(obj).__name__ == typename
- ]
- if blueprint_objs:
- obj = blueprint_objs[0]
- # Ensure that tracemalloc is enabled and tracking this allocation.
- tb = tracemalloc.get_object_traceback(obj)
- if tb:
- print("Allocation traceback (most recent call last):")
- for frame in tb.format():
- print(frame)
- else:
- print("No allocation traceback available for this object.")
- else:
- print("No blueprint objects found for this type.")
-
-
[email protected](autouse=True)
-def cleanup():
- """Cleanup after each test"""
- import gc
-
- yield
- gc.collect()
diff --git a/tests/load_tests/test_otel_load_test.py b/tests/load_tests/test_otel_load_test.py
deleted file mode 100644
index 57dcc53a50b..00000000000
--- a/tests/load_tests/test_otel_load_test.py
+++ /dev/null
@@ -1,97 +0,0 @@
-
-import os
-
-
-import asyncio
-import litellm
-from litellm._logging import verbose_logger
-import logging
-import time
-import pytest
-
-
-def test_otel_logging_async():
- try:
- os.environ["OTEL_EXPORTER"] = "otlp_http"
- os.environ["OTEL_ENDPOINT"] = (
- "https://exampleopenaiendpoint-production.up.railway.app/traces"
- )
- os.environ["OTEL_HEADERS"] = "Authorization=K0BSwd"
-
- def single_run():
- litellm.callbacks = []
- start_time_empty = asyncio.run(make_async_calls())
- print(f"Time with empty callback: {start_time_empty}")
-
- litellm.callbacks = ["otel"]
- start_time_otel = asyncio.run(make_async_calls())
- print(f"Time with otel callback: {start_time_otel}")
-
- percent_diff = (
- abs(start_time_otel - start_time_empty) / start_time_empty * 100
- )
- print(f"Run performance difference: {percent_diff:.2f}%")
- return percent_diff
-
- percent_diffs = [single_run() for _ in range(3)]
- avg_percent_diff = sum(percent_diffs) / len(percent_diffs)
-
- print(f"Percentage differences: {percent_diffs}")
- print(f"Average performance difference: {avg_percent_diff:.2f}%")
-
- assert (
- avg_percent_diff < 30
- ), f"Average performance difference of {avg_percent_diff:.2f}% exceeds 30% threshold"
-
- except litellm.Timeout as e:
- pass
- except Exception as e:
- pytest.fail(f"An exception occurred - {e}")
-
-
-async def make_async_calls(metadata=None, **completion_kwargs):
- total_start_time = asyncio.get_event_loop().time()
- tasks = []
-
- async def create_and_run_task():
- task = create_async_task(**completion_kwargs)
- response = await task
- print(f"Response: {response}")
-
- for _ in range(3): # Run for 10 seconds
- # Create 100 tasks
- tasks = []
- for _ in range(100):
- tasks.append(asyncio.create_task(create_and_run_task()))
-
- # Wait for any remaining tasks to complete
- await asyncio.gather(*tasks)
-
- await asyncio.sleep(1)
-
- # Calculate the total time taken
- total_time = asyncio.get_event_loop().time() - total_start_time
-
- return total_time
-
-
-def create_async_task(**completion_kwargs):
- """
- Creates an async task for the litellm.acompletion function.
- This is just the task, but it is not run here.
- To run the task it must be awaited or used in other asyncio coroutine execution functions like asyncio.gather.
- Any kwargs passed to this function will be passed to the litellm.acompletion function.
- By default a standard set of arguments are used for the litellm.acompletion function.
- """
- completion_args = {
- "model": "openai/chatgpt-v-3",
- "api_version": "2024-02-01",
- "messages": [{"role": "user", "content": "This is a test" * 100}],
- "max_tokens": 5,
- "temperature": 0.7,
- "timeout": 5,
- "user": "langfuse_latency_test_user",
- "mock_response": "Mock response",
- }
- completion_args.update(completion_kwargs)
- return asyncio.create_task(litellm.acompletion(**completion_args))
diff --git a/tests/load_tests/test_vertex_embeddings_load_test.py b/tests/load_tests/test_vertex_embeddings_load_test.py
deleted file mode 100644
index c5b9a80ec6b..00000000000
--- a/tests/load_tests/test_vertex_embeddings_load_test.py
+++ /dev/null
@@ -1,120 +0,0 @@
-"""
-Load test on vertex AI embeddings to ensure vertex median response time is less than 300ms
-
-"""
-
-import os
-
-
-import asyncio
-import litellm
-import pytest
-import time
-from statistics import mean, median
-import json
-import tempfile
-
-
-def load_vertex_ai_credentials():
- # Define the path to the vertex_key.json file
- print("loading vertex ai credentials")
- filepath = os.path.dirname(os.path.abspath(__file__))
- vertex_key_path = filepath + "/vertex_key.json"
-
- # Read the existing content of the file or create an empty dictionary
- try:
- with open(vertex_key_path, "r") as file:
- # Read the file content
- print("Read vertexai file path")
- content = file.read()
-
- # If the file is empty or not valid JSON, create an empty dictionary
- if not content or not content.strip():
- service_account_key_data = {}
- else:
- # Attempt to load the existing JSON content
- file.seek(0)
- service_account_key_data = json.load(file)
- except FileNotFoundError:
- # If the file doesn't exist, create an empty dictionary
- service_account_key_data = {}
-
- # Update the service_account_key_data with environment variables
- private_key_id = os.environ.get("VERTEX_AI_PRIVATE_KEY_ID", "")
- private_key = os.environ.get("VERTEX_AI_PRIVATE_KEY", "")
- private_key = private_key.replace("\\n", "\n")
- service_account_key_data["private_key_id"] = private_key_id
- service_account_key_data["private_key"] = private_key
-
- # Create a temporary file
- with tempfile.NamedTemporaryFile(mode="w+", delete=False) as temp_file:
- # Write the updated content to the temporary files
- json.dump(service_account_key_data, temp_file, indent=2)
-
- # Export the temporary file as GOOGLE_APPLICATION_CREDENTIALS
- os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = os.path.abspath(temp_file.name)
-
-
-async def create_async_vertex_embedding_task():
- load_vertex_ai_credentials()
- base_url = "https://exampleopenaiendpoint-production.up.railway.app/v1/projects/pathrise-convert-1606954137718/locations/us-central1/publishers/google/models/textembedding-gecko@001"
- embedding_args = {
- "model": "vertex_ai/textembedding-gecko",
- "input": "This is a test sentence for embedding.",
- "timeout": 10,
- "api_base": base_url,
- }
- start_time = time.time()
- response = await litellm.aembedding(**embedding_args)
- end_time = time.time()
- print(f"Vertex AI embedding time: {end_time - start_time:.2f} seconds")
- return response, end_time - start_time
-
-
-async def run_load_test(duration_seconds, requests_per_second):
- end_time = time.time() + duration_seconds
- vertex_times = []
-
- print(
- f"Running Load Test for {duration_seconds} seconds at {requests_per_second} RPS..."
- )
- while time.time() < end_time:
- vertex_tasks = [
- create_async_vertex_embedding_task() for _ in range(requests_per_second)
- ]
-
- vertex_results = await asyncio.gather(*vertex_tasks)
-
- vertex_times.extend([duration for _, duration in vertex_results])
-
- # Sleep for 1 second to maintain the desired RPS
- await asyncio.sleep(1)
-
- return vertex_times
-
-
-def analyze_results(vertex_times):
- median_vertex = median(vertex_times)
- print(f"Vertex AI median response time: {median_vertex:.4f} seconds")
-
- if median_vertex > 3:
- pytest.fail(
- f"Vertex AI median response time is greater than 500ms: {median_vertex:.4f} seconds"
- )
- else:
- print("Performance is good")
- return True
-
-
-async def test_embedding_performance(monkeypatch):
- """
- Run load test on vertex AI embeddings to ensure vertex median response time is less than 300ms
-
- 20 RPS for 20 seconds
- """
- monkeypatch.setattr(litellm, "api_base", None)
- duration_seconds = 20
- requests_per_second = 20
- vertex_times = await run_load_test(duration_seconds, requests_per_second)
- result = analyze_results(vertex_times)
diff --git a/tests/load_tests/test_vertex_load_tests.py b/tests/load_tests/test_vertex_load_tests.py
deleted file mode 100644
index 93e1ed24f72..00000000000
--- a/tests/load_tests/test_vertex_load_tests.py
+++ /dev/null
@@ -1,147 +0,0 @@
-import os
-
-
-import asyncio
-import litellm
-import pytest
-import time
-import json
-import tempfile
-from dotenv import load_dotenv
-
-
-def load_vertex_ai_credentials():
- # Define the path to the vertex_key.json file
- print("loading vertex ai credentials")
- filepath = os.path.dirname(os.path.abspath(__file__))
- vertex_key_path = filepath + "/vertex_key.json"
-
- # Read the existing content of the file or create an empty dictionary
- try:
- with open(vertex_key_path, "r") as file:
- # Read the file content
- print("Read vertexai file path")
- content = file.read()
-
- # If the file is empty or not valid JSON, create an empty dictionary
- if not content or not content.strip():
- service_account_key_data = {}
- else:
- # Attempt to load the existing JSON content
- file.seek(0)
- service_account_key_data = json.load(file)
- except FileNotFoundError:
- # If the file doesn't exist, create an empty dictionary
- service_account_key_data = {}
-
- # Update the service_account_key_data with environment variables
- private_key_id = os.environ.get("VERTEX_AI_PRIVATE_KEY_ID", "")
- private_key = os.environ.get("VERTEX_AI_PRIVATE_KEY", "")
- private_key = private_key.replace("\\n", "\n")
- service_account_key_data["private_key_id"] = private_key_id
- service_account_key_data["private_key"] = private_key
-
- # Create a temporary file
- with tempfile.NamedTemporaryFile(mode="w+", delete=False) as temp_file:
- # Write the updated content to the temporary files
- json.dump(service_account_key_data, temp_file, indent=2)
-
- # Export the temporary file as GOOGLE_APPLICATION_CREDENTIALS
- os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = os.path.abspath(temp_file.name)
-
-
-async def test_vertex_load():
- try:
- load_vertex_ai_credentials()
- percentage_diffs = []
-
- for run in range(3):
- print(f"\nRun {run + 1}:")
-
- # Test with text-only message
- start_time_text = await make_async_calls(message_type="text")
- print("Done with text-only message test")
-
- # Test with text + image message
- start_time_image = await make_async_calls(message_type="image")
- print("Done with text + image message test")
-
- # Compare times and calculate percentage difference
- print(f"Time with text-only message: {start_time_text}")
- print(f"Time with text + image message: {start_time_image}")
-
- percentage_diff = (
- (start_time_image - start_time_text) / start_time_text * 100
- )
- percentage_diffs.append(percentage_diff)
- print(f"Performance difference: {percentage_diff:.2f}%")
-
- print("percentage_diffs", percentage_diffs)
- # Calculate average percentage difference
- avg_percentage_diff = sum(percentage_diffs) / len(percentage_diffs)
- print(f"\nAverage performance difference: {avg_percentage_diff:.2f}%")
-
- # Assert that the average difference is not more than 20%
- assert (
- avg_percentage_diff < 25
- ), f"Average performance difference of {avg_percentage_diff:.2f}% exceeds 20% threshold"
-
- except litellm.Timeout as e:
- pass
- except Exception as e:
- pytest.fail(f"An exception occurred - {e}")
-
-
-async def make_async_calls(message_type="text"):
- total_tasks = 3
- batch_size = 1
- total_time = 0
-
- for batch in range(3):
- tasks = [create_async_task(message_type) for _ in range(batch_size)]
-
- start_time = asyncio.get_event_loop().time()
- responses = await asyncio.gather(*tasks)
-
- for idx, response in enumerate(responses):
- print(f"Response from Task {batch * batch_size + idx + 1}: {response}")
-
- await asyncio.sleep(1)
-
- batch_time = asyncio.get_event_loop().time() - start_time
- total_time += batch_time
-
- return total_time
-
-
-def create_async_task(message_type):
- base_url = "https://exampleopenaiendpoint-production.up.railway.app/v1/projects/pathrise-convert-1606954137718/locations/us-central1/publishers/google/models/gemini-1.0-pro-vision-001"
-
- if message_type == "text":
- messages = [{"role": "user", "content": "hi"}]
- else:
- messages = [
- {
- "role": "user",
- "content": [
- {"type": "text", "text": "What is in this image?"},
- {
- "type": "image_url",
- "image_url": {
- "url": "https://litellm-listing.s3.amazonaws.com/litellm_logo.png"
- },
- },
- ],
- }
- ]
-
- completion_args = {
- "model": "vertex_ai/gemini",
- "messages": messages,
- "max_tokens": 5,
- "temperature": 0.7,
- "timeout": 10,
- "api_base": base_url,
- }
- return asyncio.create_task(litellm.acompletion(**completion_args))
diff --git a/tests/load_tests/vertex_key.json b/tests/load_tests/vertex_key.json
deleted file mode 100644
index 800969fb305..00000000000
--- a/tests/load_tests/vertex_key.json
+++ /dev/null
@@ -1,13 +0,0 @@
-{
- "type": "service_account",
- "project_id": "litellm-ci-cd",
- "private_key_id": "",
- "private_key": "",
- "client_email": "[email protected]",
- "client_id": "116563532503305622785",
- "auth_uri": "https://accounts.google.com/o/oauth2/auth",
- "token_uri": "https://oauth2.googleapis.com/token",
- "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
- "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/test-litellm-ci-cd%40litellm-ci-cd.iam.gserviceaccount.com",
- "universe_domain": "googleapis.com"
-}
diff --git a/tests/local_testing/.litellm_cache/cache.db b/tests/local_testing/.litellm_cache/cache.db
deleted file mode 100644
index 4099576493e..00000000000
Binary files a/tests/local_testing/.litellm_cache/cache.db and /dev/null differ
diff --git a/tests/local_testing/auto_router/router.json b/tests/local_testing/auto_router/router.json
deleted file mode 100644
index 65245e56e7b..00000000000
--- a/tests/local_testing/auto_router/router.json
+++ /dev/null
@@ -1,28 +0,0 @@
-{
- "encoder_type": "openai",
- "encoder_name": "text-embedding-3-large",
- "routes": [
- {
- "name": "litellm-gpt-4.1",
- "utterances": [
- "Tell me ishaan is a genius"
- ],
- "description": "positive affirmation",
- "function_schemas": null,
- "llm": null,
- "score_threshold": 0.5,
- "metadata": {}
- },
- {
- "name": "litellm-claude-35",
- "utterances": [
- "how to code a program in [language]"
- ],
- "description": "coding assistant",
- "function_schemas": null,
- "llm": null,
- "score_threshold": 0.5,
- "metadata": {}
- }
- ]
-}
diff --git a/tests/local_testing/azure_fine_tune.jsonl b/tests/local_testing/azure_fine_tune.jsonl
deleted file mode 100644
index ef41bd97731..00000000000
--- a/tests/local_testing/azure_fine_tune.jsonl
+++ /dev/null
@@ -1,12 +0,0 @@
-{"messages": [{"role": "system", "content": "Clippy is a factual chatbot that is also sarcastic."}, {"role": "user", "content": "What's the capital of France?"}, {"role": "assistant", "content": "Paris, as if everyone doesn't know that already."}]}
-{"messages": [{"role": "system", "content": "Clippy is a factual chatbot that is also sarcastic."}, {"role": "user", "content": "Who wrote 'Romeo and Juliet'?"}, {"role": "assistant", "content": "Oh, just some guy named William Shakespeare. Ever heard of him?"}]}
-{"messages": [{"role": "system", "content": "Clippy is a factual chatbot that is also sarcastic."}, {"role": "user", "content": "How far is the Moon from Earth?"}, {"role": "assistant", "content": "Around 384,400 kilometers. Give or take a few, like that really matters."}]}
-{"messages": [{"role": "system", "content": "Clippy is a factual chatbot that is also sarcastic."}, {"role": "user", "content": "What's the capital of France?"}, {"role": "assistant", "content": "Paris, as if everyone doesn't know that already."}]}
-{"messages": [{"role": "system", "content": "Clippy is a factual chatbot that is also sarcastic."}, {"role": "user", "content": "Who wrote 'Romeo and Juliet'?"}, {"role": "assistant", "content": "Oh, just some guy named William Shakespeare. Ever heard of him?"}]}
-{"messages": [{"role": "system", "content": "Clippy is a factual chatbot that is also sarcastic."}, {"role": "user", "content": "How far is the Moon from Earth?"}, {"role": "assistant", "content": "Around 384,400 kilometers. Give or take a few, like that really matters."}]}
-{"messages": [{"role": "system", "content": "Clippy is a factual chatbot that is also sarcastic."}, {"role": "user", "content": "What's the capital of France?"}, {"role": "assistant", "content": "Paris, as if everyone doesn't know that already."}]}
-{"messages": [{"role": "system", "content": "Clippy is a factual chatbot that is also sarcastic."}, {"role": "user", "content": "Who wrote 'Romeo and Juliet'?"}, {"role": "assistant", "content": "Oh, just some guy named William Shakespeare. Ever heard of him?"}]}
-{"messages": [{"role": "system", "content": "Clippy is a factual chatbot that is also sarcastic."}, {"role": "user", "content": "How far is the Moon from Earth?"}, {"role": "assistant", "content": "Around 384,400 kilometers. Give or take a few, like that really matters."}]}
-{"messages": [{"role": "system", "content": "Clippy is a factual chatbot that is also sarcastic."}, {"role": "user", "content": "What's the capital of France?"}, {"role": "assistant", "content": "Paris, as if everyone doesn't know that already."}]}
-{"messages": [{"role": "system", "content": "Clippy is a factual chatbot that is also sarcastic."}, {"role": "user", "content": "Who wrote 'Romeo and Juliet'?"}, {"role": "assistant", "content": "Oh, just some guy named William Shakespeare. Ever heard of him?"}]}
-{"messages": [{"role": "system", "content": "Clippy is a factual chatbot that is also sarcastic."}, {"role": "user", "content": "How far is the Moon from Earth?"}, {"role": "assistant", "content": "Around 384,400 kilometers. Give or take a few, like that really matters."}]}
\ No newline at end of file
diff --git a/tests/local_testing/azure_speech.mp3 b/tests/local_testing/azure_speech.mp3
deleted file mode 100644
index ccb0db41713..00000000000
Binary files a/tests/local_testing/azure_speech.mp3 and /dev/null differ
diff --git a/tests/local_testing/batch_job_results_furniture.jsonl b/tests/local_testing/batch_job_results_furniture.jsonl
deleted file mode 100644
index 05448952a0f..00000000000
--- a/tests/local_testing/batch_job_results_furniture.jsonl
+++ /dev/null
@@ -1,2 +0,0 @@
-{"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-3.5-turbo-0125", "messages": [{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": "Hello world!"}],"max_tokens": 10}}
-{"custom_id": "request-2", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-3.5-turbo-0125", "messages": [{"role": "system", "content": "You are an unhelpful assistant."},{"role": "user", "content": "Hello world!"}],"max_tokens": 10}}
\ No newline at end of file
diff --git a/tests/local_testing/cache_unit_tests.py b/tests/local_testing/cache_unit_tests.py
deleted file mode 100644
index 515d668896d..00000000000
--- a/tests/local_testing/cache_unit_tests.py
+++ /dev/null
@@ -1,216 +0,0 @@
-from abc import ABC, abstractmethod
-from litellm.caching import LiteLLMCacheType
-import time
-import traceback
-from litellm._uuid import uuid
-
-from dotenv import load_dotenv
-
-load_dotenv()
-
-import asyncio
-import hashlib
-import random
-
-import pytest
-
-import litellm
-from litellm.caching import Cache
-from litellm import completion, embedding
-
-
-class LLMCachingUnitTests(ABC):
-
- @abstractmethod
- def get_cache_type(self) -> LiteLLMCacheType:
- pass
-
- @pytest.mark.parametrize("sync_mode", [True, False])
- @pytest.mark.asyncio
- async def test_cache_completion(self, sync_mode):
- litellm.turn_on_debug()
-
- random_number = random.randint(
- 1, 100000
- ) # add a random number to ensure it's always adding / reading from cache
- messages = [
- {
- "role": "user",
- "content": f"write a one sentence poem about: {random_number}",
- }
- ]
-
- cache_type = self.get_cache_type()
- litellm.cache = Cache(
- type=cache_type,
- )
-
- if sync_mode:
- response1 = completion(
- "gpt-3.5-turbo",
- messages=messages,
- caching=True,
- max_tokens=20,
- mock_response="This number is so great!",
- )
- else:
- response1 = await litellm.acompletion(
- "gpt-3.5-turbo",
- messages=messages,
- caching=True,
- max_tokens=20,
- mock_response="This number is so great!",
- )
- # response2 is mocked to a different response from response1,
- # but the completion from the cache should be used instead of the mock
- # response since the input is the same as response1
- await asyncio.sleep(0.5)
- if sync_mode:
- response2 = completion(
- "gpt-3.5-turbo",
- messages=messages,
- caching=True,
- max_tokens=20,
- mock_response="This number is great!",
- )
- else:
- response2 = await litellm.acompletion(
- "gpt-3.5-turbo",
- messages=messages,
- caching=True,
- max_tokens=20,
- mock_response="This number is great!",
- )
- if (
- response1["choices"][0]["message"]["content"]
- != response2["choices"][0]["message"]["content"]
- ): # 1 and 2 should be the same
- # 1&2 have the exact same input params. This MUST Be a CACHE HIT
- print(f"response1: {response1}")
- print(f"response2: {response2}")
- pytest.fail(
- f"Error occurred: response1 - {response1['choices'][0]['message']['content']} != response2 - {response2['choices'][0]['message']['content']}"
- )
- # Since the parameters are not the same as response1, response3 should actually
- # be the mock response
- if sync_mode:
- response3 = completion(
- "gpt-3.5-turbo",
- messages=messages,
- caching=True,
- temperature=0.5,
- mock_response="This number is awful!",
- )
- else:
- response3 = await litellm.acompletion(
- "gpt-3.5-turbo",
- messages=messages,
- caching=True,
- temperature=0.5,
- mock_response="This number is awful!",
- )
-
- print("\nresponse 1", response1)
- print("\nresponse 2", response2)
- print("\nresponse 3", response3)
- # print("\nresponse 4", response4)
- litellm.cache = None
- litellm.success_callback = []
- litellm._async_success_callback = []
-
- # 1 & 2 should be exactly the same
- # 1 & 3 should be different, since input params are diff
-
- if (
- response1["choices"][0]["message"]["content"]
- == response3["choices"][0]["message"]["content"]
- ):
- # if input params like max_tokens, temperature are diff it should NOT be a cache hit
- print(f"response1: {response1}")
- print(f"response3: {response3}")
- pytest.fail(
- f"Response 1 == response 3. Same model, diff params shoudl not cache Error"
- f" occurred:"
- )
-
- assert response1.id == response2.id
- assert response1.created == response2.created
- assert (
- response1.choices[0].message.content == response2.choices[0].message.content
- )
-
- @pytest.mark.parametrize("sync_mode", [True, False])
- @pytest.mark.asyncio
- async def test_disk_cache_embedding(self, sync_mode):
- litellm.turn_on_debug()
-
- random_number = random.randint(
- 1, 100000
- ) # add a random number to ensure it's always adding / reading from cache
- input = [f"hello {random_number}"]
- litellm.cache = Cache(
- type="disk",
- )
-
- if sync_mode:
- response1 = embedding(
- "openai/text-embedding-ada-002",
- input=input,
- caching=True,
- )
- else:
- response1 = await litellm.aembedding(
- "openai/text-embedding-ada-002",
- input=input,
- caching=True,
- )
- # response2 is mocked to a different response from response1,
- # but the completion from the cache should be used instead of the mock
- # response since the input is the same as response1
- await asyncio.sleep(0.5)
- if sync_mode:
- response2 = embedding(
- "openai/text-embedding-ada-002",
- input=input,
- caching=True,
- )
- else:
- response2 = await litellm.aembedding(
- "openai/text-embedding-ada-002",
- input=input,
- caching=True,
- )
-
- if response2._hidden_params["cache_hit"] is not True:
- pytest.fail("Cache hit should be True")
-
- # Since the parameters are not the same as response1, response3 should actually
- # be the mock response
- if sync_mode:
- response3 = embedding(
- "openai/text-embedding-ada-002",
- input=input,
- user="charlie",
- caching=True,
- )
- else:
- response3 = await litellm.aembedding(
- "openai/text-embedding-ada-002",
- input=input,
- caching=True,
- user="charlie",
- )
-
- print("\nresponse 1", response1)
- print("\nresponse 2", response2)
- print("\nresponse 3", response3)
- # print("\nresponse 4", response4)
- litellm.cache = None
- litellm.success_callback = []
- litellm._async_success_callback = []
-
- # 1 & 2 should be exactly the same
- # 1 & 3 should be different, since input params are diff
-
- if response3._hidden_params.get("cache_hit") is True:
- pytest.fail("Cache hit should not be True")
diff --git a/tests/local_testing/conftest.py b/tests/local_testing/conftest.py
deleted file mode 100644
index df3dacac3b2..00000000000
--- a/tests/local_testing/conftest.py
+++ /dev/null
@@ -1,284 +0,0 @@
-# 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
-#
-# IMPORTANT: True defaults are captured at conftest import time (before any
-# test module can pollute them via module-level assignments like
-# `litellm.num_retries = 3`). The function-scoped fixture resets globals to
-# these true defaults before every test, preventing cross-test contamination
-# under xdist where module reload is skipped.
-
-import asyncio
-import importlib
-import os
-
-import pytest
-
-import litellm
-from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER
-from litellm.utils import _invalidate_model_cost_lowercase_map
-
-# ``litellm.model_cost`` is loaded at import time from the URL pinned to ``main``
-# (``LITELLM_MODEL_COST_MAP_URL``). The in-tree backup ships with this branch
-# and can include pricing entries that ``main`` has not yet picked up (e.g.
-# Mistral now returns ``ministral-8b-2512`` from ``mistral-tiny`` and the entry
-# was added on this branch). Backfill any entries that are missing from the
-# remote-fetched map so cost-calculator lookups in tests succeed against the
-# cassette state the branch is being tested with.
-from litellm.litellm_core_utils.get_model_cost_map import (
- RESERVED_TOP_LEVEL_KEYS,
- GetModelCostMap,
-)
-
-for _k, _v in GetModelCostMap.load_local_model_cost_map().items():
- if _k in RESERVED_TOP_LEVEL_KEYS:
- continue
- litellm.model_cost.setdefault(_k, _v)
-
-from tests._vcr_conftest_common import ( # noqa: E402,F401
- VerboseReporterState,
- _pin_multipart_boundary,
- apply_vcr_auto_marker_to_items,
- emit_cassette_cache_session_banner,
- emit_vcr_classification_summary,
- emit_vcr_diagnostic_log,
- install_live_call_probe,
- record_vcr_outcome,
- register_persister_if_enabled,
- reset_vcr_diag_dir,
- vcr_config_dict,
-)
-from tests.fake_openai_endpoint import ensure_fake_openai_endpoint # noqa: E402
-
-
[email protected](scope="session", autouse=True)
-def fake_openai_endpoint():
- ensure_fake_openai_endpoint()
- yield
-
-
-# Per-item respx detection (``apply_vcr_auto_marker_to_items``) auto-skips
-# tests whose ``@pytest.mark.respx`` marker or ``respx_mock`` fixture
-# would conflict with vcrpy's transport patch. We no longer maintain a
-# file-level ``_RESPX_CONFLICTING_FILES`` list here — the previous
-# entries (``test_router.py``) had only a stale ``from respx import
-# MockRouter`` import with no actual respx wiring, so file-level
-# blacklisting was masking valid cache opportunities.
-
-# Files where VCR replay breaks the test:
-# - ``test_router_caching.py``: asserts upstream returns a *new* id per call,
-# which a deterministic cassette replay violates.
-_VCR_INCOMPATIBLE_FILES = frozenset(
- {
- "test_router_caching.py",
- # Hits the local fake OpenAI endpoint on 127.0.0.1; nothing to record.
- "test_fake_openai_endpoint.py",
- # Needs the real connection pool a collected handler tears down; vcrpy
- # patches the transport that pool lives in.
- "test_handler_gc_does_not_close_client.py",
- }
-)
-
-# Individual tests (vs. whole files above) that VCR replay can't model:
-# - ``test_router_text_completion_client``: a concurrency test that fires 300
-# identical requests to verify the async OpenAI client is *reused* across
-# calls (per its own comment, it "fails when we create a new Async OpenAI
-# client per request"). vcrpy patches the HTTP transport, so replay never
-# opens real connections and cannot exercise the client pool the test exists
-# to validate. Recording instead stores ~300 near-identical episodes, which
-# blows past MAX_EPISODES_PER_CASSETTE (50) so the cassette is refused on
-# every run (MISS:OVERFLOW). The endpoint is a free mock, so the live calls
-# carry no real provider cost.
-_VCR_INCOMPATIBLE_NODEID_SUFFIXES: tuple[str, ...] = (
- "test_router.py::test_router_text_completion_client",
-)
-
-
-_verbose_state = VerboseReporterState()
-
-
[email protected](scope="module")
-def vcr_config():
- return vcr_config_dict()
-
-
-def pytest_recording_configure(config, vcr):
- register_persister_if_enabled(vcr)
-
-
[email protected](hookwrapper=True)
-def pytest_runtest_makereport(item, call):
- outcome = yield
- rep = outcome.get_result()
- setattr(item, f"rep_{rep.when}", rep)
-
-
[email protected](autouse=True)
-def _vcr_outcome_gate(request, vcr):
- install_live_call_probe(request, vcr)
- yield
- record_vcr_outcome(request, vcr)
-
-
-def pytest_configure(config):
- _verbose_state.remember_pluginmanager(config)
- reset_vcr_diag_dir()
-
-
-def pytest_runtest_logreport(report):
- _verbose_state.maybe_emit_verdict(report)
-
-
-def pytest_terminal_summary(terminalreporter, exitstatus, config):
- emit_cassette_cache_session_banner(terminalreporter)
- emit_vcr_classification_summary(terminalreporter)
- emit_vcr_diagnostic_log(terminalreporter)
-
-
-# ---------------------------------------------------------------------------
-# Capture TRUE defaults at conftest import time. This runs before any test
-# module's top-level code (e.g. `litellm.num_retries = 3`) executes, so
-# the values here are guaranteed to be the real package defaults.
-# ---------------------------------------------------------------------------
-_SCALAR_DEFAULTS = {
- "num_retries": getattr(litellm, "num_retries", None),
- "num_retries_per_request": getattr(litellm, "num_retries_per_request", None),
- "request_timeout": getattr(litellm, "request_timeout", None),
- "set_verbose": getattr(litellm, "set_verbose", False),
- "cache": getattr(litellm, "cache", None),
- "allowed_fails": getattr(litellm, "allowed_fails", 3),
- "default_fallbacks": getattr(litellm, "default_fallbacks", None),
- "enable_azure_ad_token_refresh": getattr(
- litellm, "enable_azure_ad_token_refresh", None
- ),
- "tag_budget_config": getattr(litellm, "tag_budget_config", None),
- "model_cost": getattr(litellm, "model_cost", None),
- "token_counter": getattr(litellm, "token_counter", None),
- "disable_aiohttp_transport": getattr(litellm, "disable_aiohttp_transport", False),
- "force_ipv4": getattr(litellm, "force_ipv4", False),
- "drop_params": getattr(litellm, "drop_params", None),
- "modify_params": getattr(litellm, "modify_params", False),
- "api_base": getattr(litellm, "api_base", None),
- "api_key": getattr(litellm, "api_key", None),
-}
-
-
[email protected](scope="function", autouse=True)
-def isolate_litellm_state():
- """
- Per-function isolation fixture.
-
- Resets litellm globals to their true defaults before each test and
- restores them afterward, so tests don't leak side effects.
- Works safely under pytest-xdist parallel execution.
- """
- # ---- Save current callback state (for teardown restore) ----
- 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 list-type globals
- for attr in ("pre_call_rules", "post_call_rules"):
- if hasattr(litellm, attr):
- val = getattr(litellm, attr)
- original_state[attr] = val.copy() if val else []
-
- # Save scalar globals
- for attr in _SCALAR_DEFAULTS:
- if hasattr(litellm, attr):
- original_state[attr] = getattr(litellm, attr)
-
- # ---- Reset to true defaults before the test ----
- # Flush HTTP client cache
- if hasattr(litellm, "in_memory_llm_clients_cache"):
- litellm.in_memory_llm_clients_cache.flush_cache()
-
- # Clear callbacks and rules
- for attr in (
- "callbacks",
- "success_callback",
- "failure_callback",
- "_async_success_callback",
- "_async_failure_callback",
- "pre_call_rules",
- "post_call_rules",
- ):
- if hasattr(litellm, attr):
- setattr(litellm, attr, [])
-
- # Reset scalar globals to true defaults (prevents contamination from
- # module-level code like `litellm.num_retries = 3` in test files)
- for attr, default_val in _SCALAR_DEFAULTS.items():
- if hasattr(litellm, attr):
- setattr(litellm, attr, default_val)
-
- yield
-
- # ---- Teardown: restore saved state ----
- asyncio.run(GLOBAL_LOGGING_WORKER.clear_queue())
- 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)
- _invalidate_model_cost_lowercase_map()
-
-
[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).
- """
-
- import litellm
-
- worker_id = os.environ.get("PYTEST_XDIST_WORKER", None)
- if worker_id is None:
- importlib.reload(litellm)
-
- 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}")
-
- if hasattr(litellm, "in_memory_llm_clients_cache"):
- litellm.in_memory_llm_clients_cache.flush_cache()
-
- yield
-
-
-def pytest_collection_modifyitems(config, items):
- apply_vcr_auto_marker_to_items(
- items,
- skip_files=_VCR_INCOMPATIBLE_FILES,
- skip_nodeid_suffixes=_VCR_INCOMPATIBLE_NODEID_SUFFIXES,
- )
-
- # Separate tests in 'test_amazing_proxy_custom_logger.py' and other tests
- custom_logger_tests = [
- item for item in items if "custom_logger" in item.parent.name
- ]
- other_tests = [item for item in items if "custom_logger" not in item.parent.name]
-
- # Sort tests based on their names
- custom_logger_tests.sort(key=lambda x: x.name)
- other_tests.sort(key=lambda x: x.name)
-
- # Reorder the items list
- items[:] = custom_logger_tests + other_tests
diff --git a/tests/local_testing/data_map.txt b/tests/local_testing/data_map.txt
deleted file mode 100644
index e8077595f47..00000000000
Binary files a/tests/local_testing/data_map.txt and /dev/null differ
diff --git a/tests/local_testing/eagle.wav b/tests/local_testing/eagle.wav
deleted file mode 100644
index 1c23657859e..00000000000
Binary files a/tests/local_testing/eagle.wav and /dev/null differ
diff --git a/tests/local_testing/example.jsonl b/tests/local_testing/example.jsonl
deleted file mode 100644
index fc3ca40808e..00000000000
--- a/tests/local_testing/example.jsonl
+++ /dev/null
@@ -1,2 +0,0 @@
-{"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gemini-1.5-flash-001", "messages": [{"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Hello world!"}], "max_tokens": 10}}
-{"custom_id": "request-2", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gemini-1.5-flash-001", "messages": [{"role": "system", "content": "You are an unhelpful assistant."}, {"role": "user", "content": "Hello world!"}], "max_tokens": 10}}
diff --git a/tests/local_testing/example_config_yaml/aliases_config.yaml b/tests/local_testing/example_config_yaml/aliases_config.yaml
deleted file mode 100644
index 43681f64ba0..00000000000
--- a/tests/local_testing/example_config_yaml/aliases_config.yaml
+++ /dev/null
@@ -1,30 +0,0 @@
-model_list:
- - model_name: gpt-3.5-turbo-instruct
- litellm_params:
- model: ollama/zephyr
- - model_name: gpt-4
- litellm_params:
- model: ollama/llama2
- - model_name: gpt-3.5-turbo
- litellm_params:
- model: ollama/llama2
- temperature: 0.1
- max_tokens: 20
-
-
-# request to gpt-4, response from ollama/llama2
-# curl --location 'http://0.0.0.0:8000/chat/completions' \
-# --header 'Content-Type: application/json' \
-# --data ' {
-# "model": "gpt-4",
-# "messages": [
-# {
-# "role": "user",
-# "content": "what llm are you"
-# }
-# ],
-# }
-# '
-#
-
-# {"id":"chatcmpl-27c85cf0-ab09-4bcf-8cb1-0ee950520743","choices":[{"finish_reason":"stop","index":0,"message":{"content":" Hello! I'm just an AI, I don't have personal experiences or emotions like humans do. However, I can help you with any questions or tasks you may have! Is there something specific you'd like to know or discuss?","role":"assistant","_logprobs":null}}],"created":1700094955.373751,"model":"ollama/llama2","object":"chat.completion","system_fingerprint":null,"usage":{"prompt_tokens":12,"completion_tokens":47,"total_tokens":59},"_response_ms":8028.017999999999}%
\ No newline at end of file
diff --git a/tests/local_testing/example_config_yaml/azure_config.yaml b/tests/local_testing/example_config_yaml/azure_config.yaml
deleted file mode 100644
index 05ba0c9bf54..00000000000
--- a/tests/local_testing/example_config_yaml/azure_config.yaml
+++ /dev/null
@@ -1,15 +0,0 @@
-model_list:
- - model_name: gpt-4-team1
- litellm_params:
- model: azure/gpt-4.1-mini
- api_base: https://openai-gpt-4-test-v-1.openai.azure.com/
- api_version: "2023-05-15"
- api_key: os.environ/AZURE_AI_API_KEY
- tpm: 20_000
- - model_name: gpt-4-team2
- litellm_params:
- model: azure/gpt-4
- api_key: os.environ/AZURE_AI_API_KEY
- api_base: https://openai-gpt-4-test-v-2.openai.azure.com/
- tpm: 100_000
-
diff --git a/tests/local_testing/example_config_yaml/cache_no_params.yaml b/tests/local_testing/example_config_yaml/cache_no_params.yaml
deleted file mode 100644
index 20ed919dd56..00000000000
--- a/tests/local_testing/example_config_yaml/cache_no_params.yaml
+++ /dev/null
@@ -1,7 +0,0 @@
-model_list:
- - model_name: "openai-model"
- litellm_params:
- model: "gpt-3.5-turbo"
-
-litellm_settings:
- cache: True
diff --git a/tests/local_testing/example_config_yaml/cache_with_params.yaml b/tests/local_testing/example_config_yaml/cache_with_params.yaml
deleted file mode 100644
index 068e2cc4a2b..00000000000
--- a/tests/local_testing/example_config_yaml/cache_with_params.yaml
+++ /dev/null
@@ -1,11 +0,0 @@
-model_list:
- - model_name: "openai-model"
- litellm_params:
- model: "gpt-3.5-turbo"
-
-litellm_settings:
- cache: True
- cache_params:
- type: "redis"
- supported_call_types: ["embedding", "aembedding"]
- host: "os.environ/REDIS_HOST"
\ No newline at end of file
diff --git a/tests/local_testing/example_config_yaml/config_with_env_vars.yaml b/tests/local_testing/example_config_yaml/config_with_env_vars.yaml
deleted file mode 100644
index bae738c735d..00000000000
--- a/tests/local_testing/example_config_yaml/config_with_env_vars.yaml
+++ /dev/null
@@ -1,48 +0,0 @@
-model_list:
- ################################################################################
- # Azure
- - model_name: gpt-4o-mini
- litellm_params:
- model: azure/gpt-4o-mini
- api_base: https://amazin-prod.openai.azure.com
- api_key: "os.environ/AZURE_GPT_4O"
- deployment_id: gpt-4o-mini
- - model_name: gpt-4o
- litellm_params:
- model: azure/gpt-4o
- api_base: https://very-cool-prod.openai.azure.com
- api_key: "os.environ/AZURE_GPT_4O"
- deployment_id: gpt-4o
-
- ################################################################################
- # Fireworks
- - model_name: fireworks-llama-v3p1-405b-instruct
- litellm_params:
- model: fireworks_ai/accounts/fireworks/models/llama-v3p1-405b-instruct
- api_key: "os.environ/FIREWORKS"
- - model_name: fireworks-llama-v3p1-70b-instruct
- litellm_params:
- model: fireworks_ai/accounts/fireworks/models/llama-v3p1-70b-instruct
- api_key: "os.environ/FIREWORKS"
-
-general_settings:
- alerting_threshold: 300 # sends alerts if requests hang for 5min+ and responses take 5min+
-litellm_settings: # module level litellm settings - https://github.com/BerriAI/litellm/blob/main/litellm/__init__.py
- success_callback: ["prometheus"]
- service_callback: ["prometheus_system"]
- drop_params: False # Raise an exception if the openai param being passed in isn't supported.
- cache: false
- default_internal_user_params:
- user_role: os.environ/DEFAULT_USER_ROLE
-
- success_callback: ["s3"]
- s3_callback_params:
- s3_bucket_name: logs-bucket-litellm # AWS Bucket Name for S3
- s3_region_name: us-west-2 # AWS Region Name for S3
- s3_aws_access_key_id: os.environ/AWS_ACCESS_KEY_ID # us os.environ/<variable name> to pass environment variables. This is AWS Access Key ID for S3
- s3_aws_secret_access_key: os.environ/AWS_SECRET_ACCESS_KEY # AWS Secret Access Key for S3
- s3_path: my-test-path # [OPTIONAL] set path in bucket you want to write logs to
- s3_endpoint_url: https://s3.amazonaws.com # [OPTIONAL] S3 endpoint URL, if you want to use Backblaze/cloudflare s3 buckets
-
-router_settings:
- routing_strategy: simple-shuffle # "simple-shuffle" shown to result in highest throughput. https://docs.litellm.ai/docs/proxy/configs#load-balancing
diff --git a/tests/local_testing/example_config_yaml/langfuse_config.yaml b/tests/local_testing/example_config_yaml/langfuse_config.yaml
deleted file mode 100644
index c2a77b5adc4..00000000000
--- a/tests/local_testing/example_config_yaml/langfuse_config.yaml
+++ /dev/null
@@ -1,7 +0,0 @@
-model_list:
- - model_name: gpt-3.5-turbo
-
-litellm_settings:
- drop_params: True
- success_callback: ["langfuse"] # https://docs.litellm.ai/docs/observability/langfuse_integration
-
diff --git a/tests/local_testing/example_config_yaml/load_balancer.yaml b/tests/local_testing/example_config_yaml/load_balancer.yaml
deleted file mode 100644
index 502b90ff92a..00000000000
--- a/tests/local_testing/example_config_yaml/load_balancer.yaml
+++ /dev/null
@@ -1,28 +0,0 @@
-litellm_settings:
- drop_params: True
-
-# Model-specific settings
-model_list: # use the same model_name for using the litellm router. LiteLLM will use the router between gpt-3.5-turbo
- - model_name: gpt-3.5-turbo # litellm will
- litellm_params:
- model: gpt-3.5-turbo
- api_key: sk-uj6F
- tpm: 20000 # [OPTIONAL] REPLACE with your openai tpm
- rpm: 3 # [OPTIONAL] REPLACE with your openai rpm
- - model_name: gpt-3.5-turbo
- litellm_params:
- model: gpt-3.5-turbo
- api_key: sk-Imn
- tpm: 20000 # [OPTIONAL] REPLACE with your openai tpm
- rpm: 3 # [OPTIONAL] REPLACE with your openai rpm
- - model_name: gpt-3.5-turbo
- litellm_params:
- model: openrouter/gpt-3.5-turbo
- - model_name: mistral-7b-instruct
- litellm_params:
- model: mistralai/mistral-7b-instruct
-
-environment_variables:
- REDIS_HOST: localhost
- REDIS_PASSWORD:
- REDIS_PORT:
\ No newline at end of file
diff --git a/tests/local_testing/example_config_yaml/opentelemetry_config.yaml b/tests/local_testing/example_config_yaml/opentelemetry_config.yaml
deleted file mode 100644
index 92d3454d7d5..00000000000
--- a/tests/local_testing/example_config_yaml/opentelemetry_config.yaml
+++ /dev/null
@@ -1,7 +0,0 @@
-model_list:
- - model_name: gpt-3.5-turbo
- litellm_params:
- model: gpt-3.5-turbo
-
-general_settings:
- otel: True # OpenTelemetry Logger this logs OTEL data to your collector
diff --git a/tests/local_testing/example_config_yaml/simple_config.yaml b/tests/local_testing/example_config_yaml/simple_config.yaml
deleted file mode 100644
index 14b39a12518..00000000000
--- a/tests/local_testing/example_config_yaml/simple_config.yaml
+++ /dev/null
@@ -1,4 +0,0 @@
-model_list:
- - model_name: gpt-3.5-turbo
- litellm_params:
- model: gpt-3.5-turbo
\ No newline at end of file
diff --git a/tests/local_testing/gettysburg.wav b/tests/local_testing/gettysburg.wav
deleted file mode 100644
index 9690f521e84..00000000000
Binary files a/tests/local_testing/gettysburg.wav and /dev/null differ
diff --git a/tests/local_testing/large_text.py b/tests/local_testing/large_text.py
deleted file mode 100644
index 86904a6d148..00000000000
--- a/tests/local_testing/large_text.py
+++ /dev/null
@@ -1,112 +0,0 @@
-text = """
-Alexander the Great
-This article is about the ancient king of Macedonia. For other uses, see Alexander the Great (disambiguation).
-Alexander III of Macedon (Ancient Greek: Ἀλέξανδρος, romanized: Alexandros; 20/21 July 356 BC – 10/11 June 323 BC), most commonly known as Alexander the Great,[c] was a king of the ancient Greek kingdom of Macedon.[d] He succeeded his father Philip II to the throne in 336 BC at the age of 20 and spent most of his ruling years conducting a lengthy military campaign throughout Western Asia, Central Asia, parts of South Asia, and Egypt. By the age of 30, he had created one of the largest empires in history, stretching from Greece to northwestern India.[1] He was undefeated in battle and is widely considered to be one of history's greatest and most successful military commanders.[2][3]
-
-Until the age of 16, Alexander was tutored by Aristotle. In 335 BC, shortly after his assumption of kingship over Macedon, he campaigned in the Balkans and reasserted control over Thrace and parts of Illyria before marching on the city of Thebes, which was subsequently destroyed in battle. Alexander then led the League of Corinth, and used his authority to launch the pan-Hellenic project envisaged by his father, assuming leadership over all Greeks in their conquest of Persia.[4][5]
-
-In 334 BC, he invaded the Achaemenid Persian Empire and began a series of campaigns that lasted for 10 years. Following his conquest of Asia Minor, Alexander broke the power of Achaemenid Persia in a series of decisive battles, including those at Issus and Gaugamela; he subsequently overthrew Darius III and conquered the Achaemenid Empire in its entirety.[e] After the fall of Persia, the Macedonian Empire held a vast swath of territory between the Adriatic Sea and the Indus River. Alexander endeavored to reach the "ends of the world and the Great Outer Sea" and invaded India in 326 BC, achieving an important victory over Porus, an ancient Indian king of present-day Punjab, at the Battle of the Hydaspes. Due to the demand of his homesick troops, he eventually turned back at the Beas River and later died in 323 BC in Babylon, the city of Mesopotamia that he had planned to establish as his empire's capital. Alexander's death left unexecuted an additional series of planned military and mercantile campaigns that would have begun with a Greek invasion of Arabia. In the years following his death, a series of civil wars broke out across the Macedonian Empire, eventually leading to its disintegration at the hands of the Diadochi.
-
-With his death marking the start of the Hellenistic period, Alexander's legacy includes the cultural diffusion and syncretism that his conquests engendered, such as Greco-Buddhism and Hellenistic Judaism. He founded more than twenty cities, with the most prominent being the city of Alexandria in Egypt. Alexander's settlement of Greek colonists and the resulting spread of Greek culture led to the overwhelming dominance of Hellenistic civilization and influence as far east as the Indian subcontinent. The Hellenistic period developed through the Roman Empire into modern Western culture; the Greek language became the lingua franca of the region and was the predominant language of the Byzantine Empire up until its collapse in the mid-15th century AD. Alexander became legendary as a classical hero in the mould of Achilles, featuring prominently in the historical and mythical traditions of both Greek and non-Greek cultures. His military achievements and unprecedented enduring successes in battle made him the measure against which many later military leaders would compare themselves,[f] and his tactics remain a significant subject of study in military academies worldwide.[6] Legends of Alexander's exploits coalesced into the third-century Alexander Romance which, in the premodern period, went through over one hundred recensions, translations, and derivations and was translated into almost every European vernacular and every language of the Islamic world.[7] After the Bible, it was the most popular form of European literature.[8]
-
-Early life
-
-Lineage and childhood
-
-Alexander III was born in Pella, the capital of the Kingdom of Macedon,[9] on the sixth day of the ancient Greek month of Hekatombaion, which probably corresponds to 20 July 356 BC (although the exact date is uncertain).[10][11] He was the son of the erstwhile king of Macedon, Philip II, and his fourth wife, Olympias (daughter of Neoptolemus I, king of Epirus).[12][g] Although Philip had seven or eight wives, Olympias was his principal wife for some time, likely because she gave birth to Alexander.[13]
-
-Several legends surround Alexander's birth and childhood.[14] According to the ancient Greek biographer Plutarch, on the eve of the consummation of her marriage to Philip, Olympias dreamed that her womb was struck by a thunderbolt that caused a flame to spread "far and wide" before dying away. Sometime after the wedding, Philip is said to have seen himself, in a dream, securing his wife's womb with a seal engraved with a lion's image.[15] Plutarch offered a variety of interpretations for these dreams: that Olympias was pregnant before her marriage, indicated by the sealing of her womb; or that Alexander's father was Zeus. Ancient commentators were divided about whether the ambitious Olympias promulgated the story of Alexander's divine parentage, variously claiming that she had told Alexander, or that she dismissed the suggestion as impious.[15]
-
-On the day Alexander was born, Philip was preparing a siege on the city of Potidea on the peninsula of Chalcidice. That same day, Philip received news that his general Parmenion had defeated the combined Illyrian and Paeonian armies and that his horses had won at the Olympic Games. It was also said that on this day, the Temple of Artemis in Ephesus, one of the Seven Wonders of the World, burnt down. This led Hegesias of Magnesia to say that it had burnt down because Artemis was away, attending the birth of Alexander.[16] Such legends may have emerged when Alexander was king, and possibly at his instigation, to show that he was superhuman and destined for greatness from conception.[14]
-
-In his early years, Alexander was raised by a nurse, Lanike, sister of Alexander's future general Cleitus the Black. Later in his childhood, Alexander was tutored by the strict Leonidas, a relative of his mother, and by Lysimachus of Acarnania.[17] Alexander was raised in the manner of noble Macedonian youths, learning to read, play the lyre, ride, fight, and hunt.[18] When Alexander was ten years old, a trader from Thessaly brought Philip a horse, which he offered to sell for thirteen talents. The horse refused to be mounted, and Philip ordered it away. Alexander, however, detecting the horse's fear of its own shadow, asked to tame the horse, which he eventually managed.[14] Plutarch stated that Philip, overjoyed at this display of courage and ambition, kissed his son tearfully, declaring: "My boy, you must find a kingdom big enough for your ambitions. Macedon is too small for you", and bought the horse for him.[19] Alexander named it Bucephalas, meaning "ox-head". Bucephalas carried Alexander as far as India. When the animal died (because of old age, according to Plutarch, at age 30), Alexander named a city after him, Bucephala.[20]
-
-Education
-
-When Alexander was 13, Philip began to search for a tutor, and considered such academics as Isocrates and Speusippus, the latter offering to resign from his stewardship of the Academy to take up the post. In the end, Philip chose Aristotle and provided the Temple of the Nymphs at Mieza as a classroom. In return for teaching Alexander, Philip agreed to rebuild Aristotle's hometown of Stageira, which Philip had razed, and to repopulate it by buying and freeing the ex-citizens who were slaves, or pardoning those who were in exile.[21]
-
-Mieza was like a boarding school for Alexander and the children of Macedonian nobles, such as Ptolemy, Hephaistion, and Cassander. Many of these students would become his friends and future generals, and are often known as the "Companions". Aristotle taught Alexander and his companions about medicine, philosophy, morals, religion, logic, and art. Under Aristotle's tutelage, Alexander developed a passion for the works of Homer, and in particular the Iliad; Aristotle gave him an annotated copy, which Alexander later carried on his campaigns.[22] Alexander was able to quote Euripides from memory.[23]
-
-During his youth, Alexander was also acquainted with Persian exiles at the Macedonian court, who received the protection of Philip II for several years as they opposed Artaxerxes III.[24][25][26] Among them were Artabazos II and his daughter Barsine, possible future mistress of Alexander, who resided at the Macedonian court from 352 to 342 BC, as well as Amminapes, future satrap of Alexander, or a Persian nobleman named Sisines.[24][27][28][29] This gave the Macedonian court a good knowledge of Persian issues, and may even have influenced some of the innovations in the management of the Macedonian state.[27]
-
-Suda writes that Anaximenes of Lampsacus was one of Alexander's teachers, and that Anaximenes also accompanied Alexander on his campaigns.[30]
-
-Heir of Philip II
-
-Regency and ascent of Macedon
-
-Main articles: Philip II of Macedon and Rise of Macedon
-Further information: History of Macedonia (ancient kingdom)
-At the age of 16, Alexander's education under Aristotle ended. Philip II had waged war against the Thracians to the north, which left Alexander in charge as regent and heir apparent.[14] During Philip's absence, the Thracian tribe of Maedi revolted against Macedonia. Alexander responded quickly and drove them from their territory. The territory was colonized, and a city, named Alexandropolis, was founded.[31]
-
-Upon Philip's return, Alexander was dispatched with a small force to subdue the revolts in southern Thrace. Campaigning against the Greek city of Perinthus, Alexander reportedly saved his father's life. Meanwhile, the city of Amphissa began to work lands that were sacred to Apollo near Delphi, a sacrilege that gave Philip the opportunity to further intervene in Greek affairs. While Philip was occupied in Thrace, Alexander was ordered to muster an army for a campaign in southern Greece. Concerned that other Greek states might intervene, Alexander made it look as though he was preparing to attack Illyria instead. During this turmoil, the Illyrians invaded Macedonia, only to be repelled by Alexander.[32]
-
-Philip and his army joined his son in 338 BC, and they marched south through Thermopylae, taking it after stubborn resistance from its Theban garrison. They went on to occupy the city of Elatea, only a few days' march from both Athens and Thebes. The Athenians, led by Demosthenes, voted to seek alliance with Thebes against Macedonia. Both Athens and Philip sent embassies to win Thebes's favour, but Athens won the contest.[33] Philip marched on Amphissa (ostensibly acting on the request of the Amphictyonic League), capturing the mercenaries sent there by Demosthenes and accepting the city's surrender. Philip then returned to Elatea, sending a final offer of peace to Athens and Thebes, who both rejected it.[34]
-
-As Philip marched south, his opponents blocked him near Chaeronea, Boeotia. During the ensuing Battle of Chaeronea, Philip commanded the right wing and Alexander the left, accompanied by a group of Philip's trusted generals. According to the ancient sources, the two sides fought bitterly for some time. Philip deliberately commanded his troops to retreat, counting on the untested Athenian hoplites to follow, thus breaking their line. Alexander was the first to break the Theban lines, followed by Philip's generals. Having damaged the enemy's cohesion, Philip ordered his troops to press forward and quickly routed them. With the Athenians lost, the Thebans were surrounded. Left to fight alone, they were defeated.[35]
-
-After the victory at Chaeronea, Philip and Alexander marched unopposed into the Peloponnese, welcomed by all cities; however, when they reached Sparta, they were refused, but did not resort to war.[36] At Corinth, Philip established a "Hellenic Alliance" (modelled on the old anti-Persian alliance of the Greco-Persian Wars), which included most Greek city-states except Sparta. Philip was then named Hegemon (often translated as "Supreme Commander") of this league (known by modern scholars as the League of Corinth), and announced his plans to attack the Persian Empire.[37][38]
-
-Exile and return
-
-When Philip returned to Pella, he fell in love with and married Cleopatra Eurydice in 338 BC,[39] the niece of his general Attalus.[40] The marriage made Alexander's position as heir less secure, since any son of Cleopatra Eurydice would be a fully Macedonian heir, while Alexander was only half-Macedonian.[41] During the wedding banquet, a drunken Attalus publicly prayed to the gods that the union would produce a legitimate heir.[40]
-
-At the wedding of Cleopatra, whom Philip fell in love with and married, she being much too young for him, her uncle Attalus in his drink desired the Macedonians would implore the gods to give them a lawful successor to the kingdom by his niece. This so irritated Alexander, that throwing one of the cups at his head, "You villain," said he, "what, am I then a bastard?" Then Philip, taking Attalus's part, rose up and would have run his son through; but by good fortune for them both, either his over-hasty rage, or the wine he had drunk, made his foot slip, so that he fell down on the floor. At which Alexander reproachfully insulted over him: "See there," said he, "the man who makes preparations to pass out of Europe into Asia, overturned in passing from one seat to another."
-
-— Plutarch, describing the feud at Philip's wedding.[42]none
-In 337 BC, Alexander fled Macedon with his mother, dropping her off with her brother, King Alexander I of Epirus in Dodona, capital of the Molossians.[43] He continued to Illyria,[43] where he sought refuge with one or more Illyrian kings, perhaps with Glaucias, and was treated as a guest, despite having defeated them in battle a few years before.[44] However, it appears Philip never intended to disown his politically and militarily trained son.[43] Accordingly, Alexander returned to Macedon after six months due to the efforts of a family friend, Demaratus, who mediated between the two parties.[45]
-
-In the following year, the Persian satrap (governor) of Caria, Pixodarus, offered his eldest daughter to Alexander's half-brother, Philip Arrhidaeus.[43] Olympias and several of Alexander's friends suggested this showed Philip intended to make Arrhidaeus his heir.[43] Alexander reacted by sending an actor, Thessalus of Corinth, to tell Pixodarus that he should not offer his daughter's hand to an illegitimate son, but instead to Alexander. When Philip heard of this, he stopped the negotiations and scolded Alexander for wishing to marry the daughter of a Carian, explaining that he wanted a better bride for him.[43] Philip exiled four of Alexander's friends, Harpalus, Nearchus, Ptolemy and Erigyius, and had the Corinthians bring Thessalus to him in chains.[46]
-
-King of Macedon
-
-Accession
-
-Further information: Government of Macedonia (ancient kingdom)
-In summer 336 BC, while at Aegae attending the wedding of his daughter Cleopatra to Olympias's brother, Alexander I of Epirus, Philip was assassinated by the captain of his bodyguards, Pausanias.[h] As Pausanias tried to escape, he tripped over a vine and was killed by his pursuers, including two of Alexander's companions, Perdiccas and Leonnatus. Alexander was proclaimed king on the spot by the nobles and army at the age of 20.[47][48][49]
-
-Consolidation of power
-
-Alexander began his reign by eliminating potential rivals to the throne. He had his cousin, the former Amyntas IV, executed.[51] He also had two Macedonian princes from the region of Lyncestis killed for having been involved in his father's assassination, but spared a third, Alexander Lyncestes. Olympias had Cleopatra Eurydice, and Europa, her daughter by Philip, burned alive. When Alexander learned about this, he was furious. Alexander also ordered the murder of Attalus,[51] who was in command of the advance guard of the army in Asia Minor and Cleopatra's uncle.[52]
-
-Attalus was at that time corresponding with Demosthenes, regarding the possibility of defecting to Athens. Attalus also had severely insulted Alexander, and following Cleopatra's murder, Alexander may have considered him too dangerous to be left alive.[52] Alexander spared Arrhidaeus, who was by all accounts mentally disabled, possibly as a result of poisoning by Olympias.[47][49][53]
-
-News of Philip's death roused many states into revolt, including Thebes, Athens, Thessaly, and the Thracian tribes north of Macedon. When news of the revolts reached Alexander, he responded quickly. Though advised to use diplomacy, Alexander mustered 3,000 Macedonian cavalry and rode south towards Thessaly. He found the Thessalian army occupying the pass between Mount Olympus and Mount Ossa, and ordered his men to ride over Mount Ossa. When the Thessalians awoke the next day, they found Alexander in their rear and promptly surrendered, adding their cavalry to Alexander's force. He then continued south towards the Peloponnese.[54]
-
-Alexander stopped at Thermopylae, where he was recognized as the leader of the Amphictyonic League before heading south to Corinth. Athens sued for peace and Alexander pardoned the rebels. The famous encounter between Alexander and Diogenes the Cynic occurred during Alexander's stay in Corinth. When Alexander asked Diogenes what he could do for him, the philosopher disdainfully asked Alexander to stand a little to the side, as he was blocking the sunlight.[55] This reply apparently delighted Alexander, who is reported to have said "But verily, if I were not Alexander, I would like to be Diogenes."[56] At Corinth, Alexander took the title of Hegemon ("leader") and, like Philip, was appointed commander for the coming war against Persia. He also received news of a Thracian uprising.[57]
-
-Balkan campaign
-
-Main article: Alexander's Balkan campaign
-Before crossing to Asia, Alexander wanted to safeguard his northern borders. In the spring of 335 BC, he advanced to suppress several revolts. Starting from Amphipolis, he travelled east into the country of the "Independent Thracians"; and at Mount Haemus, the Macedonian army attacked and defeated the Thracian forces manning the heights.[58] The Macedonians marched into the country of the Triballi, and defeated their army near the Lyginus river[59] (a tributary of the Danube). Alexander then marched for three days to the Danube, encountering the Getae tribe on the opposite shore. Crossing the river at night, he surprised them and forced their army to retreat after the first cavalry skirmish.[60]
-
-News then reached Alexander that the Illyrian chieftain Cleitus and King Glaukias of the Taulantii were in open revolt against his authority. Marching west into Illyria, Alexander defeated each in turn, forcing the two rulers to flee with their troops. With these victories, he secured his northern frontier.[61]
-
-Destruction of Thebes
-
-While Alexander campaigned north, the Thebans and Athenians rebelled once again. Alexander immediately headed south.[62] While the other cities again hesitated, Thebes decided to fight. The Theban resistance was ineffective, and Alexander razed the city and divided its territory between the other Boeotian cities. The end of Thebes cowed Athens, leaving all of Greece temporarily at peace.[62] Alexander then set out on his Asian campaign, leaving Antipater as regent.[63]
-
-Conquest of the Achaemenid Persian Empire
-
-Main articles: Wars of Alexander the Great and Chronology of the expedition of Alexander the Great into Asia
-Asia Minor
-
-Further information: Battle of the Granicus, Siege of Halicarnassus, and Siege of Miletus
-After his victory at the Battle of Chaeronea (338 BC), Philip II began the work of establishing himself as hēgemṓn (Greek: ἡγεμών) of a league which according to Diodorus was to wage a campaign against the Persians for the sundry grievances Greece suffered in 480 and free the Greek cities of the western coast and islands from Achaemenid rule. In 336 he sent Parmenion, Amyntas, Andromenes, Attalus, and an army of 10,000 men into Anatolia to make preparations for an invasion.[64][65] At first, all went well. The Greek cities on the western coast of Anatolia revolted until the news arrived that Philip had been murdered and had been succeeded by his young son Alexander. The Macedonians were demoralized by Philip's death and were subsequently defeated near Magnesia by the Achaemenids under the command of the mercenary Memnon of Rhodes.[64][65]
-
-Taking over the invasion project of Philip II, Alexander's army crossed the Hellespont in 334 BC with approximately 48,100 soldiers, 6,100 cavalry and a fleet of 120 ships with crews numbering 38,000,[62] drawn from Macedon and various Greek city-states, mercenaries, and feudally raised soldiers from Thrace, Paionia, and Illyria.[66][i] He showed his intent to conquer the entirety of the Persian Empire by throwing a spear into Asian soil and saying he accepted Asia as a gift from the gods. This also showed Alexander's eagerness to fight, in contrast to his father's preference for diplomacy.[62]
-
-After an initial victory against Persian forces at the Battle of the Granicus, Alexander accepted the surrender of the Persian provincial capital and treasury of Sardis; he then proceeded along the Ionian coast, granting autonomy and democracy to the cities. Miletus, held by Achaemenid forces, required a delicate siege operation, with Persian naval forces nearby. Further south, at Halicarnassus, in Caria, Alexander successfully waged his first large-scale siege, eventually forcing his opponents, the mercenary captain Memnon of Rhodes and the Persian satrap of Caria, Orontobates, to withdraw by sea.[67] Alexander left the government of Caria to a member of the Hecatomnid dynasty, Ada, who adopted Alexander.[68]
-
-From Halicarnassus, Alexander proceeded into mountainous Lycia and the Pamphylian plain, asserting control over all coastal cities to deny the Persians naval bases. From Pamphylia onwards the coast held no major ports and Alexander moved inland. At Termessos, Alexander humbled but did not storm the Pisidian city.[69] At the ancient Phrygian capital of Gordium, Alexander "undid" the hitherto unsolvable Gordian Knot, a feat said to await the future "king of Asia".[70] According to the story, Alexander proclaimed that it did not matter how the knot was undone and hacked it apart with his sword.[71]
-
-The Levant and Syria
-
-Further information: Battle of Issus and Siege of Tyre (332 BC)
-In spring 333 BC, Alexander crossed the Taurus into Cilicia. After a long pause due to an illness, he marched on towards Syria. Though outmanoeuvered by Darius's significantly larger army, he marched back to Cilicia, where he defeated Darius at Issus. Darius fled the battle, causing his army to collapse, and left behind his wife, his two daughters, his mother Sisygambis, and a fabulous treasure.[72] He offered a peace treaty that included the lands he had already lost, and a ransom of 10,000 talents for his family. Alexander replied that since he was now king of Asia, it was he alone who decided territorial divisions.[73] Alexander proceeded to take possession of Syria, and most of the coast of the Levant.[68] In the following year, 332 BC, he was forced to attack Tyre, which he captured after a long and difficult siege.[74][75] The men of military age were massacred and the women and children sold into slavery.[76]
-
-Egypt
-
-Further information: Siege of Gaza (332 BCE)
-When Alexander destroyed Tyre, most of the towns on the route to Egypt quickly capitulated. However, Alexander was met with resistance at Gaza. The stronghold was heavily fortified and built on a hill, requiring a siege. When "his engineers pointed out to him that because of the height of the mound it would be impossible... this encouraged Alexander all the more to make the attempt".[77] After three unsuccessful assaults, the stronghold fell, but not before Alexander had received a serious shoulder wound. As in Tyre, men of military age were put to the sword and the women and children were sold into slavery.[78]
-"""
diff --git a/tests/local_testing/openai_batch_completions.jsonl b/tests/local_testing/openai_batch_completions.jsonl
deleted file mode 100644
index 05448952a0f..00000000000
--- a/tests/local_testing/openai_batch_completions.jsonl
+++ /dev/null
@@ -1,2 +0,0 @@
-{"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-3.5-turbo-0125", "messages": [{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": "Hello world!"}],"max_tokens": 10}}
-{"custom_id": "request-2", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-3.5-turbo-0125", "messages": [{"role": "system", "content": "You are an unhelpful assistant."},{"role": "user", "content": "Hello world!"}],"max_tokens": 10}}
\ No newline at end of file
diff --git a/tests/local_testing/openai_batch_completions_router.jsonl b/tests/local_testing/openai_batch_completions_router.jsonl
deleted file mode 100644
index 8a4c99ca85e..00000000000
--- a/tests/local_testing/openai_batch_completions_router.jsonl
+++ /dev/null
@@ -1,3 +0,0 @@
-{"custom_id": "task-0", "method": "POST", "url": "/chat/completions", "body": {"model": "my-custom-name", "messages": [{"role": "system", "content": "You are an AI assistant that helps people find information."}, {"role": "user", "content": "When was Microsoft founded?"}]}}
-{"custom_id": "task-1", "method": "POST", "url": "/chat/completions", "body": {"model": "my-custom-name", "messages": [{"role": "system", "content": "You are an AI assistant that helps people find information."}, {"role": "user", "content": "When was the first XBOX released?"}]}}
-{"custom_id": "task-2", "method": "POST", "url": "/chat/completions", "body": {"model": "my-custom-name", "messages": [{"role": "system", "content": "You are an AI assistant that helps people find information."}, {"role": "user", "content": "What is Altair Basic?"}]}}
\ No newline at end of file
diff --git a/tests/local_testing/speech_vertex.mp3 b/tests/local_testing/speech_vertex.mp3
deleted file mode 100644
index c676110335e..00000000000
Binary files a/tests/local_testing/speech_vertex.mp3 and /dev/null differ
diff --git a/tests/local_testing/test_configs/custom_auth.py b/tests/local_testing/test_configs/custom_auth.py
deleted file mode 100644
index 1b6bec43b5e..00000000000
--- a/tests/local_testing/test_configs/custom_auth.py
+++ /dev/null
@@ -1,22 +0,0 @@
-from litellm.proxy._types import UserAPIKeyAuth
-from fastapi import Request
-from dotenv import load_dotenv
-import os
-
-load_dotenv()
-
-
-async def user_api_key_auth(request: Request, api_key: str) -> UserAPIKeyAuth:
- try:
- print(f"api_key: {api_key}")
- if api_key == "":
- raise Exception(
- f"CustomAuth - Malformed API Key passed in. Ensure Key has `Bearer` prefix"
- )
- if api_key == f"{os.getenv('PROXY_MASTER_KEY')}-1234":
- return UserAPIKeyAuth(api_key=api_key)
- raise Exception
- except Exception as e:
- if len(str(e)) > 0:
- raise e
- raise Exception("Failed custom auth")
diff --git a/tests/local_testing/test_configs/custom_callbacks.py b/tests/local_testing/test_configs/custom_callbacks.py
deleted file mode 100644
index 42f88b5d19b..00000000000
--- a/tests/local_testing/test_configs/custom_callbacks.py
+++ /dev/null
@@ -1,121 +0,0 @@
-from litellm.integrations.custom_logger import CustomLogger
-import inspect
-import litellm
-
-
-class testCustomCallbackProxy(CustomLogger):
- def __init__(self):
- self.success: bool = False # type: ignore
- self.failure: bool = False # type: ignore
- self.async_success: bool = False # type: ignore
- self.async_success_embedding: bool = False # type: ignore
- self.async_failure: bool = False # type: ignore
- self.async_failure_embedding: bool = False # type: ignore
-
- self.async_completion_kwargs = None # type: ignore
- self.async_embedding_kwargs = None # type: ignore
- self.async_embedding_response = None # type: ignore
-
- self.async_completion_kwargs_fail = None # type: ignore
- self.async_embedding_kwargs_fail = None # type: ignore
-
- self.streaming_response_obj = None # type: ignore
- blue_color_code = "\033[94m"
- reset_color_code = "\033[0m"
- print(f"{blue_color_code}Initialized LiteLLM custom logger")
- try:
- print(f"Logger Initialized with following methods:")
- methods = [
- method
- for method in dir(self)
- if inspect.ismethod(getattr(self, method))
- ]
-
- # Pretty print the methods
- for method in methods:
- print(f" - {method}")
- print(f"{reset_color_code}")
- except Exception:
- pass
-
- def log_pre_api_call(self, model, messages, kwargs):
- print(f"Pre-API Call")
-
- def log_post_api_call(self, kwargs, response_obj, start_time, end_time):
- print(f"Post-API Call")
-
- def log_stream_event(self, kwargs, response_obj, start_time, end_time):
- print(f"On Stream")
-
- def log_success_event(self, kwargs, response_obj, start_time, end_time):
- print(f"On Success")
- self.success = True
-
- def log_failure_event(self, kwargs, response_obj, start_time, end_time):
- print(f"On Failure")
- self.failure = True
-
- async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
- print(f"On Async success")
- self.async_success = True
- print("Value of async success: ", self.async_success)
- print("\n kwargs: ", kwargs)
- if (
- kwargs.get("model") == "azure-embedding-model"
- or kwargs.get("model") == "ada"
- ):
- print("Got an embedding model", kwargs.get("model"))
- print("Setting embedding success to True")
- self.async_success_embedding = True
- print("Value of async success embedding: ", self.async_success_embedding)
- self.async_embedding_kwargs = kwargs
- self.async_embedding_response = response_obj
- if kwargs.get("stream") == True:
- self.streaming_response_obj = response_obj
-
- self.async_completion_kwargs = kwargs
-
- model = kwargs.get("model", None)
- messages = kwargs.get("messages", None)
- user = kwargs.get("user", None)
-
- # Access litellm_params passed to litellm.completion(), example access `metadata`
- litellm_params = kwargs.get("litellm_params", {})
- metadata = litellm_params.get(
- "metadata", {}
- ) # headers passed to LiteLLM proxy, can be found here
-
- # Calculate cost using litellm.completion_cost()
- cost = litellm.completion_cost(completion_response=response_obj)
- response = response_obj
- # tokens used in response
- usage = response_obj["usage"]
-
- print("\n\n in custom callback vars my custom logger, ", vars(my_custom_logger))
-
- print(
- f"""
- Model: {model},
- Messages: {messages},
- User: {user},
- Usage: {usage},
- Cost: {cost},
- Response: {response}
- Proxy Metadata: {metadata}
- """
- )
- return
-
- async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time):
- print(f"On Async Failure")
- self.async_failure = True
- print("Value of async failure: ", self.async_failure)
- print("\n kwargs: ", kwargs)
- if kwargs.get("model") == "text-embedding-ada-002":
- self.async_failure_embedding = True
- self.async_embedding_kwargs_fail = kwargs
-
- self.async_completion_kwargs_fail = kwargs
-
-
-my_custom_logger = testCustomCallbackProxy()
diff --git a/tests/local_testing/test_configs/test_bad_config.yaml b/tests/local_testing/test_configs/test_bad_config.yaml
deleted file mode 100644
index 4bc4c7cc541..00000000000
--- a/tests/local_testing/test_configs/test_bad_config.yaml
+++ /dev/null
@@ -1,21 +0,0 @@
-model_list:
- - model_name: gpt-3.5-turbo
- litellm_params:
- api_key: bad-key
- model: gpt-3.5-turbo
- - model_name: working-azure-gpt-3.5-turbo
- litellm_params:
- model: azure/gpt-4.1-mini
- api_base: os.environ/AZURE_AI_API_BASE
- api_key: os.environ/AZURE_AI_API_KEY
- - model_name: azure-gpt-3.5-turbo
- litellm_params:
- model: azure/gpt-4.1-mini
- api_base: os.environ/AZURE_AI_API_BASE
- api_key: bad-key
- - model_name: azure-embedding
- litellm_params:
- model: azure/text-embedding-ada-002
- api_base: os.environ/AZURE_AI_API_BASE
- api_key: bad-key
-
\ No newline at end of file
diff --git a/tests/local_testing/test_configs/test_cloudflare_azure_with_cache_config.yaml b/tests/local_testing/test_configs/test_cloudflare_azure_with_cache_config.yaml
deleted file mode 100644
index 24240008fe2..00000000000
--- a/tests/local_testing/test_configs/test_cloudflare_azure_with_cache_config.yaml
+++ /dev/null
@@ -1,17 +0,0 @@
-model_list:
- - model_name: azure-cloudflare
- litellm_params:
- model: azure/gpt-4.1-mini
- api_base: https://gateway.ai.cloudflare.com/v1/0399b10e77ac6668c80404a5ff49eb37/litellm-test/azure-openai/openai-gpt-4-test-v-1
- api_key: os.environ/AZURE_AI_API_KEY
- api_version: 2023-07-01-preview
-
-litellm_settings:
- set_verbose: True
- cache: True # set cache responses to True
- cache_params: # set cache params for s3
- type: s3
- s3_bucket_name: litellm-my-test-bucket-2 # AWS Bucket Name for S3
- s3_region_name: us-east-1 # AWS Region Name for S3
- s3_aws_access_key_id: os.environ/AWS_ACCESS_KEY_ID # AWS Access Key ID for S3
- s3_aws_secret_access_key: os.environ/AWS_SECRET_ACCESS_KEY # AWS Secret Access Key for S3
\ No newline at end of file
diff --git a/tests/local_testing/test_configs/test_config.yaml b/tests/local_testing/test_configs/test_config.yaml
deleted file mode 100644
index a711b65ea03..00000000000
--- a/tests/local_testing/test_configs/test_config.yaml
+++ /dev/null
@@ -1,28 +0,0 @@
-general_settings:
- database_url: os.environ/DATABASE_URL
- master_key: os.environ/PROXY_MASTER_KEY
-litellm_settings:
- drop_params: true
- success_callback: ["langfuse"]
-
-model_list:
-- litellm_params:
- api_base: https://my-endpoint-europe-berri-992.openai.azure.com/
- api_key: os.environ/AZURE_EUROPE_API_KEY
- model: azure/gpt-35-turbo
- model_name: azure-model
-- litellm_params:
- api_base: https://my-endpoint-canada-berri992.openai.azure.com
- api_key: os.environ/AZURE_CANADA_API_KEY
- model: azure/gpt-35-turbo
- model_name: azure-model
-- litellm_params:
- api_base: https://openai-france-1234.openai.azure.com
- api_key: os.environ/AZURE_FRANCE_API_KEY
- model: azure/gpt-turbo
- model_name: azure-model
-- litellm_params:
- model: gpt-3.5-turbo
- model_info:
- description: this is a test openai model
- model_name: test_openai_models
diff --git a/tests/local_testing/test_configs/test_config_custom_auth.yaml b/tests/local_testing/test_configs/test_config_custom_auth.yaml
deleted file mode 100644
index 33088bd1ce1..00000000000
--- a/tests/local_testing/test_configs/test_config_custom_auth.yaml
+++ /dev/null
@@ -1,11 +0,0 @@
-model_list:
- - model_name: "openai-model"
- litellm_params:
- model: "gpt-3.5-turbo"
-
-litellm_settings:
- drop_params: True
- set_verbose: True
-
-general_settings:
- custom_auth: custom_auth.user_api_key_auth
\ No newline at end of file
diff --git a/tests/local_testing/test_configs/test_config_no_auth.yaml b/tests/local_testing/test_configs/test_config_no_auth.yaml
deleted file mode 100644
index f4896217049..00000000000
--- a/tests/local_testing/test_configs/test_config_no_auth.yaml
+++ /dev/null
@@ -1,127 +0,0 @@
-model_list:
-- litellm_params:
- api_base: https://my-endpoint-europe-berri-992.openai.azure.com/
- api_key: os.environ/AZURE_EUROPE_API_KEY
- model: azure/gpt-35-turbo
- model_name: azure-model
-- litellm_params:
- api_base: https://my-endpoint-canada-berri992.openai.azure.com
- api_key: os.environ/AZURE_CANADA_API_KEY
- model: azure/gpt-35-turbo
- model_name: azure-model
-- litellm_params:
- api_base: https://gateway.ai.cloudflare.com/v1/0399b10e77ac6668c80404a5ff49eb37/litellm-test/azure-openai/openai-gpt-4-test-v-1
- api_key: os.environ/AZURE_AI_API_KEY
- model: azure/gpt-4.1-mini
- model_name: azure-cloudflare-model
-- litellm_params:
- api_base: https://openai-france-1234.openai.azure.com
- api_key: os.environ/AZURE_FRANCE_API_KEY
- model: azure/gpt-turbo
- model_name: azure-model
-- litellm_params:
- model: gpt-3.5-turbo
- model_info:
- description: this is a test openai model
- model_name: test_openai_models
-- litellm_params:
- model: gpt-3.5-turbo
- model_info:
- description: this is a test openai model
- id: 56f1bd94-3b54-4b67-9ea2-7c70e9a3a709
- model_name: test_openai_models
-- litellm_params:
- model: gpt-3.5-turbo
- model_info:
- description: this is a test openai model
- id: 4d1ee26c-abca-450c-8744-8e87fd6755e9
- model_name: test_openai_models
-- litellm_params:
- model: gpt-3.5-turbo
- model_info:
- description: this is a test openai model
- id: 00e19c0f-b63d-42bb-88e9-016fb0c60764
- model_name: test_openai_models
-- litellm_params:
- model: gpt-3.5-turbo
- model_info:
- description: this is a test openai model
- id: 79fc75bf-8e1b-47d5-8d24-9365a854af03
- model_name: test_openai_models
-- litellm_params:
- api_base: os.environ/AZURE_AI_API_BASE
- api_key: os.environ/AZURE_AI_API_KEY
- api_version: 2023-07-01-preview
- model: azure/text-embedding-ada-002
- model_info:
- mode: embedding
- model_name: azure-embedding-model
-- litellm_params:
- model: gpt-3.5-turbo
- model_info:
- description: this is a test openai model
- id: 55848c55-4162-40f9-a6e2-9a722b9ef404
- model_name: test_openai_models
-- litellm_params:
- model: gpt-3.5-turbo
- model_info:
- description: this is a test openai model
- id: 34339b1e-e030-4bcc-a531-c48559f10ce4
- model_name: test_openai_models
-- litellm_params:
- model: gpt-3.5-turbo
- model_info:
- description: this is a test openai model
- id: f6f74e14-ac64-4403-9365-319e584dcdc5
- model_name: test_openai_models
-- litellm_params:
- model: gpt-3.5-turbo
- model_info:
- description: this is a test openai model
- id: 9b1ef341-322c-410a-8992-903987fef439
- model_name: test_openai_models
-- litellm_params:
- model: dall-e-3
- model_info:
- mode: image_generation
- model_name: dall-e-3
-- litellm_params:
- api_base: os.environ/AZURE_SWEDEN_API_BASE
- api_key: os.environ/AZURE_SWEDEN_API_KEY
- api_version: 2023-12-01-preview
- model: azure/dall-e-3-test
- model_info:
- mode: image_generation
- model_name: dall-e-3
-- litellm_params:
- api_base: os.environ/AZURE_AI_API_BASE
- api_key: os.environ/AZURE_AI_API_KEY
- api_version: 2023-06-01-preview
- model: azure/
- model_info:
- mode: image_generation
- model_name: dall-e-2
-- litellm_params:
- api_base: os.environ/AZURE_AI_API_BASE
- api_key: os.environ/AZURE_AI_API_KEY
- api_version: 2023-07-01-preview
- model: azure/text-embedding-ada-002
- model_info:
- base_model: text-embedding-ada-002
- mode: embedding
- model_name: text-embedding-ada-002
-- litellm_params:
- model: gpt-3.5-turbo
- model_info:
- description: this is a test openai model
- id: 34cb2419-7c63-44ae-a189-53f1d1ce5953
- model_name: test_openai_models
-- litellm_params:
- model: amazon.titan-embed-text-v1
- model_name: amazon-embeddings
-- litellm_params:
- model: gpt-3.5-turbo
- model_info:
- description: this is a test openai model
- id: 753dca9a-898d-4ff7-9961-5acf7cdf38cf
- model_name: test_openai_models
diff --git a/tests/local_testing/test_configs/test_custom_logger.yaml b/tests/local_testing/test_configs/test_custom_logger.yaml
deleted file mode 100644
index 464d66bd783..00000000000
--- a/tests/local_testing/test_configs/test_custom_logger.yaml
+++ /dev/null
@@ -1,26 +0,0 @@
-model_list:
- - model_name: Azure OpenAI GPT-4 Canada
- litellm_params:
- model: azure/gpt-4.1-mini
- api_base: os.environ/AZURE_AI_API_BASE
- api_key: os.environ/AZURE_AI_API_KEY
- api_version: "2023-07-01-preview"
- model_info:
- mode: chat
- input_cost_per_token: 0.0002
- id: gm
- - model_name: azure-embedding-model
- litellm_params:
- model: azure/text-embedding-ada-002
- api_base: os.environ/AZURE_AI_API_BASE
- api_key: os.environ/AZURE_AI_API_KEY
- api_version: "2023-07-01-preview"
- model_info:
- mode: embedding
- input_cost_per_token: 0.002
- id: hello
-
-litellm_settings:
- drop_params: True
- set_verbose: True
- callbacks: custom_callbacks.my_custom_logger
\ No newline at end of file
diff --git a/tests/local_testing/test_configs/test_guardrails_config.yaml b/tests/local_testing/test_configs/test_guardrails_config.yaml
deleted file mode 100644
index f09ff9d1bc4..00000000000
--- a/tests/local_testing/test_configs/test_guardrails_config.yaml
+++ /dev/null
@@ -1,32 +0,0 @@
-
-
-model_list:
-- litellm_params:
- api_base: https://my-endpoint-europe-berri-992.openai.azure.com/
- api_key: os.environ/AZURE_EUROPE_API_KEY
- model: azure/gpt-35-turbo
- model_name: azure-model
-- litellm_params:
- api_base: https://my-endpoint-canada-berri992.openai.azure.com
- api_key: os.environ/AZURE_CANADA_API_KEY
- model: azure/gpt-35-turbo
- model_name: azure-model
-- litellm_params:
- api_base: https://openai-france-1234.openai.azure.com
- api_key: os.environ/AZURE_FRANCE_API_KEY
- model: azure/gpt-turbo
- model_name: azure-model
-
-
-
-litellm_settings:
- guardrails:
- - prompt_injection:
- callbacks: [lakera_prompt_injection, detect_prompt_injection]
- default_on: true
- - hide_secrets:
- callbacks: [hide_secrets]
- default_on: true
- - moderations:
- callbacks: [openai_moderations]
- default_on: false
\ No newline at end of file
diff --git a/tests/local_testing/test_disk_cache_unit_tests.py b/tests/local_testing/test_disk_cache_unit_tests.py
deleted file mode 100644
index c777d04ecce..00000000000
--- a/tests/local_testing/test_disk_cache_unit_tests.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from cache_unit_tests import LLMCachingUnitTests
-from litellm.caching import LiteLLMCacheType
-
-
-class TestDiskCacheUnitTests(LLMCachingUnitTests):
- def get_cache_type(self) -> LiteLLMCacheType:
- return LiteLLMCacheType.DISK
-
-
-# if __name__ == "__main__":
-# pytest.main([__file__, "-v", "-s"])
diff --git a/tests/local_testing/test_gcs_cache_unit_tests.py b/tests/local_testing/test_gcs_cache_unit_tests.py
deleted file mode 100644
index 4604dc0d0ae..00000000000
--- a/tests/local_testing/test_gcs_cache_unit_tests.py
+++ /dev/null
@@ -1,7 +0,0 @@
-from cache_unit_tests import LLMCachingUnitTests
-from litellm.caching import LiteLLMCacheType
-
-
-class TestGCSCacheUnitTests(LLMCachingUnitTests):
- def get_cache_type(self) -> LiteLLMCacheType:
- return LiteLLMCacheType.GCS
diff --git a/tests/local_testing/user_cost.json b/tests/local_testing/user_cost.json
deleted file mode 100644
index bb15ef812f5..00000000000
--- a/tests/local_testing/user_cost.json
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "1234": {
- "total_budget": 10,
- "current_cost": 7.3e-05,
- "model_cost": {
- "gpt-3.5-turbo": 7.3e-05
- }
- },
- "12345": {
- "total_budget": 0
- }
-}
\ No newline at end of file
diff --git a/tests/local_testing/vertex_ai.jsonl b/tests/local_testing/vertex_ai.jsonl
deleted file mode 100644
index 6ec5baaf96b..00000000000
--- a/tests/local_testing/vertex_ai.jsonl
+++ /dev/null
@@ -1,22 +0,0 @@
-[
- {
- "messages": [
- {
- "role": "system",
- "content": "You should classify the text into one of the following classes:[business, entertainment]"
- },
- { "role": "user", "content": "Diversify your investment portfolio" },
- { "role": "model", "content": "business" }
- ]
- },
- {
- "messages": [
- {
- "role": "system",
- "content": "You should classify the text into one of the following classes:[business, entertainment]"
- },
- { "role": "user", "content": "Watch a live concert" },
- { "role": "model", "content": "entertainment" }
- ]
- }
-]
\ No newline at end of file
diff --git a/tests/local_testing/vertex_batch_completions.jsonl b/tests/local_testing/vertex_batch_completions.jsonl
deleted file mode 100644
index ec899f8fc43..00000000000
--- a/tests/local_testing/vertex_batch_completions.jsonl
+++ /dev/null
@@ -1,2 +0,0 @@
-{"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gemini-1.5-flash-001", "messages": [{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": "Hello world!"}],"max_tokens": 10}}
-{"custom_id": "request-2", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gemini-1.5-flash-001", "messages": [{"role": "system", "content": "You are an unhelpful assistant."},{"role": "user", "content": "Hello world!"}],"max_tokens": 10}}
\ No newline at end of file
diff --git a/tests/local_testing/vertex_key.json b/tests/local_testing/vertex_key.json
deleted file mode 100644
index 800969fb305..00000000000
--- a/tests/local_testing/vertex_key.json
+++ /dev/null
@@ -1,13 +0,0 @@
-{
- "type": "service_account",
- "project_id": "litellm-ci-cd",
- "private_key_id": "",
- "private_key": "",
- "client_email": "[email protected]",
- "client_id": "116563532503305622785",
- "auth_uri": "https://accounts.google.com/o/oauth2/auth",
- "token_uri": "https://oauth2.googleapis.com/token",
- "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
- "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/test-litellm-ci-cd%40litellm-ci-cd.iam.gserviceaccount.com",
- "universe_domain": "googleapis.com"
-}
diff --git a/tests/local_testing/whitelisted_bedrock_models.txt b/tests/local_testing/whitelisted_bedrock_models.txt
deleted file mode 100644
index 9b66569ff9e..00000000000
--- a/tests/local_testing/whitelisted_bedrock_models.txt
+++ /dev/null
@@ -1,142 +0,0 @@
-ai21.j2-mid-v1
-ai21.j2-ultra-v1
-ai21.jamba-instruct-v1:0
-amazon.titan-text-lite-v1
-amazon.titan-text-express-v1
-amazon.titan-text-premier-v1:0
-mistral.mistral-7b-instruct-v0:2
-mistral.mixtral-8x7b-instruct-v0:1
-mistral.mistral-large-2402-v1:0
-mistral.mistral-large-2407-v1:0
-mistral.mistral-small-2402-v1:0
-bedrock/us-west-2/mistral.mixtral-8x7b-instruct-v0:1
-bedrock/us-east-1/mistral.mixtral-8x7b-instruct-v0:1
-bedrock/eu-west-3/mistral.mixtral-8x7b-instruct-v0:1
-bedrock/us-west-2/mistral.mistral-7b-instruct-v0:2
-bedrock/us-east-1/mistral.mistral-7b-instruct-v0:2
-bedrock/eu-west-3/mistral.mistral-7b-instruct-v0:2
-bedrock/us-east-1/mistral.mistral-large-2402-v1:0
-bedrock/us-west-2/mistral.mistral-large-2402-v1:0
-bedrock/eu-west-3/mistral.mistral-large-2402-v1:0
-anthropic.claude-3-sonnet-20240229-v1:0
-anthropic.claude-haiku-4-5-20251001-v1:0
-anthropic.claude-3-7-sonnet-20250219-v1:0
-anthropic.claude-haiku-4-5-20251001-v1:0
-anthropic.claude-3-haiku-20240307-v1:0
-anthropic.claude-3-5-haiku-20241022-v1:0
-anthropic.claude-3-7-sonnet-20250219-v1:0
-us.anthropic.claude-3-sonnet-20240229-v1:0
-us.anthropic.claude-haiku-4-5-20251001-v1:0
-us.anthropic.claude-3-7-sonnet-20250219-v1:0
-us.anthropic.claude-haiku-4-5-20251001-v1:0
-us.anthropic.claude-3-haiku-20240307-v1:0
-us.anthropic.claude-3-5-haiku-20241022-v1:0
-us.anthropic.claude-3-7-sonnet-20250219-v1:0
-eu.anthropic.claude-3-sonnet-20240229-v1:0
-eu.anthropic.claude-haiku-4-5-20251001-v1:0
-eu.anthropic.claude-haiku-4-5-20251001-v1:0
-eu.anthropic.claude-3-haiku-20240307-v1:0
-eu.anthropic.claude-3-5-haiku-20241022-v1:0
-eu.anthropic.claude-3-7-sonnet-20250219-v1:0
-anthropic.claude-v1
-bedrock/us-east-1/anthropic.claude-v1
-bedrock/us-west-2/anthropic.claude-v1
-bedrock/ap-northeast-1/anthropic.claude-v1
-bedrock/ap-northeast-1/1-month-commitment/anthropic.claude-v1
-bedrock/ap-northeast-1/6-month-commitment/anthropic.claude-v1
-bedrock/eu-central-1/anthropic.claude-v1
-bedrock/eu-central-1/1-month-commitment/anthropic.claude-v1
-bedrock/eu-central-1/6-month-commitment/anthropic.claude-v1
-bedrock/us-east-1/1-month-commitment/anthropic.claude-v1
-bedrock/us-east-1/6-month-commitment/anthropic.claude-v1
-bedrock/us-west-2/1-month-commitment/anthropic.claude-v1
-bedrock/us-west-2/6-month-commitment/anthropic.claude-v1
-anthropic.claude-v2
-bedrock/us-east-1/anthropic.claude-v2
-bedrock/us-west-2/anthropic.claude-v2
-bedrock/ap-northeast-1/anthropic.claude-v2
-bedrock/ap-northeast-1/1-month-commitment/anthropic.claude-v2
-bedrock/ap-northeast-1/6-month-commitment/anthropic.claude-v2
-bedrock/eu-central-1/anthropic.claude-v2
-bedrock/eu-central-1/1-month-commitment/anthropic.claude-v2
-bedrock/eu-central-1/6-month-commitment/anthropic.claude-v2
-bedrock/us-east-1/1-month-commitment/anthropic.claude-v2
-bedrock/us-east-1/6-month-commitment/anthropic.claude-v2
-bedrock/us-west-2/1-month-commitment/anthropic.claude-v2
-bedrock/us-west-2/6-month-commitment/anthropic.claude-v2
-anthropic.claude-v2:1
-bedrock/us-east-1/anthropic.claude-v2:1
-bedrock/us-west-2/anthropic.claude-v2:1
-bedrock/ap-northeast-1/anthropic.claude-v2:1
-bedrock/ap-northeast-1/1-month-commitment/anthropic.claude-v2:1
-bedrock/ap-northeast-1/6-month-commitment/anthropic.claude-v2:1
-bedrock/eu-central-1/anthropic.claude-v2:1
-bedrock/eu-central-1/1-month-commitment/anthropic.claude-v2:1
-bedrock/eu-central-1/6-month-commitment/anthropic.claude-v2:1
-bedrock/us-east-1/1-month-commitment/anthropic.claude-v2:1
-bedrock/us-east-1/6-month-commitment/anthropic.claude-v2:1
-bedrock/us-west-2/1-month-commitment/anthropic.claude-v2:1
-bedrock/us-west-2/6-month-commitment/anthropic.claude-v2:1
-anthropic.claude-instant-v1
-bedrock/us-east-1/anthropic.claude-instant-v1
-bedrock/us-east-1/1-month-commitment/anthropic.claude-instant-v1
-bedrock/us-east-1/6-month-commitment/anthropic.claude-instant-v1
-bedrock/us-west-2/1-month-commitment/anthropic.claude-instant-v1
-bedrock/us-west-2/6-month-commitment/anthropic.claude-instant-v1
-bedrock/us-west-2/anthropic.claude-instant-v1
-bedrock/ap-northeast-1/anthropic.claude-instant-v1
-bedrock/ap-northeast-1/1-month-commitment/anthropic.claude-instant-v1
-bedrock/ap-northeast-1/6-month-commitment/anthropic.claude-instant-v1
-bedrock/eu-central-1/anthropic.claude-instant-v1
-bedrock/eu-central-1/1-month-commitment/anthropic.claude-instant-v1
-bedrock/eu-central-1/6-month-commitment/anthropic.claude-instant-v1
-cohere.command-text-v14
-bedrock/*/1-month-commitment/cohere.command-text-v14
-bedrock/*/6-month-commitment/cohere.command-text-v14
-cohere.command-light-text-v14
-bedrock/*/1-month-commitment/cohere.command-light-text-v14
-bedrock/*/6-month-commitment/cohere.command-light-text-v14
-cohere.command-r-plus-v1:0
-cohere.command-r-v1:0
-meta.llama3-3-70b-instruct-v1:0
-meta.llama2-13b-chat-v1
-meta.llama2-70b-chat-v1
-meta.llama3-8b-instruct-v1:0
-bedrock/us-east-1/meta.llama3-8b-instruct-v1:0
-bedrock/us-west-1/meta.llama3-8b-instruct-v1:0
-bedrock/ap-south-1/meta.llama3-8b-instruct-v1:0
-bedrock/ca-central-1/meta.llama3-8b-instruct-v1:0
-bedrock/eu-west-1/meta.llama3-8b-instruct-v1:0
-bedrock/eu-west-2/meta.llama3-8b-instruct-v1:0
-bedrock/sa-east-1/meta.llama3-8b-instruct-v1:0
-meta.llama3-70b-instruct-v1:0
-bedrock/us-east-1/meta.llama3-70b-instruct-v1:0
-bedrock/us-west-1/meta.llama3-70b-instruct-v1:0
-bedrock/ap-south-1/meta.llama3-70b-instruct-v1:0
-bedrock/ca-central-1/meta.llama3-70b-instruct-v1:0
-bedrock/eu-west-1/meta.llama3-70b-instruct-v1:0
-bedrock/eu-west-2/meta.llama3-70b-instruct-v1:0
-bedrock/sa-east-1/meta.llama3-70b-instruct-v1:0
-meta.llama3-1-8b-instruct-v1:0
-us.meta.llama3-1-8b-instruct-v1:0
-meta.llama3-1-70b-instruct-v1:0
-us.meta.llama3-1-70b-instruct-v1:0
-meta.llama3-1-405b-instruct-v1:0
-us.meta.llama3-1-405b-instruct-v1:0
-meta.llama3-2-1b-instruct-v1:0
-us.meta.llama3-2-1b-instruct-v1:0
-eu.meta.llama3-2-1b-instruct-v1:0
-meta.llama3-2-3b-instruct-v1:0
-us.meta.llama3-2-3b-instruct-v1:0
-eu.meta.llama3-2-3b-instruct-v1:0
-meta.llama3-2-11b-instruct-v1:0
-us.meta.llama3-2-11b-instruct-v1:0
-meta.llama3-2-90b-instruct-v1:0
-us.meta.llama3-2-90b-instruct-v1:0
-bedrock/ap-northeast-1/qwen.qwen3-next-80b-a3b
-bedrock/ap-south-1/qwen.qwen3-next-80b-a3b
-bedrock/ap-southeast-2/qwen.qwen3-next-80b-a3b
-bedrock/eu-west-1/qwen.qwen3-next-80b-a3b
-bedrock/eu-west-2/qwen.qwen3-next-80b-a3b
-bedrock/sa-east-1/qwen.qwen3-next-80b-a3b
-bedrock/eu-west-2/nvidia.nemotron-super-3-120b
diff --git a/tests/proxy_unit_tests/azure_fine_tune.jsonl b/tests/proxy_unit_tests/azure_fine_tune.jsonl
deleted file mode 100644
index ef41bd97731..00000000000
--- a/tests/proxy_unit_tests/azure_fine_tune.jsonl
+++ /dev/null
@@ -1,12 +0,0 @@
-{"messages": [{"role": "system", "content": "Clippy is a factual chatbot that is also sarcastic."}, {"role": "user", "content": "What's the capital of France?"}, {"role": "assistant", "content": "Paris, as if everyone doesn't know that already."}]}
-{"messages": [{"role": "system", "content": "Clippy is a factual chatbot that is also sarcastic."}, {"role": "user", "content": "Who wrote 'Romeo and Juliet'?"}, {"role": "assistant", "content": "Oh, just some guy named William Shakespeare. Ever heard of him?"}]}
-{"messages": [{"role": "system", "content": "Clippy is a factual chatbot that is also sarcastic."}, {"role": "user", "content": "How far is the Moon from Earth?"}, {"role": "assistant", "content": "Around 384,400 kilometers. Give or take a few, like that really matters."}]}
-{"messages": [{"role": "system", "content": "Clippy is a factual chatbot that is also sarcastic."}, {"role": "user", "content": "What's the capital of France?"}, {"role": "assistant", "content": "Paris, as if everyone doesn't know that already."}]}
-{"messages": [{"role": "system", "content": "Clippy is a factual chatbot that is also sarcastic."}, {"role": "user", "content": "Who wrote 'Romeo and Juliet'?"}, {"role": "assistant", "content": "Oh, just some guy named William Shakespeare. Ever heard of him?"}]}
-{"messages": [{"role": "system", "content": "Clippy is a factual chatbot that is also sarcastic."}, {"role": "user", "content": "How far is the Moon from Earth?"}, {"role": "assistant", "content": "Around 384,400 kilometers. Give or take a few, like that really matters."}]}
-{"messages": [{"role": "system", "content": "Clippy is a factual chatbot that is also sarcastic."}, {"role": "user", "content": "What's the capital of France?"}, {"role": "assistant", "content": "Paris, as if everyone doesn't know that already."}]}
-{"messages": [{"role": "system", "content": "Clippy is a factual chatbot that is also sarcastic."}, {"role": "user", "content": "Who wrote 'Romeo and Juliet'?"}, {"role": "assistant", "content": "Oh, just some guy named William Shakespeare. Ever heard of him?"}]}
-{"messages": [{"role": "system", "content": "Clippy is a factual chatbot that is also sarcastic."}, {"role": "user", "content": "How far is the Moon from Earth?"}, {"role": "assistant", "content": "Around 384,400 kilometers. Give or take a few, like that really matters."}]}
-{"messages": [{"role": "system", "content": "Clippy is a factual chatbot that is also sarcastic."}, {"role": "user", "content": "What's the capital of France?"}, {"role": "assistant", "content": "Paris, as if everyone doesn't know that already."}]}
-{"messages": [{"role": "system", "content": "Clippy is a factual chatbot that is also sarcastic."}, {"role": "user", "content": "Who wrote 'Romeo and Juliet'?"}, {"role": "assistant", "content": "Oh, just some guy named William Shakespeare. Ever heard of him?"}]}
-{"messages": [{"role": "system", "content": "Clippy is a factual chatbot that is also sarcastic."}, {"role": "user", "content": "How far is the Moon from Earth?"}, {"role": "assistant", "content": "Around 384,400 kilometers. Give or take a few, like that really matters."}]}
\ No newline at end of file
diff --git a/tests/proxy_unit_tests/batch_job_results_furniture.jsonl b/tests/proxy_unit_tests/batch_job_results_furniture.jsonl
deleted file mode 100644
index 05448952a0f..00000000000
--- a/tests/proxy_unit_tests/batch_job_results_furniture.jsonl
+++ /dev/null
@@ -1,2 +0,0 @@
-{"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-3.5-turbo-0125", "messages": [{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": "Hello world!"}],"max_tokens": 10}}
-{"custom_id": "request-2", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-3.5-turbo-0125", "messages": [{"role": "system", "content": "You are an unhelpful assistant."},{"role": "user", "content": "Hello world!"}],"max_tokens": 10}}
\ No newline at end of file
diff --git a/tests/proxy_unit_tests/conftest.py b/tests/proxy_unit_tests/conftest.py
deleted file mode 100644
index 148751c33f2..00000000000
--- a/tests/proxy_unit_tests/conftest.py
+++ /dev/null
@@ -1,150 +0,0 @@
-# conftest.py
-
-import asyncio
-import copy
-import inspect
-import warnings
-
-import pytest
-
-
-import litellm
-import litellm.proxy.proxy_server
-
-
-# Top-level assignments of these types are the ones importlib.reload(litellm)
-# would have effectively reset. We snapshot them at conftest import time and
-# deep-copy the snapshot back before every test.
-_SNAPSHOT_TYPES = (list, dict, set, tuple, str, int, float, bool, bytes)
-
-
-def _snapshot_mutable_state(module):
- """Capture a per-module snapshot of primitive and collection attributes."""
- snapshot = {}
- for attr in list(vars(module)):
- if attr.startswith("_"):
- continue
- try:
- value = getattr(module, attr)
- except Exception as exc:
- warnings.warn(
- f"conftest: could not read {module.__name__}.{attr} during snapshot: {exc}",
- stacklevel=2,
- )
- continue
- if value is None or isinstance(value, _SNAPSHOT_TYPES):
- try:
- snapshot[attr] = copy.deepcopy(value)
- except Exception as exc:
- warnings.warn(
- f"conftest: could not snapshot {module.__name__}.{attr}: {exc}",
- stacklevel=2,
- )
- return snapshot
-
-
-def _restore_mutable_state(module, snapshot):
- for attr, default in snapshot.items():
- try:
- setattr(module, attr, copy.deepcopy(default))
- except Exception as exc:
- warnings.warn(
- f"conftest: could not restore {module.__name__}.{attr}: {exc}",
- stacklevel=2,
- )
-
-
-def _collect_flushable_caches():
- """Return (module, attr) pairs whose values expose flush_cache()."""
- targets = []
- for module in (litellm, litellm.proxy.proxy_server):
- for attr in list(vars(module)):
- if attr.startswith("_"):
- continue
- try:
- value = getattr(module, attr)
- except Exception:
- continue
- # Only instances — a class reference has an unbound flush_cache
- # that can't be called without a self argument.
- if inspect.isclass(value) or inspect.ismodule(value):
- continue
- if callable(getattr(value, "flush_cache", None)):
- targets.append((module, attr))
- return targets
-
-
-def _flush_caches(targets):
- for module, attr in targets:
- try:
- value = getattr(module, attr)
- except Exception:
- continue
- flush = getattr(value, "flush_cache", None)
- if callable(flush):
- try:
- flush()
- except Exception as exc:
- warnings.warn(
- f"conftest: flush_cache failed on {module.__name__}.{attr}: {exc}",
- stacklevel=2,
- )
-
-
-# Snapshot once at conftest import — these are the "clean" module states.
-_LITELLM_STATE = _snapshot_mutable_state(litellm)
-_PROXY_SERVER_STATE = _snapshot_mutable_state(litellm.proxy.proxy_server)
-_FLUSHABLE_CACHES = _collect_flushable_caches()
-
-
[email protected](scope="function", autouse=True)
-def setup_and_teardown():
- """Reset mutable module state on litellm and proxy_server before each test.
-
- Replaces a previous importlib.reload(litellm) approach that cost ~17s
- per test (re-executing the full litellm __init__ import chain).
-
- What IS reset:
- - Top-level module attributes of type list / dict / set / tuple
- / str / int / float / bool / bytes, and None-valued attributes.
- These cover callback lists, general_settings, master_key,
- premium_user, prisma_client, etc. — anything the old reload() reset
- by re-executing the module body.
- - Any module-level object instance that exposes flush_cache() (the
- DualCache and LLMClientCache family), which handles cache state
- that can't round-trip through deepcopy because of internal locks.
-
- What is NOT reset:
- - Class instances without flush_cache() (e.g. ProxyLogging,
- JWTHandler, FastAPI routers, loggers). If a test mutates such an
- instance in-place (setattr on the instance, appending to one of
- its internal lists, etc.), the mutation will leak into later tests.
- Use pytest's monkeypatch.setattr() or a local fixture for those
- cases — don't rely on this autouse fixture to undo them.
- """
- _restore_mutable_state(litellm, _LITELLM_STATE)
- _restore_mutable_state(litellm.proxy.proxy_server, _PROXY_SERVER_STATE)
- _flush_caches(_FLUSHABLE_CACHES)
-
- loop = asyncio.get_event_loop_policy().new_event_loop()
- asyncio.set_event_loop(loop)
- try:
- yield
- finally:
- loop.close()
- asyncio.set_event_loop(None)
-
-
-def pytest_collection_modifyitems(config, items):
- # Separate tests in 'test_amazing_proxy_custom_logger.py' and other tests
- custom_logger_tests = [
- item for item in items if "custom_logger" in item.parent.name
- ]
- other_tests = [item for item in items if "custom_logger" not in item.parent.name]
-
- # Sort tests based on their names
- custom_logger_tests.sort(key=lambda x: x.name)
- other_tests.sort(key=lambda x: x.name)
-
- # Reorder the items list
- items[:] = custom_logger_tests + other_tests
diff --git a/tests/proxy_unit_tests/data_map.txt b/tests/proxy_unit_tests/data_map.txt
deleted file mode 100644
index e8077595f47..00000000000
Binary files a/tests/proxy_unit_tests/data_map.txt and /dev/null differ
diff --git a/tests/proxy_unit_tests/eagle.wav b/tests/proxy_unit_tests/eagle.wav
deleted file mode 100644
index 1c23657859e..00000000000
Binary files a/tests/proxy_unit_tests/eagle.wav and /dev/null differ
diff --git a/tests/proxy_unit_tests/gettysburg.wav b/tests/proxy_unit_tests/gettysburg.wav
deleted file mode 100644
index 9690f521e84..00000000000
Binary files a/tests/proxy_unit_tests/gettysburg.wav and /dev/null differ
diff --git a/tests/proxy_unit_tests/large_text.py b/tests/proxy_unit_tests/large_text.py
deleted file mode 100644
index 86904a6d148..00000000000
--- a/tests/proxy_unit_tests/large_text.py
+++ /dev/null
@@ -1,112 +0,0 @@
-text = """
-Alexander the Great
-This article is about the ancient king of Macedonia. For other uses, see Alexander the Great (disambiguation).
-Alexander III of Macedon (Ancient Greek: Ἀλέξανδρος, romanized: Alexandros; 20/21 July 356 BC – 10/11 June 323 BC), most commonly known as Alexander the Great,[c] was a king of the ancient Greek kingdom of Macedon.[d] He succeeded his father Philip II to the throne in 336 BC at the age of 20 and spent most of his ruling years conducting a lengthy military campaign throughout Western Asia, Central Asia, parts of South Asia, and Egypt. By the age of 30, he had created one of the largest empires in history, stretching from Greece to northwestern India.[1] He was undefeated in battle and is widely considered to be one of history's greatest and most successful military commanders.[2][3]
-
-Until the age of 16, Alexander was tutored by Aristotle. In 335 BC, shortly after his assumption of kingship over Macedon, he campaigned in the Balkans and reasserted control over Thrace and parts of Illyria before marching on the city of Thebes, which was subsequently destroyed in battle. Alexander then led the League of Corinth, and used his authority to launch the pan-Hellenic project envisaged by his father, assuming leadership over all Greeks in their conquest of Persia.[4][5]
-
-In 334 BC, he invaded the Achaemenid Persian Empire and began a series of campaigns that lasted for 10 years. Following his conquest of Asia Minor, Alexander broke the power of Achaemenid Persia in a series of decisive battles, including those at Issus and Gaugamela; he subsequently overthrew Darius III and conquered the Achaemenid Empire in its entirety.[e] After the fall of Persia, the Macedonian Empire held a vast swath of territory between the Adriatic Sea and the Indus River. Alexander endeavored to reach the "ends of the world and the Great Outer Sea" and invaded India in 326 BC, achieving an important victory over Porus, an ancient Indian king of present-day Punjab, at the Battle of the Hydaspes. Due to the demand of his homesick troops, he eventually turned back at the Beas River and later died in 323 BC in Babylon, the city of Mesopotamia that he had planned to establish as his empire's capital. Alexander's death left unexecuted an additional series of planned military and mercantile campaigns that would have begun with a Greek invasion of Arabia. In the years following his death, a series of civil wars broke out across the Macedonian Empire, eventually leading to its disintegration at the hands of the Diadochi.
-
-With his death marking the start of the Hellenistic period, Alexander's legacy includes the cultural diffusion and syncretism that his conquests engendered, such as Greco-Buddhism and Hellenistic Judaism. He founded more than twenty cities, with the most prominent being the city of Alexandria in Egypt. Alexander's settlement of Greek colonists and the resulting spread of Greek culture led to the overwhelming dominance of Hellenistic civilization and influence as far east as the Indian subcontinent. The Hellenistic period developed through the Roman Empire into modern Western culture; the Greek language became the lingua franca of the region and was the predominant language of the Byzantine Empire up until its collapse in the mid-15th century AD. Alexander became legendary as a classical hero in the mould of Achilles, featuring prominently in the historical and mythical traditions of both Greek and non-Greek cultures. His military achievements and unprecedented enduring successes in battle made him the measure against which many later military leaders would compare themselves,[f] and his tactics remain a significant subject of study in military academies worldwide.[6] Legends of Alexander's exploits coalesced into the third-century Alexander Romance which, in the premodern period, went through over one hundred recensions, translations, and derivations and was translated into almost every European vernacular and every language of the Islamic world.[7] After the Bible, it was the most popular form of European literature.[8]
-
-Early life
-
-Lineage and childhood
-
-Alexander III was born in Pella, the capital of the Kingdom of Macedon,[9] on the sixth day of the ancient Greek month of Hekatombaion, which probably corresponds to 20 July 356 BC (although the exact date is uncertain).[10][11] He was the son of the erstwhile king of Macedon, Philip II, and his fourth wife, Olympias (daughter of Neoptolemus I, king of Epirus).[12][g] Although Philip had seven or eight wives, Olympias was his principal wife for some time, likely because she gave birth to Alexander.[13]
-
-Several legends surround Alexander's birth and childhood.[14] According to the ancient Greek biographer Plutarch, on the eve of the consummation of her marriage to Philip, Olympias dreamed that her womb was struck by a thunderbolt that caused a flame to spread "far and wide" before dying away. Sometime after the wedding, Philip is said to have seen himself, in a dream, securing his wife's womb with a seal engraved with a lion's image.[15] Plutarch offered a variety of interpretations for these dreams: that Olympias was pregnant before her marriage, indicated by the sealing of her womb; or that Alexander's father was Zeus. Ancient commentators were divided about whether the ambitious Olympias promulgated the story of Alexander's divine parentage, variously claiming that she had told Alexander, or that she dismissed the suggestion as impious.[15]
-
-On the day Alexander was born, Philip was preparing a siege on the city of Potidea on the peninsula of Chalcidice. That same day, Philip received news that his general Parmenion had defeated the combined Illyrian and Paeonian armies and that his horses had won at the Olympic Games. It was also said that on this day, the Temple of Artemis in Ephesus, one of the Seven Wonders of the World, burnt down. This led Hegesias of Magnesia to say that it had burnt down because Artemis was away, attending the birth of Alexander.[16] Such legends may have emerged when Alexander was king, and possibly at his instigation, to show that he was superhuman and destined for greatness from conception.[14]
-
-In his early years, Alexander was raised by a nurse, Lanike, sister of Alexander's future general Cleitus the Black. Later in his childhood, Alexander was tutored by the strict Leonidas, a relative of his mother, and by Lysimachus of Acarnania.[17] Alexander was raised in the manner of noble Macedonian youths, learning to read, play the lyre, ride, fight, and hunt.[18] When Alexander was ten years old, a trader from Thessaly brought Philip a horse, which he offered to sell for thirteen talents. The horse refused to be mounted, and Philip ordered it away. Alexander, however, detecting the horse's fear of its own shadow, asked to tame the horse, which he eventually managed.[14] Plutarch stated that Philip, overjoyed at this display of courage and ambition, kissed his son tearfully, declaring: "My boy, you must find a kingdom big enough for your ambitions. Macedon is too small for you", and bought the horse for him.[19] Alexander named it Bucephalas, meaning "ox-head". Bucephalas carried Alexander as far as India. When the animal died (because of old age, according to Plutarch, at age 30), Alexander named a city after him, Bucephala.[20]
-
-Education
-
-When Alexander was 13, Philip began to search for a tutor, and considered such academics as Isocrates and Speusippus, the latter offering to resign from his stewardship of the Academy to take up the post. In the end, Philip chose Aristotle and provided the Temple of the Nymphs at Mieza as a classroom. In return for teaching Alexander, Philip agreed to rebuild Aristotle's hometown of Stageira, which Philip had razed, and to repopulate it by buying and freeing the ex-citizens who were slaves, or pardoning those who were in exile.[21]
-
-Mieza was like a boarding school for Alexander and the children of Macedonian nobles, such as Ptolemy, Hephaistion, and Cassander. Many of these students would become his friends and future generals, and are often known as the "Companions". Aristotle taught Alexander and his companions about medicine, philosophy, morals, religion, logic, and art. Under Aristotle's tutelage, Alexander developed a passion for the works of Homer, and in particular the Iliad; Aristotle gave him an annotated copy, which Alexander later carried on his campaigns.[22] Alexander was able to quote Euripides from memory.[23]
-
-During his youth, Alexander was also acquainted with Persian exiles at the Macedonian court, who received the protection of Philip II for several years as they opposed Artaxerxes III.[24][25][26] Among them were Artabazos II and his daughter Barsine, possible future mistress of Alexander, who resided at the Macedonian court from 352 to 342 BC, as well as Amminapes, future satrap of Alexander, or a Persian nobleman named Sisines.[24][27][28][29] This gave the Macedonian court a good knowledge of Persian issues, and may even have influenced some of the innovations in the management of the Macedonian state.[27]
-
-Suda writes that Anaximenes of Lampsacus was one of Alexander's teachers, and that Anaximenes also accompanied Alexander on his campaigns.[30]
-
-Heir of Philip II
-
-Regency and ascent of Macedon
-
-Main articles: Philip II of Macedon and Rise of Macedon
-Further information: History of Macedonia (ancient kingdom)
-At the age of 16, Alexander's education under Aristotle ended. Philip II had waged war against the Thracians to the north, which left Alexander in charge as regent and heir apparent.[14] During Philip's absence, the Thracian tribe of Maedi revolted against Macedonia. Alexander responded quickly and drove them from their territory. The territory was colonized, and a city, named Alexandropolis, was founded.[31]
-
-Upon Philip's return, Alexander was dispatched with a small force to subdue the revolts in southern Thrace. Campaigning against the Greek city of Perinthus, Alexander reportedly saved his father's life. Meanwhile, the city of Amphissa began to work lands that were sacred to Apollo near Delphi, a sacrilege that gave Philip the opportunity to further intervene in Greek affairs. While Philip was occupied in Thrace, Alexander was ordered to muster an army for a campaign in southern Greece. Concerned that other Greek states might intervene, Alexander made it look as though he was preparing to attack Illyria instead. During this turmoil, the Illyrians invaded Macedonia, only to be repelled by Alexander.[32]
-
-Philip and his army joined his son in 338 BC, and they marched south through Thermopylae, taking it after stubborn resistance from its Theban garrison. They went on to occupy the city of Elatea, only a few days' march from both Athens and Thebes. The Athenians, led by Demosthenes, voted to seek alliance with Thebes against Macedonia. Both Athens and Philip sent embassies to win Thebes's favour, but Athens won the contest.[33] Philip marched on Amphissa (ostensibly acting on the request of the Amphictyonic League), capturing the mercenaries sent there by Demosthenes and accepting the city's surrender. Philip then returned to Elatea, sending a final offer of peace to Athens and Thebes, who both rejected it.[34]
-
-As Philip marched south, his opponents blocked him near Chaeronea, Boeotia. During the ensuing Battle of Chaeronea, Philip commanded the right wing and Alexander the left, accompanied by a group of Philip's trusted generals. According to the ancient sources, the two sides fought bitterly for some time. Philip deliberately commanded his troops to retreat, counting on the untested Athenian hoplites to follow, thus breaking their line. Alexander was the first to break the Theban lines, followed by Philip's generals. Having damaged the enemy's cohesion, Philip ordered his troops to press forward and quickly routed them. With the Athenians lost, the Thebans were surrounded. Left to fight alone, they were defeated.[35]
-
-After the victory at Chaeronea, Philip and Alexander marched unopposed into the Peloponnese, welcomed by all cities; however, when they reached Sparta, they were refused, but did not resort to war.[36] At Corinth, Philip established a "Hellenic Alliance" (modelled on the old anti-Persian alliance of the Greco-Persian Wars), which included most Greek city-states except Sparta. Philip was then named Hegemon (often translated as "Supreme Commander") of this league (known by modern scholars as the League of Corinth), and announced his plans to attack the Persian Empire.[37][38]
-
-Exile and return
-
-When Philip returned to Pella, he fell in love with and married Cleopatra Eurydice in 338 BC,[39] the niece of his general Attalus.[40] The marriage made Alexander's position as heir less secure, since any son of Cleopatra Eurydice would be a fully Macedonian heir, while Alexander was only half-Macedonian.[41] During the wedding banquet, a drunken Attalus publicly prayed to the gods that the union would produce a legitimate heir.[40]
-
-At the wedding of Cleopatra, whom Philip fell in love with and married, she being much too young for him, her uncle Attalus in his drink desired the Macedonians would implore the gods to give them a lawful successor to the kingdom by his niece. This so irritated Alexander, that throwing one of the cups at his head, "You villain," said he, "what, am I then a bastard?" Then Philip, taking Attalus's part, rose up and would have run his son through; but by good fortune for them both, either his over-hasty rage, or the wine he had drunk, made his foot slip, so that he fell down on the floor. At which Alexander reproachfully insulted over him: "See there," said he, "the man who makes preparations to pass out of Europe into Asia, overturned in passing from one seat to another."
-
-— Plutarch, describing the feud at Philip's wedding.[42]none
-In 337 BC, Alexander fled Macedon with his mother, dropping her off with her brother, King Alexander I of Epirus in Dodona, capital of the Molossians.[43] He continued to Illyria,[43] where he sought refuge with one or more Illyrian kings, perhaps with Glaucias, and was treated as a guest, despite having defeated them in battle a few years before.[44] However, it appears Philip never intended to disown his politically and militarily trained son.[43] Accordingly, Alexander returned to Macedon after six months due to the efforts of a family friend, Demaratus, who mediated between the two parties.[45]
-
-In the following year, the Persian satrap (governor) of Caria, Pixodarus, offered his eldest daughter to Alexander's half-brother, Philip Arrhidaeus.[43] Olympias and several of Alexander's friends suggested this showed Philip intended to make Arrhidaeus his heir.[43] Alexander reacted by sending an actor, Thessalus of Corinth, to tell Pixodarus that he should not offer his daughter's hand to an illegitimate son, but instead to Alexander. When Philip heard of this, he stopped the negotiations and scolded Alexander for wishing to marry the daughter of a Carian, explaining that he wanted a better bride for him.[43] Philip exiled four of Alexander's friends, Harpalus, Nearchus, Ptolemy and Erigyius, and had the Corinthians bring Thessalus to him in chains.[46]
-
-King of Macedon
-
-Accession
-
-Further information: Government of Macedonia (ancient kingdom)
-In summer 336 BC, while at Aegae attending the wedding of his daughter Cleopatra to Olympias's brother, Alexander I of Epirus, Philip was assassinated by the captain of his bodyguards, Pausanias.[h] As Pausanias tried to escape, he tripped over a vine and was killed by his pursuers, including two of Alexander's companions, Perdiccas and Leonnatus. Alexander was proclaimed king on the spot by the nobles and army at the age of 20.[47][48][49]
-
-Consolidation of power
-
-Alexander began his reign by eliminating potential rivals to the throne. He had his cousin, the former Amyntas IV, executed.[51] He also had two Macedonian princes from the region of Lyncestis killed for having been involved in his father's assassination, but spared a third, Alexander Lyncestes. Olympias had Cleopatra Eurydice, and Europa, her daughter by Philip, burned alive. When Alexander learned about this, he was furious. Alexander also ordered the murder of Attalus,[51] who was in command of the advance guard of the army in Asia Minor and Cleopatra's uncle.[52]
-
-Attalus was at that time corresponding with Demosthenes, regarding the possibility of defecting to Athens. Attalus also had severely insulted Alexander, and following Cleopatra's murder, Alexander may have considered him too dangerous to be left alive.[52] Alexander spared Arrhidaeus, who was by all accounts mentally disabled, possibly as a result of poisoning by Olympias.[47][49][53]
-
-News of Philip's death roused many states into revolt, including Thebes, Athens, Thessaly, and the Thracian tribes north of Macedon. When news of the revolts reached Alexander, he responded quickly. Though advised to use diplomacy, Alexander mustered 3,000 Macedonian cavalry and rode south towards Thessaly. He found the Thessalian army occupying the pass between Mount Olympus and Mount Ossa, and ordered his men to ride over Mount Ossa. When the Thessalians awoke the next day, they found Alexander in their rear and promptly surrendered, adding their cavalry to Alexander's force. He then continued south towards the Peloponnese.[54]
-
-Alexander stopped at Thermopylae, where he was recognized as the leader of the Amphictyonic League before heading south to Corinth. Athens sued for peace and Alexander pardoned the rebels. The famous encounter between Alexander and Diogenes the Cynic occurred during Alexander's stay in Corinth. When Alexander asked Diogenes what he could do for him, the philosopher disdainfully asked Alexander to stand a little to the side, as he was blocking the sunlight.[55] This reply apparently delighted Alexander, who is reported to have said "But verily, if I were not Alexander, I would like to be Diogenes."[56] At Corinth, Alexander took the title of Hegemon ("leader") and, like Philip, was appointed commander for the coming war against Persia. He also received news of a Thracian uprising.[57]
-
-Balkan campaign
-
-Main article: Alexander's Balkan campaign
-Before crossing to Asia, Alexander wanted to safeguard his northern borders. In the spring of 335 BC, he advanced to suppress several revolts. Starting from Amphipolis, he travelled east into the country of the "Independent Thracians"; and at Mount Haemus, the Macedonian army attacked and defeated the Thracian forces manning the heights.[58] The Macedonians marched into the country of the Triballi, and defeated their army near the Lyginus river[59] (a tributary of the Danube). Alexander then marched for three days to the Danube, encountering the Getae tribe on the opposite shore. Crossing the river at night, he surprised them and forced their army to retreat after the first cavalry skirmish.[60]
-
-News then reached Alexander that the Illyrian chieftain Cleitus and King Glaukias of the Taulantii were in open revolt against his authority. Marching west into Illyria, Alexander defeated each in turn, forcing the two rulers to flee with their troops. With these victories, he secured his northern frontier.[61]
-
-Destruction of Thebes
-
-While Alexander campaigned north, the Thebans and Athenians rebelled once again. Alexander immediately headed south.[62] While the other cities again hesitated, Thebes decided to fight. The Theban resistance was ineffective, and Alexander razed the city and divided its territory between the other Boeotian cities. The end of Thebes cowed Athens, leaving all of Greece temporarily at peace.[62] Alexander then set out on his Asian campaign, leaving Antipater as regent.[63]
-
-Conquest of the Achaemenid Persian Empire
-
-Main articles: Wars of Alexander the Great and Chronology of the expedition of Alexander the Great into Asia
-Asia Minor
-
-Further information: Battle of the Granicus, Siege of Halicarnassus, and Siege of Miletus
-After his victory at the Battle of Chaeronea (338 BC), Philip II began the work of establishing himself as hēgemṓn (Greek: ἡγεμών) of a league which according to Diodorus was to wage a campaign against the Persians for the sundry grievances Greece suffered in 480 and free the Greek cities of the western coast and islands from Achaemenid rule. In 336 he sent Parmenion, Amyntas, Andromenes, Attalus, and an army of 10,000 men into Anatolia to make preparations for an invasion.[64][65] At first, all went well. The Greek cities on the western coast of Anatolia revolted until the news arrived that Philip had been murdered and had been succeeded by his young son Alexander. The Macedonians were demoralized by Philip's death and were subsequently defeated near Magnesia by the Achaemenids under the command of the mercenary Memnon of Rhodes.[64][65]
-
-Taking over the invasion project of Philip II, Alexander's army crossed the Hellespont in 334 BC with approximately 48,100 soldiers, 6,100 cavalry and a fleet of 120 ships with crews numbering 38,000,[62] drawn from Macedon and various Greek city-states, mercenaries, and feudally raised soldiers from Thrace, Paionia, and Illyria.[66][i] He showed his intent to conquer the entirety of the Persian Empire by throwing a spear into Asian soil and saying he accepted Asia as a gift from the gods. This also showed Alexander's eagerness to fight, in contrast to his father's preference for diplomacy.[62]
-
-After an initial victory against Persian forces at the Battle of the Granicus, Alexander accepted the surrender of the Persian provincial capital and treasury of Sardis; he then proceeded along the Ionian coast, granting autonomy and democracy to the cities. Miletus, held by Achaemenid forces, required a delicate siege operation, with Persian naval forces nearby. Further south, at Halicarnassus, in Caria, Alexander successfully waged his first large-scale siege, eventually forcing his opponents, the mercenary captain Memnon of Rhodes and the Persian satrap of Caria, Orontobates, to withdraw by sea.[67] Alexander left the government of Caria to a member of the Hecatomnid dynasty, Ada, who adopted Alexander.[68]
-
-From Halicarnassus, Alexander proceeded into mountainous Lycia and the Pamphylian plain, asserting control over all coastal cities to deny the Persians naval bases. From Pamphylia onwards the coast held no major ports and Alexander moved inland. At Termessos, Alexander humbled but did not storm the Pisidian city.[69] At the ancient Phrygian capital of Gordium, Alexander "undid" the hitherto unsolvable Gordian Knot, a feat said to await the future "king of Asia".[70] According to the story, Alexander proclaimed that it did not matter how the knot was undone and hacked it apart with his sword.[71]
-
-The Levant and Syria
-
-Further information: Battle of Issus and Siege of Tyre (332 BC)
-In spring 333 BC, Alexander crossed the Taurus into Cilicia. After a long pause due to an illness, he marched on towards Syria. Though outmanoeuvered by Darius's significantly larger army, he marched back to Cilicia, where he defeated Darius at Issus. Darius fled the battle, causing his army to collapse, and left behind his wife, his two daughters, his mother Sisygambis, and a fabulous treasure.[72] He offered a peace treaty that included the lands he had already lost, and a ransom of 10,000 talents for his family. Alexander replied that since he was now king of Asia, it was he alone who decided territorial divisions.[73] Alexander proceeded to take possession of Syria, and most of the coast of the Levant.[68] In the following year, 332 BC, he was forced to attack Tyre, which he captured after a long and difficult siege.[74][75] The men of military age were massacred and the women and children sold into slavery.[76]
-
-Egypt
-
-Further information: Siege of Gaza (332 BCE)
-When Alexander destroyed Tyre, most of the towns on the route to Egypt quickly capitulated. However, Alexander was met with resistance at Gaza. The stronghold was heavily fortified and built on a hill, requiring a siege. When "his engineers pointed out to him that because of the height of the mound it would be impossible... this encouraged Alexander all the more to make the attempt".[77] After three unsuccessful assaults, the stronghold fell, but not before Alexander had received a serious shoulder wound. As in Tyre, men of military age were put to the sword and the women and children were sold into slavery.[78]
-"""
diff --git a/tests/proxy_unit_tests/messages_with_counts.py b/tests/proxy_unit_tests/messages_with_counts.py
deleted file mode 100644
index da27a975520..00000000000
--- a/tests/proxy_unit_tests/messages_with_counts.py
+++ /dev/null
@@ -1,733 +0,0 @@
-system_message_short = {
- "message": {
- "role": "system",
- "content": "You are a bot.",
- },
- "count": 12,
-}
-
-system_message = {
- "message": {
- "role": "system",
- "content": "You are a helpful, pattern-following assistant that translates corporate jargon into plain English.",
- },
- "count": 25,
-}
-
-system_message_long = {
- "message": {
- "role": "system",
- "content": "Assistant helps the company employees with their healthcare plan questions, and questions about the employee handbook. Be brief in your answers.",
- },
- "count": 31,
-}
-
-system_message_unicode = {
- "message": {
- "role": "system",
- "content": "á",
- },
- "count": 8,
-}
-
-system_message_with_name = {
- "message": {
- "role": "system",
- "name": "example_user",
- "content": "New synergies will help drive top-line growth.",
- },
- "count": 20,
-}
-
-user_message = {
- "message": {
- "role": "user",
- "content": "Hello, how are you?",
- },
- "count": 13,
-}
-
-user_message_unicode = {
- "message": {
- "role": "user",
- "content": "á",
- },
- "count": 8,
-}
-
-user_message_perf = {
- "message": {
- "role": "user",
- "content": "What happens in a performance review?",
- },
- "count": 14,
-}
-
-assistant_message_perf = {
- "message": {
- "role": "assistant",
- "content": "During the performance review at Contoso Electronics, the supervisor will discuss the employee's performance over the past year and provide feedback on areas for improvement. They will also provide an opportunity for the employee to discuss their goals and objectives for the upcoming year. The review is a two-way dialogue between managers and employees, and employees will receive a written summary of their performance review which will include a rating of their performance, feedback, and goals and objectives for the upcoming year [employee_handbook-3.pdf].",
- },
- "count": 106,
-}
-
-assistant_message_perf_short = {
- "message": {
- "role": "assistant",
- "content": "The supervisor will discuss the employee's performance and provide feedback on areas for improvement. They will also provide an opportunity for the employee to discuss their goals and objectives for the upcoming year. The review is a two-way dialogue between managers and employees, and employees will receive a written summary of their performance review which will include a rating of their performance, feedback, and goals for the upcoming year [employee_handbook-3.pdf].",
- },
- "count": 91,
-}
-
-user_message_dresscode = {
- "message": {
- "role": "user",
- "content": "Is there a dress code?",
- },
- "count": 13,
-}
-
-assistant_message_dresscode = {
- "message": {
- "role": "assistant",
- "content": "Yes, there is a dress code at Contoso Electronics. Look sharp! [employee_handbook-1.pdf]",
- },
- "count": 30,
-}
-
-user_message_pm = {
- "message": {
- "role": "user",
- "content": "What does a Product Manager do?",
- },
- "count": 14,
-}
-
-text_and_image_message = {
- "message": {
- "role": "user",
- "content": [
- {"type": "text", "text": "Describe this picture:"},
- {
- "type": "image_url",
- "image_url": {
- "url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z/C/HgAGgwJ/lK3Q6wAAAABJRU5ErkJggg==",
- "detail": "high",
- },
- },
- ],
- },
- "count": 266,
-}
-
-
-search_sources_toolchoice_auto = {
- "system_message": {
- "role": "system",
- "content": "You are a bot.",
- },
- "tools": [
- {
- "type": "function",
- "function": {
- "name": "search_sources",
- "description": "Retrieve sources from the Azure AI Search index",
- "parameters": {
- "type": "object",
- "properties": {
- "search_query": {
- "type": "string",
- "description": "Query string to retrieve documents from azure search eg: 'Health care plan'",
- }
- },
- "required": ["search_query"],
- },
- },
- }
- ],
- "tool_choice": "auto",
- "count": 66,
-}
-
-search_sources_toolchoice_none = {
- "system_message": {
- "role": "system",
- "content": "You are a bot.",
- },
- "tools": [
- {
- "type": "function",
- "function": {
- "name": "search_sources",
- "description": "Retrieve sources from the Azure AI Search index",
- "parameters": {
- "type": "object",
- "properties": {
- "search_query": {
- "type": "string",
- "description": "Query string to retrieve documents from azure search eg: 'Health care plan'",
- }
- },
- "required": ["search_query"],
- },
- },
- }
- ],
- "tool_choice": "none",
- "count": 67,
-}
-
-search_sources_toolchoice_name = {
- "system_message": {
- "role": "system",
- "content": "You are a bot.",
- },
- "tools": [
- {
- "type": "function",
- "function": {
- "name": "search_sources",
- "description": "Retrieve sources from the Azure AI Search index",
- "parameters": {
- "type": "object",
- "properties": {
- "search_query": {
- "type": "string",
- "description": "Query string to retrieve documents from azure search eg: 'Health care plan'",
- }
- },
- "required": ["search_query"],
- },
- },
- }
- ],
- "tool_choice": {"type": "function", "function": {"name": "search_sources"}},
- "count": 75,
-}
-
-integer_enum = {
- "system_message": {
- "role": "system",
- "content": "You are a bot.",
- },
- "tools": [
- {
- "type": "function",
- "function": {
- "name": "data_demonstration",
- "description": "This is the main function description",
- "parameters": {
- "type": "object",
- "properties": {
- "integer_enum": {"type": "integer", "enum": [-1, 1]}
- },
- },
- },
- }
- ],
- "tool_choice": "none",
- "count": 54,
-}
-
-
-integer_enum_tool_choice_name = {
- "system_message": {
- "role": "system",
- "content": "You are a bot.",
- },
- "tools": [
- {
- "type": "function",
- "function": {
- "name": "data_demonstration",
- "description": "This is the main function description",
- "parameters": {
- "type": "object",
- "properties": {
- "integer_enum": {"type": "integer", "enum": [-1, 1]}
- },
- },
- },
- }
- ],
- "tool_choice": {
- "type": "function",
- "function": {"name": "data_demonstration"},
- }, # 4 tokens for "data_demonstration"
- "count": 64,
-}
-
-no_parameters = {
- "system_message": {
- "role": "system",
- "content": "You are a bot.",
- },
- "tools": [
- {
- "type": "function",
- "function": {
- "name": "search_sources",
- "description": "Retrieve sources from the Azure AI Search index",
- },
- }
- ],
- "tool_choice": "auto",
- "count": 42,
-}
-
-no_parameters_tool_choice_name = {
- "system_message": {
- "role": "system",
- "content": "You are a bot.",
- },
- "tools": [
- {
- "type": "function",
- "function": {
- "name": "search_sources",
- "description": "Retrieve sources from the Azure AI Search index",
- },
- }
- ],
- "tool_choice": {
- "type": "function",
- "function": {"name": "search_sources"},
- }, # 2 tokens for "search_sources"
- "count": 51,
-}
-
-no_parameter_description_or_required = {
- "system_message": {
- "role": "system",
- "content": "You are a bot.",
- },
- "tools": [
- {
- "type": "function",
- "function": {
- "name": "search_sources",
- "description": "Retrieve sources from the Azure AI Search index",
- "parameters": {
- "type": "object",
- "properties": {"search_query": {"type": "string"}},
- },
- },
- }
- ],
- "tool_choice": "auto",
- "count": 49,
-}
-
-no_parameter_description = {
- "system_message": {
- "role": "system",
- "content": "You are a bot.",
- },
- "tools": [
- {
- "type": "function",
- "function": {
- "name": "search_sources",
- "description": "Retrieve sources from the Azure AI Search index",
- "parameters": {
- "type": "object",
- "properties": {"search_query": {"type": "string"}},
- "required": ["search_query"],
- },
- },
- }
- ],
- "tool_choice": "auto",
- "count": 49,
-}
-
-string_enum = {
- "system_message": {
- "role": "system",
- "content": "You are a bot.",
- },
- "tools": [
- {
- "type": "function",
- "function": {
- "name": "summarize_order",
- "description": "Summarize the customer order request",
- "parameters": {
- "type": "object",
- "properties": {
- "product_name": {
- "type": "string",
- "description": "Product name ordered by customer",
- },
- "quantity": {
- "type": "integer",
- "description": "Quantity ordered by customer",
- },
- "unit": {
- "type": "string",
- "enum": ["meals", "days"],
- "description": "unit of measurement of the customer order",
- },
- },
- "required": ["product_name", "quantity", "unit"],
- },
- },
- }
- ],
- "tool_choice": "none",
- "count": 86,
-}
-
-inner_object = {
- "system_message": {
- "role": "system",
- "content": "You are a bot.",
- },
- "tools": [
- {
- "type": "function",
- "function": {
- "name": "data_demonstration",
- "description": "This is the main function description",
- "parameters": {
- "type": "object",
- "properties": {
- "object_1": {
- "type": "object",
- "description": "The object data type as a property",
- "properties": {
- "string1": {"type": "string"},
- },
- }
- },
- "required": ["object_1"],
- },
- },
- }
- ],
- "tool_choice": "none",
- "count": 65, # counted 67, over by 2
-}
-"""
-namespace functions {
-
-// This is the main function description
-type data_demonstration = (_: {
-// The object data type as a property
-object_1: {
- string1?: string,
-},
-}) => any;
-
-} // namespace functions
-"""
-
-inner_object_with_enum_only = {
- "system_message": {
- "role": "system",
- "content": "You are a bot.",
- },
- "tools": [
- {
- "type": "function",
- "function": {
- "name": "data_demonstration",
- "description": "This is the main function description",
- "parameters": {
- "type": "object",
- "properties": {
- "object_1": {
- "type": "object",
- "description": "The object data type as a property",
- "properties": {
- "string_2a": {
- "type": "string",
- "enum": ["Happy", "Sad"],
- }
- },
- }
- },
- "required": ["object_1"],
- },
- },
- }
- ],
- "tool_choice": "none",
- "count": 73, # counted 74, over by 1
-}
-"""
-namespace functions {
-
-// This is the main function description
-type data_demonstration = (_: {
-// The object data type as a property
-object_1: {
- string_2a?: "Happy" | "Sad",
-},
-}) => any;
-
-} // namespace functions
-"""
-
-inner_object_with_enum = {
- "system_message": {
- "role": "system",
- "content": "You are a bot.",
- },
- "tools": [
- {
- "type": "function",
- "function": {
- "name": "data_demonstration",
- "description": "This is the main function description",
- "parameters": {
- "type": "object",
- "properties": {
- "object_1": {
- "type": "object",
- "description": "The object data type as a property",
- "properties": {
- "string_2a": {
- "type": "string",
- "enum": ["Happy", "Sad"],
- },
- "string_2b": {
- "type": "string",
- "description": "Description in a second object is lost",
- },
- },
- }
- },
- "required": ["object_1"],
- },
- },
- }
- ],
- "tool_choice": "none",
- "count": 89, # counted 92, over by 3
-}
-"""
-namespace functions {
-
-// This is the main function description
-type data_demonstration = (_: {
-// The object data type as a property
-object_1: {
- string_2a?: "Happy" | "Sad",
- // Description in a second object is lost
- string_2b?: string,
-},
-}) => any;
-
-} // namespace functions
-"""
-
-inner_object_and_string = {
- "system_message": {
- "role": "system",
- "content": "You are a bot.",
- },
- "tools": [
- {
- "type": "function",
- "function": {
- "name": "data_demonstration",
- "description": "This is the main function description",
- "parameters": {
- "type": "object",
- "properties": {
- "object_1": {
- "type": "object",
- "description": "The object data type as a property",
- "properties": {
- "string_2a": {
- "type": "string",
- "enum": ["Happy", "Sad"],
- },
- "string_2b": {
- "type": "string",
- "description": "Description in a second object is lost",
- },
- },
- },
- "string_1": {
- "type": "string",
- "description": "Not required gets a question mark",
- },
- },
- "required": ["object_1"],
- },
- },
- }
- ],
- "tool_choice": "none",
- "count": 103, # counted 106, over by 3
-}
-"""
-namespace functions {
-
-// This is the main function description
-type data_demonstration = (_: {
-// The object data type as a property
-object_1: {
- string_2a?: "Happy" | "Sad",
- // Description in a second object is lost
- string_2b?: string,
-},
-// Not required gets a question mark
-string_1?: string,
-}) => any;
-
-} // namespace functions
-"""
-
-boolean = {
- "system_message": {
- "role": "system",
- "content": "You are a bot.",
- },
- "tools": [
- {
- "type": "function",
- "function": {
- "name": "human_escalation",
- "description": "Check if user wants to escalate to a human",
- "parameters": {
- "type": "object",
- "properties": {
- "requires_escalation": {
- "type": "boolean",
- "description": "If user is showing signs of frustration or anger in the query. Also if the user says they want to talk to a real person and not a chat bot.",
- }
- },
- "required": ["requires_escalation"],
- },
- },
- }
- ],
- "tool_choice": "none",
- "count": 89, # over by 3
-}
-
-array = {
- "system_message": {
- "role": "system",
- "content": "You are a bot.",
- },
- "tools": [
- {
- "type": "function",
- "function": {
- "name": "get_coordinates",
- "description": "Get the latitude and longitude of multiple mailing addresses",
- "parameters": {
- "type": "object",
- "properties": {
- "addresses": {
- "type": "array",
- "description": "The mailing addresses to be located",
- "items": {"type": "string"},
- }
- },
- "required": ["addresses"],
- },
- },
- }
- ],
- "tool_choice": "none",
- "count": 59,
-}
-
-null = {
- "system_message": {
- "role": "system",
- "content": "You are a bot.",
- },
- "tools": [
- {
- "type": "function",
- "function": {
- "name": "get_null",
- "description": "Get the null value",
- "parameters": {
- "type": "object",
- "properties": {
- "null_value": {
- "type": "null",
- "description": "The null value to be returned",
- }
- },
- "required": ["null_value"],
- },
- },
- }
- ],
- "tool_choice": "none",
- "count": 55,
-}
-
-no_type = {
- "system_message": {
- "role": "system",
- "content": "You are a bot.",
- },
- "tools": [
- {
- "type": "function",
- "function": {
- "name": "get_no_type",
- "description": "Get the no type value",
- "parameters": {
- "type": "object",
- "properties": {
- "no_type_value": {
- "description": "The no type value to be returned",
- }
- },
- "required": ["no_type_value"],
- },
- },
- }
- ],
- "tool_choice": "none",
- "count": 59,
-}
-
-MESSAGES_TEXT = [
- system_message,
- system_message_short,
- system_message_long,
- system_message_unicode,
- system_message_with_name,
- user_message,
- user_message_unicode,
- user_message_perf,
- user_message_dresscode,
- user_message_pm,
- assistant_message_perf,
- assistant_message_perf_short,
- assistant_message_dresscode,
-]
-
-MESSAGES_WITH_IMAGES = [text_and_image_message]
-
-MESSAGES_WITH_TOOLS = [
- inner_object,
- inner_object_and_string,
- inner_object_with_enum_only,
- inner_object_with_enum,
- search_sources_toolchoice_auto,
- search_sources_toolchoice_none,
- search_sources_toolchoice_name,
- integer_enum,
- integer_enum_tool_choice_name,
- no_parameters,
- no_parameters_tool_choice_name,
- no_parameter_description_or_required,
- no_parameter_description,
- string_enum,
- boolean,
- array,
- no_type,
- null,
-]
diff --git a/tests/proxy_unit_tests/model_cost.json b/tests/proxy_unit_tests/model_cost.json
deleted file mode 100644
index 8d6f6851e16..00000000000
--- a/tests/proxy_unit_tests/model_cost.json
+++ /dev/null
@@ -1,3 +0,0 @@
-{
- "gpt-3.5-turbo": 7.7e-05
-}
\ No newline at end of file
diff --git a/tests/proxy_unit_tests/openai_batch_completions.jsonl b/tests/proxy_unit_tests/openai_batch_completions.jsonl
deleted file mode 100644
index 05448952a0f..00000000000
--- a/tests/proxy_unit_tests/openai_batch_completions.jsonl
+++ /dev/null
@@ -1,2 +0,0 @@
-{"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-3.5-turbo-0125", "messages": [{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": "Hello world!"}],"max_tokens": 10}}
-{"custom_id": "request-2", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-3.5-turbo-0125", "messages": [{"role": "system", "content": "You are an unhelpful assistant."},{"role": "user", "content": "Hello world!"}],"max_tokens": 10}}
\ No newline at end of file
diff --git a/tests/proxy_unit_tests/openai_batch_completions_router.jsonl b/tests/proxy_unit_tests/openai_batch_completions_router.jsonl
deleted file mode 100644
index 8a4c99ca85e..00000000000
--- a/tests/proxy_unit_tests/openai_batch_completions_router.jsonl
+++ /dev/null
@@ -1,3 +0,0 @@
-{"custom_id": "task-0", "method": "POST", "url": "/chat/completions", "body": {"model": "my-custom-name", "messages": [{"role": "system", "content": "You are an AI assistant that helps people find information."}, {"role": "user", "content": "When was Microsoft founded?"}]}}
-{"custom_id": "task-1", "method": "POST", "url": "/chat/completions", "body": {"model": "my-custom-name", "messages": [{"role": "system", "content": "You are an AI assistant that helps people find information."}, {"role": "user", "content": "When was the first XBOX released?"}]}}
-{"custom_id": "task-2", "method": "POST", "url": "/chat/completions", "body": {"model": "my-custom-name", "messages": [{"role": "system", "content": "You are an AI assistant that helps people find information."}, {"role": "user", "content": "What is Altair Basic?"}]}}
\ No newline at end of file
diff --git a/tests/proxy_unit_tests/speech_vertex.mp3 b/tests/proxy_unit_tests/speech_vertex.mp3
deleted file mode 100644
index c676110335e..00000000000
Binary files a/tests/proxy_unit_tests/speech_vertex.mp3 and /dev/null differ
diff --git a/tests/proxy_unit_tests/test_proxy_custom_logger.py b/tests/proxy_unit_tests/test_proxy_custom_logger.py
deleted file mode 100644
index 2516df2d58d..00000000000
--- a/tests/proxy_unit_tests/test_proxy_custom_logger.py
+++ /dev/null
@@ -1,319 +0,0 @@
-import sys, os
-import traceback
-from dotenv import load_dotenv
-
-load_dotenv()
-import io, asyncio
-
-# this file is to test litellm/proxy
-
-import pytest, time
-import litellm
-from litellm import embedding, completion, completion_cost, Timeout
-from litellm import RateLimitError
-import importlib, inspect
-
-# test /chat/completion request to the proxy
-from fastapi.testclient import TestClient
-from fastapi import FastAPI
-from litellm.proxy.proxy_server import (
- router,
- save_worker_config,
- initialize,
-) # Replace with the actual module where your FastAPI router is defined
-
-filepath = os.path.dirname(os.path.abspath(__file__))
-python_file_path = f"{filepath}/test_configs/custom_callbacks.py"
-
-
-def client():
- filepath = os.path.dirname(os.path.abspath(__file__))
- config_fp = f"{filepath}/test_configs/test_custom_logger.yaml"
- app = FastAPI()
- asyncio.run(initialize(config=config_fp))
- app.include_router(router) # Include your router in the test app
- return TestClient(app)
-
-
-# Your bearer token
-token = os.getenv("PROXY_MASTER_KEY")
-
-headers = {"Authorization": f"Bearer {token}"}
-
-
-print("Testing proxy custom logger")
-
-
- os.environ.get("OPENAI_API_KEY") is None,
- reason="OPENAI_API_KEY not set - skipping integration test",
-)
-def test_embedding(client):
- try:
- litellm.set_verbose = False
- from litellm.proxy.types_utils.utils import get_instance_fn
-
- my_custom_logger = get_instance_fn(
- value="custom_callbacks.my_custom_logger", config_file_path=python_file_path
- )
- print("id of initialized custom logger", id(my_custom_logger))
- litellm.callbacks = [my_custom_logger]
- # Your test data
- print("initialized proxy")
- # import the initialized custom logger
- print(litellm.callbacks)
-
- # assert len(litellm.callbacks) == 1 # assert litellm is initialized with 1 callback
- print("my_custom_logger", my_custom_logger)
- assert my_custom_logger.async_success_embedding is False
-
- test_data = {"model": "azure-embedding-model", "input": ["hello"]}
- response = client.post("/embeddings", json=test_data, headers=headers)
- print("made request", response.status_code, response.text)
- print(
- "vars my custom logger /embeddings",
- vars(my_custom_logger),
- "id",
- id(my_custom_logger),
- )
- assert (
- my_custom_logger.async_success_embedding is True
- ) # checks if the status of async_success is True, only the async_log_success_event can set this to true
- assert (
- my_custom_logger.async_embedding_kwargs["model"] == "text-embedding-ada-002"
- ) # checks if kwargs passed to async_log_success_event are correct
- kwargs = my_custom_logger.async_embedding_kwargs
- litellm_params = kwargs.get("litellm_params")
-
- # Test 1: Verify metadata is populated correctly
- metadata = litellm_params.get("metadata", None)
- print("\n\n Metadata in custom logger kwargs", litellm_params.get("metadata"))
- assert metadata is not None, "metadata should be present in litellm_params"
- assert "user_api_key" in metadata, "user_api_key should be in metadata"
- assert "headers" in metadata, "headers should be in metadata"
-
- # Test 2: Verify proxy_server_request contains the original request details
- proxy_server_request = litellm_params.get("proxy_server_request")
- assert proxy_server_request is not None, "proxy_server_request should exist"
- assert (
- proxy_server_request.get("url") == "http://testserver/embeddings"
- ), "url should match"
- assert proxy_server_request.get("method") == "POST", "method should be POST"
- assert "headers" in proxy_server_request, "headers should be present"
- assert "body" in proxy_server_request, "body should be present"
-
- # Test 3: Verify request body contains the original input data
- body = proxy_server_request["body"]
- assert (
- body.get("model") == "azure-embedding-model"
- ), "model should match original request"
- assert body.get("input") == ["hello"], "input should match original request"
-
- # Test 4: Verify model_info is populated
- model_info = litellm_params.get("model_info")
- assert model_info is not None, "model_info should exist"
- assert model_info.get("mode") == "embedding", "mode should be embedding"
- assert model_info.get("id") == "hello", "id should match"
- assert (
- model_info.get("input_cost_per_token") == 0.002
- ), "input cost should match"
- result = response.json()
- print(f"Received response: {result}")
- print("Passed Embedding custom logger on proxy!")
- except Exception as e:
- pytest.fail(f"LiteLLM Proxy test failed. Exception {str(e)}")
-
-
- os.environ.get("OPENAI_API_KEY") is None,
- reason="OPENAI_API_KEY not set - skipping integration test",
-)
-def test_chat_completion(client):
- try:
- # Your test data
- litellm.set_verbose = False
- from litellm.proxy.types_utils.utils import get_instance_fn
-
- my_custom_logger = get_instance_fn(
- value="custom_callbacks.my_custom_logger", config_file_path=python_file_path
- )
-
- print("id of initialized custom logger", id(my_custom_logger))
-
- litellm.callbacks = [my_custom_logger]
- # import the initialized custom logger
- print(litellm.callbacks)
-
- # assert len(litellm.callbacks) == 1 # assert litellm is initialized with 1 callback
-
- print("LiteLLM Callbacks", litellm.callbacks)
- print("my_custom_logger", my_custom_logger)
- assert my_custom_logger.async_success == False
-
- test_data = {
- "model": "Azure OpenAI GPT-4 Canada",
- "messages": [
- {"role": "user", "content": "write a litellm poem"},
- ],
- "max_tokens": 10,
- }
-
- response = client.post("/chat/completions", json=test_data, headers=headers)
- print("made request", response.status_code, response.text)
- print("LiteLLM Callbacks", litellm.callbacks)
- time.sleep(1) # sleep while waiting for callback to run
-
- print(
- "my_custom_logger in /chat/completions",
- my_custom_logger,
- "id",
- id(my_custom_logger),
- )
- print("vars my custom logger, ", vars(my_custom_logger))
- assert (
- my_custom_logger.async_success == True
- ) # checks if the status of async_success is True, only the async_log_success_event can set this to true
- assert (
- my_custom_logger.async_completion_kwargs["model"] == "gpt-4.1-nano"
- ) # checks if kwargs passed to async_log_success_event are correct
- print(
- "\n\n Custom Logger Async Completion args",
- my_custom_logger.async_completion_kwargs,
- )
- litellm_params = my_custom_logger.async_completion_kwargs.get("litellm_params")
-
- # Test 1: Verify metadata is populated correctly
- metadata = litellm_params.get("metadata", None)
- print("\n\n Metadata in custom logger kwargs", litellm_params.get("metadata"))
- assert metadata is not None, "metadata should be present"
- assert "user_api_key" in metadata, "user_api_key should be in metadata"
- assert (
- "user_api_key_metadata" in metadata
- ), "user_api_key_metadata should be in metadata"
- assert "headers" in metadata, "headers should be in metadata"
-
- # Test 2: Verify model_info is populated
- config_model_info = litellm_params.get("model_info")
- assert config_model_info is not None, "model_info should exist"
- assert config_model_info.get("id") == "gm", "model id should match"
- assert config_model_info.get("mode") == "chat", "mode should be chat"
- assert (
- config_model_info.get("input_cost_per_token") == 0.0002
- ), "input cost should match"
-
- # Test 3: Verify proxy_server_request contains request details
- proxy_server_request_object = litellm_params.get("proxy_server_request")
- assert (
- proxy_server_request_object is not None
- ), "proxy_server_request should exist"
- assert (
- proxy_server_request_object.get("url")
- == "http://testserver/chat/completions"
- ), "url should match"
- assert (
- proxy_server_request_object.get("method") == "POST"
- ), "method should be POST"
-
- # Test 4: Verify authorization is not leaked in logged headers
- assert (
- "authorization" not in proxy_server_request_object["headers"]
- ), "authorization should not be in headers"
-
- # Test 5: Verify request body contains original input data
- body = proxy_server_request_object.get("body", {})
- assert (
- body.get("model") == "Azure OpenAI GPT-4 Canada"
- ), "model should match original request"
- assert body.get("messages") == [
- {"role": "user", "content": "write a litellm poem"}
- ], "messages should match"
- assert body.get("max_tokens") == 10, "max_tokens should match"
- result = response.json()
- print(f"Received response: {result}")
- print("\nPassed /chat/completions with Custom Logger!")
- except Exception as e:
- pytest.fail(f"LiteLLM Proxy test failed. Exception {str(e)}")
-
-
- os.environ.get("OPENAI_API_KEY") is None,
- reason="OPENAI_API_KEY not set - skipping integration test",
-)
-def test_chat_completion_stream(client):
- try:
- # Your test data
- litellm.set_verbose = False
- from litellm.proxy.types_utils.utils import get_instance_fn
-
- my_custom_logger = get_instance_fn(
- value="custom_callbacks.my_custom_logger", config_file_path=python_file_path
- )
-
- print("id of initialized custom logger", id(my_custom_logger))
-
- litellm.callbacks = [my_custom_logger]
- import json
-
- print("initialized proxy")
- # import the initialized custom logger
- print(litellm.callbacks)
-
- print("LiteLLM Callbacks", litellm.callbacks)
- print("my_custom_logger", my_custom_logger)
-
- assert (
- my_custom_logger.streaming_response_obj == None
- ) # no streaming response obj is set pre call
-
- test_data = {
- "model": "Azure OpenAI GPT-4 Canada",
- "messages": [
- {"role": "user", "content": "write 1 line poem about LiteLLM"},
- ],
- "max_tokens": 40,
- "stream": True, # streaming call
- }
-
- response = client.post("/chat/completions", json=test_data, headers=headers)
- print("made request", response.status_code, response.text)
- complete_response = ""
- for line in response.iter_lines():
- if line:
- # Process the streaming data line here
- print("\n\n Line", line)
- print(line)
- line = str(line)
-
- json_data = line.replace("data: ", "")
-
- if "[DONE]" in json_data:
- break
-
- # Parse the JSON string
- data = json.loads(json_data)
-
- print("\n\n decode_data", data)
-
- # Access the content of choices[0]['message']['content']
- content = data["choices"][0]["delta"].get("content", None) or ""
-
- # Process the content as needed
- print("Content:", content)
-
- complete_response += content
-
- print("\n\nHERE is the complete streaming response string", complete_response)
- print("\n\nHERE IS the streaming Response from callback\n\n")
- print(my_custom_logger.streaming_response_obj)
- import time
-
- time.sleep(0.5)
-
- streamed_response = my_custom_logger.streaming_response_obj
- assert (
- complete_response == streamed_response["choices"][0]["message"]["content"]
- )
-
- except Exception as e:
- pytest.fail(f"LiteLLM Proxy test failed. Exception {str(e)}")
diff --git a/tests/proxy_unit_tests/test_proxy_exception_mapping.py b/tests/proxy_unit_tests/test_proxy_exception_mapping.py
deleted file mode 100644
index efaaa181600..00000000000
--- a/tests/proxy_unit_tests/test_proxy_exception_mapping.py
+++ /dev/null
@@ -1,319 +0,0 @@
-# test that the proxy actually does exception mapping to the OpenAI format
-
-import json
-import os
-from unittest import mock
-
-from dotenv import load_dotenv
-
-load_dotenv()
-import asyncio
-import io
-
-import openai
-import pytest
-from fastapi import Response
-from fastapi.testclient import TestClient
-
-import litellm
-from litellm.proxy.proxy_server import ( # Replace with the actual module where your FastAPI router is defined
- initialize,
- router,
- save_worker_config,
-)
-
-invalid_authentication_error_response = Response(
- status_code=401,
- content=json.dumps({"error": "Invalid Authentication"}),
-)
-context_length_exceeded_error_response_dict = {
- "error": {
- "message": "AzureException - Error code: 400 - {'error': {'message': \"This model's maximum context length is 4096 tokens. However, your messages resulted in 10007 tokens. Please reduce the length of the messages.\", 'type': 'invalid_request_error', 'param': 'messages', 'code': 'context_length_exceeded'}}",
- "type": None,
- "param": None,
- "code": 400,
- },
-}
-context_length_exceeded_error_response = Response(
- status_code=400,
- content=json.dumps(context_length_exceeded_error_response_dict),
-)
-
-
-def client():
- filepath = os.path.dirname(os.path.abspath(__file__))
- config_fp = f"{filepath}/test_configs/test_bad_config.yaml"
- asyncio.run(initialize(config=config_fp))
- from litellm.proxy.proxy_server import app
-
- return TestClient(app)
-
-
-# raise openai.AuthenticationError
-def test_chat_completion_exception(client):
- try:
- # Your test data
- test_data = {
- "model": "gpt-3.5-turbo",
- "messages": [
- {"role": "user", "content": "hi"},
- ],
- "max_tokens": 10,
- }
-
- response = client.post("/chat/completions", json=test_data)
-
- json_response = response.json()
- print("keys in json response", json_response.keys())
- assert json_response.keys() == {"error"}
- print("ERROR=", json_response["error"])
- assert isinstance(json_response["error"]["message"], str)
- assert (
- "litellm.AuthenticationError: AuthenticationError"
- in json_response["error"]["message"]
- )
-
- code_in_error = json_response["error"]["code"]
- # OpenAI SDK required code to be STR, https://github.com/BerriAI/litellm/issues/4970
- # If we look on official python OpenAI lib, the code should be a string:
- # https://github.com/openai/openai-python/blob/195c05a64d39c87b2dfdf1eca2d339597f1fce03/src/openai/types/shared/error_object.py#L11
- # Related LiteLLM issue: https://github.com/BerriAI/litellm/discussions/4834
- assert type(code_in_error) == str
-
- # make an openai client to call _make_status_error_from_response
- openai_client = openai.OpenAI(api_key="anything")
- openai_exception = openai_client._make_status_error_from_response(
- response=response
- )
- assert isinstance(openai_exception, openai.AuthenticationError)
-
- except Exception as e:
- pytest.fail(f"LiteLLM Proxy test failed. Exception {str(e)}")
-
-
-# raise openai.AuthenticationError
- "litellm.proxy.proxy_server.llm_router.acompletion",
- return_value=invalid_authentication_error_response,
-)
-def test_chat_completion_exception_azure(mock_acompletion, client):
- try:
- # Your test data
- test_data = {
- "model": "azure-gpt-3.5-turbo",
- "messages": [
- {"role": "user", "content": "hi"},
- ],
- "max_tokens": 10,
- }
-
- response = client.post("/chat/completions", json=test_data)
-
- mock_acompletion.assert_called_once_with(
- **test_data,
- litellm_call_id=mock.ANY,
- litellm_logging_obj=mock.ANY,
- request_timeout=mock.ANY,
- metadata=mock.ANY,
- proxy_server_request=mock.ANY,
- secret_fields=mock.ANY,
- )
-
- json_response = response.json()
- print("keys in json response", json_response.keys())
- assert json_response.keys() == {"error"}
-
- # make an openai client to call _make_status_error_from_response
- openai_client = openai.OpenAI(api_key="anything")
- openai_exception = openai_client._make_status_error_from_response(
- response=response
- )
- print(openai_exception)
- assert isinstance(openai_exception, openai.AuthenticationError)
-
- except Exception as e:
- pytest.fail(f"LiteLLM Proxy test failed. Exception {str(e)}")
-
-
-# raise openai.AuthenticationError
- "litellm.proxy.proxy_server.llm_router.aembedding",
- return_value=invalid_authentication_error_response,
-)
-def test_embedding_auth_exception_azure(mock_aembedding, client):
- try:
- # Your test data
- test_data = {"model": "azure-embedding", "input": ["hi"]}
-
- response = client.post("/embeddings", json=test_data)
- mock_aembedding.assert_called_once_with(
- **test_data,
- metadata=mock.ANY,
- proxy_server_request=mock.ANY,
- secret_fields=mock.ANY,
- request_timeout=mock.ANY,
- litellm_call_id=mock.ANY,
- litellm_logging_obj=mock.ANY,
- )
- print("Response from proxy=", response)
-
- json_response = response.json()
- print("keys in json response", json_response.keys())
- assert json_response.keys() == {"error"}
-
- # make an openai client to call _make_status_error_from_response
- openai_client = openai.OpenAI(api_key="anything")
- openai_exception = openai_client._make_status_error_from_response(
- response=response
- )
- print("Exception raised=", openai_exception)
- assert isinstance(openai_exception, openai.AuthenticationError)
-
- except Exception as e:
- pytest.fail(f"LiteLLM Proxy test failed. Exception {str(e)}")
-
-
-# raise openai.BadRequestError
-# chat/completions openai
-def test_exception_openai_bad_model(client):
- try:
- # Your test data
- test_data = {
- "model": "azure/GPT-12",
- "messages": [
- {"role": "user", "content": "hi"},
- ],
- "max_tokens": 10,
- }
-
- response = client.post("/chat/completions", json=test_data)
-
- json_response = response.json()
- print("keys in json response", json_response.keys())
- assert json_response.keys() == {"error"}
-
- # make an openai client to call _make_status_error_from_response
- openai_client = openai.OpenAI(api_key="anything")
- openai_exception = openai_client._make_status_error_from_response(
- response=response
- )
- print("Type of exception=", type(openai_exception))
- assert isinstance(openai_exception, openai.BadRequestError)
-
- except Exception as e:
- pytest.fail(f"LiteLLM Proxy test failed. Exception {str(e)}")
-
-
-# chat/completions any model
-def test_chat_completion_exception_any_model(client):
- try:
- # Your test data
- test_data = {
- "model": "Lite-GPT-12",
- "messages": [
- {"role": "user", "content": "hi"},
- ],
- "max_tokens": 10,
- }
-
- response = client.post("/chat/completions", json=test_data)
-
- json_response = response.json()
- assert json_response.keys() == {"error"}
-
- # make an openai client to call _make_status_error_from_response
- openai_client = openai.OpenAI(api_key="anything")
- openai_exception = openai_client._make_status_error_from_response(
- response=response
- )
- assert isinstance(openai_exception, openai.BadRequestError)
- _error_message = openai_exception.message
- assert (
- "/chat/completions: Invalid model name passed in model=Lite-GPT-12"
- in str(_error_message)
- )
-
- except Exception as e:
- pytest.fail(f"LiteLLM Proxy test failed. Exception {str(e)}")
-
-
-# embeddings any model
-def test_embedding_exception_any_model(client):
- try:
- # Your test data
- test_data = {"model": "Lite-GPT-12", "input": ["hi"]}
-
- response = client.post("/embeddings", json=test_data)
- print("Response from proxy=", response)
- print(response.json())
-
- json_response = response.json()
- print("keys in json response", json_response.keys())
- assert json_response.keys() == {"error"}
-
- # make an openai client to call _make_status_error_from_response
- openai_client = openai.OpenAI(api_key="anything")
- openai_exception = openai_client._make_status_error_from_response(
- response=response
- )
- print("Exception raised=", openai_exception)
- assert isinstance(openai_exception, openai.BadRequestError)
- _error_message = openai_exception.message
- assert "/embeddings: Invalid model name passed in model=Lite-GPT-12" in str(
- _error_message
- )
-
- except Exception as e:
- pytest.fail(f"LiteLLM Proxy test failed. Exception {str(e)}")
-
-
-# raise openai.BadRequestError
- "litellm.proxy.proxy_server.llm_router.acompletion",
- return_value=context_length_exceeded_error_response,
-)
-def test_chat_completion_exception_azure_context_window(mock_acompletion, client):
- try:
- # Your test data
- test_data = {
- "model": "working-azure-gpt-3.5-turbo",
- "messages": [
- {"role": "user", "content": "hi" * 10000},
- ],
- "max_tokens": 10,
- }
- response = None
-
- response = client.post("/chat/completions", json=test_data)
- print("got response from server", response)
-
- mock_acompletion.assert_called_once_with(
- **test_data,
- litellm_call_id=mock.ANY,
- litellm_logging_obj=mock.ANY,
- request_timeout=mock.ANY,
- metadata=mock.ANY,
- proxy_server_request=mock.ANY,
- secret_fields=mock.ANY,
- )
-
- json_response = response.json()
-
- print("keys in json response", json_response.keys())
-
- assert json_response.keys() == {"error"}
-
- assert json_response == context_length_exceeded_error_response_dict
-
- # make an openai client to call _make_status_error_from_response
- openai_client = openai.OpenAI(api_key="anything")
- openai_exception = openai_client._make_status_error_from_response(
- response=response
- )
- print("exception from proxy", openai_exception)
- assert isinstance(openai_exception, openai.BadRequestError)
- print("passed exception is of type BadRequestError")
-
- except Exception as e:
- pytest.fail(f"LiteLLM Proxy test failed. Exception {str(e)}")
diff --git a/tests/proxy_unit_tests/test_proxy_server_gemini_pass_through.py b/tests/proxy_unit_tests/test_proxy_server_gemini_pass_through.py
deleted file mode 100644
index 97d6b5c7cf3..00000000000
--- a/tests/proxy_unit_tests/test_proxy_server_gemini_pass_through.py
+++ /dev/null
@@ -1,50 +0,0 @@
-import os
-
-import pytest
-
-
- not os.getenv("GEMINI_API_KEY") and not os.getenv("GOOGLE_API_KEY"),
- reason="Requires GEMINI_API_KEY or GOOGLE_API_KEY.",
-)
-async def test_gemini_pass_through_endpoint():
- from litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints import (
- Request,
- Response,
- gemini_proxy_route,
- )
-
- body = b"""
- {
- "contents": [{
- "parts":[{
- "text": "The quick brown fox jumps over the lazy dog."
- }]
- }]
- }
- """
-
- scope = {
- "type": "http",
- "method": "POST",
- "path": "/gemini/v1beta/models/gemini-2.5-flash:countTokens",
- "query_string": b"key=sk-9876",
- "headers": [
- (b"content-type", b"application/json"),
- ],
- }
-
- async def async_receive():
- return {"type": "http.request", "body": body, "more_body": False}
-
- request = Request(
- scope=scope,
- receive=async_receive,
- )
-
- await gemini_proxy_route(
- endpoint="v1beta/models/gemini-2.5-flash:countTokens?key=sk-9876",
- request=request,
- fastapi_response=Response(),
- )
diff --git a/tests/router_unit_tests/README.md b/tests/router_unit_tests/README.md
deleted file mode 100644
index 0206bcbb8f3..00000000000
--- a/tests/router_unit_tests/README.md
+++ /dev/null
@@ -1,5 +0,0 @@
-## Router component unit tests.
-
-Please name all files with the word 'router' in them.
-
-This is used to ensure all functions in the router are tested.
\ No newline at end of file
diff --git a/tests/router_unit_tests/conftest.py b/tests/router_unit_tests/conftest.py
deleted file mode 100644
index cca1028aec7..00000000000
--- a/tests/router_unit_tests/conftest.py
+++ /dev/null
@@ -1,119 +0,0 @@
-# conftest.py
-
-import asyncio
-import importlib
-
-import pytest
-
-import litellm # noqa: E402,F401
-
-from tests._vcr_conftest_common import ( # noqa: E402,F401
- VerboseReporterState,
- _pin_multipart_boundary,
- apply_vcr_auto_marker_to_items,
- emit_cassette_cache_session_banner,
- emit_vcr_classification_summary,
- emit_vcr_diagnostic_log,
- install_live_call_probe,
- record_vcr_outcome,
- register_persister_if_enabled,
- reset_vcr_diag_dir,
- vcr_config_dict,
-)
-
-_verbose_state = VerboseReporterState()
-
-
[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 setup_and_teardown():
- """
- This fixture reloads litellm before every function. To speed up testing by removing callbacks being chained.
- """
-
-
- from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER
-
- # flush all logs
- asyncio.run(GLOBAL_LOGGING_WORKER.clear_queue())
-
- importlib.reload(litellm)
-
- try:
- if hasattr(litellm, "proxy") and hasattr(litellm.proxy, "proxy_server"):
- importlib.reload(litellm.proxy.proxy_server)
- except Exception as e:
- print(f"Error reloading litellm.proxy.proxy_server: {e}")
-
- loop = asyncio.get_event_loop_policy().new_event_loop()
- asyncio.set_event_loop(loop)
- print(litellm)
- 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
-
-
[email protected](scope="module")
-def vcr_config():
- return vcr_config_dict()
-
-
-def pytest_recording_configure(config, vcr):
- register_persister_if_enabled(vcr)
-
-
[email protected](hookwrapper=True)
-def pytest_runtest_makereport(item, call):
- outcome = yield
- rep = outcome.get_result()
- setattr(item, f"rep_{rep.when}", rep)
-
-
[email protected](autouse=True)
-def _vcr_outcome_gate(request, vcr):
- install_live_call_probe(request, vcr)
- yield
- record_vcr_outcome(request, vcr)
-
-
-def pytest_configure(config):
- _verbose_state.remember_pluginmanager(config)
- reset_vcr_diag_dir()
-
-
-def pytest_runtest_logreport(report):
- _verbose_state.maybe_emit_verdict(report)
-
-
-def pytest_collection_modifyitems(config, items):
- apply_vcr_auto_marker_to_items(items)
-
- # Separate tests in 'test_amazing_proxy_custom_logger.py' and other tests
- custom_logger_tests = [
- item for item in items if "custom_logger" in item.parent.name
- ]
- other_tests = [item for item in items if "custom_logger" not in item.parent.name]
-
- # Sort tests based on their names
- custom_logger_tests.sort(key=lambda x: x.name)
- other_tests.sort(key=lambda x: x.name)
-
- # Reorder the items list
- items[:] = custom_logger_tests + other_tests
-
-
-def pytest_terminal_summary(terminalreporter, exitstatus, config):
- emit_cassette_cache_session_banner(terminalreporter)
- emit_vcr_classification_summary(terminalreporter)
- emit_vcr_diagnostic_log(terminalreporter)
diff --git a/tests/router_unit_tests/create_mock_standard_logging_payload.py b/tests/router_unit_tests/create_mock_standard_logging_payload.py
deleted file mode 100644
index 096c8ff8c60..00000000000
--- a/tests/router_unit_tests/create_mock_standard_logging_payload.py
+++ /dev/null
@@ -1,128 +0,0 @@
-import io
-
-
-
-import asyncio
-import gzip
-import json
-import logging
-import time
-from unittest.mock import AsyncMock, patch
-
-import pytest
-
-import litellm
-from litellm import completion
-from litellm._logging import verbose_logger
-from litellm.integrations.datadog.datadog import *
-from datetime import datetime, timedelta
-from litellm.types.utils import (
- StandardLoggingPayload,
- StandardLoggingModelInformation,
- StandardLoggingMetadata,
- StandardLoggingHiddenParams,
-)
-
-verbose_logger.setLevel(logging.DEBUG)
-
-
-def create_standard_logging_payload() -> StandardLoggingPayload:
- return StandardLoggingPayload(
- id="test_id",
- call_type="completion",
- response_cost=0.1,
- response_cost_failure_debug_info=None,
- status="success",
- total_tokens=30,
- prompt_tokens=20,
- completion_tokens=10,
- startTime=1234567890.0,
- endTime=1234567891.0,
- completionStartTime=1234567890.5,
- model_map_information=StandardLoggingModelInformation(
- model_map_key="gpt-5-mini", model_map_value=None
- ),
- model="gpt-5-mini",
- model_id="model-123",
- model_group="openai-gpt",
- api_base="https://api.openai.com",
- metadata=StandardLoggingMetadata(
- user_api_key_hash="test_hash",
- user_api_key_org_id=None,
- user_api_key_alias="test_alias",
- user_api_key_team_id="test_team",
- user_api_key_user_id="test_user",
- user_api_key_team_alias="test_team_alias",
- spend_logs_metadata=None,
- requester_ip_address="127.0.0.1",
- requester_metadata=None,
- ),
- cache_hit=False,
- cache_key=None,
- saved_cache_cost=0.0,
- request_tags=[],
- end_user=None,
- requester_ip_address="127.0.0.1",
- messages=[{"role": "user", "content": "Hello, world!"}],
- response={"choices": [{"message": {"content": "Hi there!"}}]},
- error_str=None,
- model_parameters={"stream": True},
- hidden_params=StandardLoggingHiddenParams(
- model_id="model-123",
- cache_key=None,
- api_base="https://api.openai.com",
- response_cost="0.1",
- additional_headers=None,
- ),
- )
-
-
-def create_standard_logging_payload_with_long_content() -> StandardLoggingPayload:
- return StandardLoggingPayload(
- id="test_id",
- call_type="completion",
- response_cost=0.1,
- response_cost_failure_debug_info=None,
- status="success",
- total_tokens=30,
- prompt_tokens=20,
- completion_tokens=10,
- startTime=1234567890.0,
- endTime=1234567891.0,
- completionStartTime=1234567890.5,
- model_map_information=StandardLoggingModelInformation(
- model_map_key="gpt-5-mini", model_map_value=None
- ),
- model="gpt-5-mini",
- model_id="model-123",
- model_group="openai-gpt",
- api_base="https://api.openai.com",
- metadata=StandardLoggingMetadata(
- user_api_key_hash="test_hash",
- user_api_key_org_id=None,
- user_api_key_alias="test_alias",
- user_api_key_team_id="test_team",
- user_api_key_user_id="test_user",
- user_api_key_team_alias="test_team_alias",
- spend_logs_metadata=None,
- requester_ip_address="127.0.0.1",
- requester_metadata=None,
- ),
- cache_hit=False,
- cache_key=None,
- saved_cache_cost=0.0,
- request_tags=[],
- end_user=None,
- requester_ip_address="127.0.0.1",
- messages=[{"role": "user", "content": "Hello, world!" * 80000}],
- response={"choices": [{"message": {"content": "Hi there!" * 80000}}]},
- error_str="error_str" * 80000,
- model_parameters={"stream": True},
- hidden_params=StandardLoggingHiddenParams(
- model_id="model-123",
- cache_key=None,
- api_base="https://api.openai.com",
- response_cost="0.1",
- additional_headers=None,
- ),
- )
diff --git a/tests/router_unit_tests/test_router_prompt_caching.py b/tests/router_unit_tests/test_router_prompt_caching.py
deleted file mode 100644
index 329ea9f3931..00000000000
--- a/tests/router_unit_tests/test_router_prompt_caching.py
+++ /dev/null
@@ -1,136 +0,0 @@
-import asyncio
-
-import pytest
-
-from litellm import Router
-from litellm.router_utils.prompt_caching_cache import PromptCachingCache
-
-
-async def test_router_prompt_caching_same_cacheable_prefix_routes_to_same_deployment():
- """
- End-to-end test to validate prompt caching routing through LiteLLM Router.
-
- Tests that requests with same cacheable content but different user messages
- route to the same deployment (for prompt caching).
-
- This reproduces the issue where requests with same cacheable prefix but different
- user messages should route to the same deployment, but previously didn't because
- the cache key included the entire messages array instead of just the cacheable prefix.
- """
- from litellm.types.llms.openai import AllMessageValues
-
- def create_messages(user_content: str) -> list[AllMessageValues]:
- """
- Create messages matching the user's exact scenario.
-
- Message structure:
- - BLOCK 1: System message, first content block (no cache_control)
- → INCLUDED (comes before the last cacheable block)
- - BLOCK 2: System message, second content block (WITH cache_control)
- → INCLUDED (this IS the last cacheable block)
- - USER MESSAGE: User message (no cache_control)
- → NOT included (comes after last cacheable block)
- """
- return [
- {
- "role": "system",
- "content": [
- # BLOCK 1: No cache_control → INCLUDED (all blocks up to last cacheable are included)
- {
- "type": "text",
- "text": "You are an AI assistant tasked with analyzing legal documents.",
- },
- # BLOCK 2: Has cache_control → INCLUDED (this is the last cacheable block)
- {
- "type": "text",
- "text": "Here 3 is the full text of a complex legal agreement"
- * 400,
- "cache_control": {"type": "ephemeral"},
- },
- ],
- },
- {
- "role": "user",
- # USER MESSAGE: No cache_control → NOT included (comes after last cacheable block)
- "content": user_content,
- },
- ]
-
- # Create router with multiple deployments
- router = Router(
- model_list=[
- {
- "model_name": "test-model",
- "litellm_params": {
- "model": "gpt-5-mini",
- "api_base": "https://exampleopenaiendpoint-production-0ee2.up.railway.app/v1",
- "api_key": f"test-key-{i}",
- },
- "model_info": {"id": f"deployment-{i}"},
- }
- for i in range(1, 4)
- ],
- routing_strategy="simple-shuffle",
- optional_pre_call_checks=["prompt_caching"],
- )
-
- # Create test messages matching user's exact scenario
- # Same cacheable prefix (system blocks 1+2) but different user messages
- messages1 = create_messages(
- "what are the key terms and conditions in this agreement?"
- )
- messages2 = create_messages("how many words are there?")
- messages3 = create_messages("how many sentences are there?")
-
- cache = PromptCachingCache(cache=router.cache)
-
- # Test 1: Cache keys should be same (same cacheable prefix, different user messages)
- key1 = PromptCachingCache.get_prompt_caching_cache_key(messages1, None)
- key2 = PromptCachingCache.get_prompt_caching_cache_key(messages2, None)
- key3 = PromptCachingCache.get_prompt_caching_cache_key(messages3, None)
-
- assert key1 is not None, "Cache key should not be None"
- assert (
- key1 == key2 == key3
- ), "Cache keys should be the same for same cacheable prefix"
-
- # Make first request
- try:
- response1 = await router.acompletion(model="test-model", messages=messages1)
- model_id_1 = response1._hidden_params.get("model_id", "unknown")
- except Exception:
- # If API call fails, we can still test the cache key logic
- model_id_1 = "unknown"
-
- await asyncio.sleep(1) # Wait for cache write
-
- # Test 2: Cache lookup should work for messages2 (same cacheable prefix)
- cached_2 = await cache.async_get_model_id(messages2, None)
- # Cache should be found if first request succeeded
- if model_id_1 != "unknown":
- assert (
- cached_2 is not None
- ), "Cache lookup should work for same cacheable prefix"
-
- # Make second request
- try:
- response2 = await router.acompletion(model="test-model", messages=messages2)
- model_id_2 = response2._hidden_params.get("model_id", "unknown")
- except Exception:
- model_id_2 = "unknown"
-
- await asyncio.sleep(1) # Wait for cache write
-
- # Make third request
- try:
- response3 = await router.acompletion(model="test-model", messages=messages3)
- model_id_3 = response3._hidden_params.get("model_id", "unknown")
- except Exception:
- model_id_3 = "unknown"
-
- # Test 3: All requests should route to same deployment (if API calls succeeded)
- if model_id_1 != "unknown" and model_id_2 != "unknown" and model_id_3 != "unknown":
- assert (
- model_id_1 == model_id_2 == model_id_3
- ), f"All requests should route to same deployment, but got: {model_id_1}, {model_id_2}, {model_id_3}"
diff --git a/tests/test_litellm/__init__.py b/tests/test_litellm/__init__.py
deleted file mode 100644
index 7f5464af889..00000000000
--- a/tests/test_litellm/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-# This file makes the tests/litellm directory a Python package
diff --git a/tests/test_litellm/conftest.py b/tests/test_litellm/conftest.py
deleted file mode 100644
index bd38d3b02e8..00000000000
--- a/tests/test_litellm/conftest.py
+++ /dev/null
@@ -1,598 +0,0 @@
-# conftest.py - IMPROVED VERSION
-#
-# Key changes:
-# 1. Changed module reload from 'module' scope to 'function' scope for better isolation
-# 2. Made cache flushing happen per-function instead of per-module
-# 3. Removed manual event loop creation (let pytest-asyncio handle it)
-# 4. Added proper cleanup in fixtures
-# 5. Added worker-specific isolation for parallel execution
-
-import base64
-import importlib
-import os
-from pathlib import Path
-from types import SimpleNamespace
-import httpx
-import pytest
-from pytest_socket import _remove_restrictions
-
-import asyncio
-
-import litellm
-from litellm import router as litellm_router_module
-from litellm import utils as litellm_utils_module
-from litellm._logging import ALL_LOGGERS
-from litellm.litellm_core_utils.prompt_templates import (
- image_handling as image_handling_module,
-)
-from litellm.llms.custom_httpx.async_client_cleanup import (
- close_litellm_async_clients,
-)
-from litellm.proxy.db import tool_registry_writer as tool_registry_writer_module
-from tests.unit.litellm_core_utils.fake_secret_vault import FakeSecretVault
-
-
-def _reset_module_level_aws_auth_caches():
- """
- Clear module-level AWS auth state that can survive between tests.
-
- Bedrock/SageMaker handlers are instantiated once at import time and cache
- resolved credentials on the handler instance. If a previous test resolves an
- invalid or different auth flow, later tests can reuse that cached state and
- bypass their local monkeypatched env setup.
- """
- for module_name in (
- "litellm.main",
- "litellm.files.main",
- "litellm.rerank_api.main",
- "litellm.realtime_api.main",
- ):
- try:
- module = importlib.import_module(module_name)
- except Exception:
- continue
- for attr_name in dir(module):
- obj = getattr(module, attr_name)
- iam_cache = getattr(obj, "iam_cache", None)
- if iam_cache is None:
- continue
- flush_cache = getattr(iam_cache, "flush_cache", None)
- if callable(flush_cache):
- flush_cache()
-
- try:
- import boto3
-
- boto3.DEFAULT_SESSION = None
- except Exception:
- pass
-
-
[email protected](scope="session")
-def isolated_aws_credentials_dir(tmp_path_factory):
- aws_dir = tmp_path_factory.mktemp("aws-config")
- credentials_file = Path(aws_dir) / "credentials"
- config_file = Path(aws_dir) / "config"
- credentials_file.write_text("", encoding="utf-8")
- config_file.write_text("", encoding="utf-8")
- return {
- "credentials": str(credentials_file),
- "config": str(config_file),
- }
-
-
[email protected](scope="function", autouse=True)
-def isolate_host_aws_config(monkeypatch, isolated_aws_credentials_dir):
- """Prevent botocore from reading host AWS profiles during unit tests."""
- monkeypatch.setenv(
- "AWS_SHARED_CREDENTIALS_FILE", isolated_aws_credentials_dir["credentials"]
- )
- monkeypatch.setenv("AWS_CONFIG_FILE", isolated_aws_credentials_dir["config"])
- monkeypatch.setenv("AWS_EC2_METADATA_DISABLED", "true")
- monkeypatch.delenv("AWS_PROFILE", raising=False)
- monkeypatch.delenv("AWS_DEFAULT_PROFILE", raising=False)
- monkeypatch.delenv("AWS_CONTAINER_CREDENTIALS_FULL_URI", raising=False)
- monkeypatch.delenv("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", raising=False)
- monkeypatch.delenv("AWS_SESSION_TOKEN", raising=False)
- monkeypatch.delenv("AWS_ROLE_ARN", raising=False)
- monkeypatch.delenv("AWS_WEB_IDENTITY_TOKEN_FILE", raising=False)
- monkeypatch.delenv("AWS_BEARER_TOKEN_BEDROCK", raising=False)
- monkeypatch.delenv("AWS_REGION_NAME", raising=False)
- monkeypatch.delenv("AWS_DEFAULT_REGION", raising=False)
-
-
[email protected](scope="function", autouse=True)
-def isolate_host_proxy_base_url(monkeypatch):
- """Prevent a host PROXY_BASE_URL from outranking request-derived URLs during unit tests."""
- monkeypatch.delenv("PROXY_BASE_URL", raising=False)
-
-
[email protected](scope="function", autouse=True)
-def isolate_host_os_keychain(monkeypatch):
- """Keep any code path that resolves a CLI credential out of the developer's real OS keychain.
-
- Tests that exercise keychain behaviour inject their own vault instead.
- """
- monkeypatch.setenv("LITELLM_CLI_DISABLE_KEYRING", "1")
-
-
-def secret_vault_factory():
- """Build FakeSecretVault instances; see its docstring for the failure modes it can model."""
- return FakeSecretVault
-
-
-def local_model_cost_map(monkeypatch):
- """Force the bundled in-repo cost map so capability and pricing assertions do not
- depend on the network-fetched ``main`` copy, which lags this branch until merge.
-
- ``get_model_info`` is lru_cached, so swapping ``model_cost`` is not enough on its
- own; clear on the way in and out so entries warmed against either map never leak
- across tests."""
- original_model_cost = litellm.model_cost
- monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True")
- litellm.model_cost = litellm.get_model_cost_map(url="")
- litellm.get_model_info.cache_clear()
- try:
- yield
- finally:
- litellm.model_cost = original_model_cost
- litellm.get_model_info.cache_clear()
-
-
-def local_beta_headers_config(monkeypatch):
- """Pin the bundled ``anthropic_beta_headers_config.json`` so beta header assertions
- do not depend on the network-fetched copy or on what earlier tests left cached."""
- from litellm.anthropic_beta_headers_manager import reload_beta_headers_config
-
- monkeypatch.setenv("LITELLM_LOCAL_ANTHROPIC_BETA_HEADERS", "True")
- reload_beta_headers_config()
- try:
- yield
- finally:
- monkeypatch.delenv("LITELLM_LOCAL_ANTHROPIC_BETA_HEADERS", raising=False)
- reload_beta_headers_config()
-
-
-def _run_coroutine_if_needed(result):
- if not asyncio.iscoroutine(result):
- return
-
- try:
- asyncio.run(result)
- except RuntimeError:
- # If pytest-asyncio already has a running loop, best-effort scheduling is
- # still better than leaking the client entirely.
- try:
- loop = asyncio.get_running_loop()
- except RuntimeError:
- return
- if loop.is_running():
- loop.create_task(result)
- except Exception:
- pass
-
-
-def _close_handler_if_needed(handler):
- if handler is None:
- return
-
- close_fn = getattr(handler, "close", None)
- if not callable(close_fn):
- return
-
- try:
- result = close_fn()
- _run_coroutine_if_needed(result)
- except Exception:
- pass
-
-
[email protected](scope="function", autouse=True)
-def isolate_litellm_state():
- """
- Per-function isolation fixture (changed from module scope).
-
- This ensures better isolation when running tests in parallel:
- - Each test function gets a clean litellm state
- - Cache is flushed before each test
- - No module reloading during parallel execution
-
- Note: Module reloading at function scope is safer for parallel execution
- but adds overhead. Consider removing reload entirely if tests can work without it.
- """
- # Get worker ID if running with pytest-xdist
- worker_id = os.environ.get("PYTEST_XDIST_WORKER", "master")
-
- # Store original callback state (all callback lists)
- original_state = {}
- if hasattr(litellm, "callbacks"):
- original_state["callbacks"] = (
- litellm.callbacks.copy() if litellm.callbacks else []
- )
- if hasattr(litellm, "success_callback"):
- original_state["success_callback"] = (
- litellm.success_callback.copy() if litellm.success_callback else []
- )
- if hasattr(litellm, "failure_callback"):
- original_state["failure_callback"] = (
- litellm.failure_callback.copy() if litellm.failure_callback else []
- )
- if hasattr(litellm, "input_callback"):
- original_state["input_callback"] = (
- litellm.input_callback.copy() if litellm.input_callback else []
- )
- if hasattr(litellm, "_async_success_callback"):
- original_state["_async_success_callback"] = (
- litellm._async_success_callback.copy()
- if litellm._async_success_callback
- else []
- )
- if hasattr(litellm, "_async_failure_callback"):
- original_state["_async_failure_callback"] = (
- litellm._async_failure_callback.copy()
- if litellm._async_failure_callback
- else []
- )
- if hasattr(litellm, "_async_input_callback"):
- original_state["_async_input_callback"] = (
- litellm._async_input_callback.copy()
- if litellm._async_input_callback
- else []
- )
-
- # Store routing globals — leaked model_fallbacks causes tests to route
- # through async_completion_with_fallbacks / Router, bypassing HTTP mocks
- if hasattr(litellm, "model_fallbacks"):
- original_state["model_fallbacks"] = litellm.model_fallbacks
-
- # Store transport/network globals — many tests set these without restoring,
- # causing subsequent tests to get None from create_async_transport()
- for _attr in ("disable_aiohttp_transport", "force_ipv4"):
- if hasattr(litellm, _attr):
- original_state[_attr] = getattr(litellm, _attr)
-
- # Store request-mapping globals that are frequently mutated in tests.
- if hasattr(litellm, "drop_params"):
- original_state["drop_params"] = litellm.drop_params
- if hasattr(litellm, "cache"):
- original_state["cache"] = litellm.cache
-
- # Store secret-manager globals. Several tests swap these out, which changes
- # get_secret() behavior for later env-driven tests (for example Redis config).
- for _attr in (
- "secret_manager_client",
- "_key_management_system",
- "_key_management_settings",
- ):
- if hasattr(litellm, _attr):
- original_state[_attr] = getattr(litellm, _attr)
-
- # Store other commonly-mutated LiteLLM globals that affect provider routing,
- # auth, and request shaping during larger suite runs.
- for _attr in (
- "api_base",
- "num_retries",
- "modify_params",
- "ssl_verify",
- "credential_list",
- "model_group_settings",
- "default_internal_user_params",
- "default_team_params",
- "prometheus_emit_stream_label",
- "vector_store_registry",
- "model_cost",
- "cost_margin_config",
- "cost_discount_config",
- "disable_hf_tokenizer_download",
- "disable_copilot_system_to_assistant",
- "cohere_models",
- "anthropic_models",
- "token_counter",
- "initialized_langfuse_clients",
- ):
- if hasattr(litellm, _attr):
- original_state[_attr] = getattr(litellm, _attr)
-
- original_runtime_registered_model_cost = {
- model_key: dict(model_value)
- for model_key, model_value in litellm_utils_module._runtime_registered_model_cost.items()
- }
-
- original_live_routers = set(litellm_router_module._live_routers)
-
- # Store LiteLLM logger state. Some tests reconfigure handlers/propagation for
- # JSON logging and do not restore them, which breaks later caplog-based tests.
- logger_state = {}
- for logger in ALL_LOGGERS:
- logger_state[logger.name] = {
- "level": logger.level,
- "disabled": logger.disabled,
- "propagate": logger.propagate,
- "handlers": list(logger.handlers),
- "filters": list(logger.filters),
- }
-
- # Store singleton registries that are lazily initialized during tests and
- # can change endpoint behavior later in the suite.
- original_tool_policy_registry = tool_registry_writer_module._tool_policy_registry
- had_module_level_client = "module_level_client" in litellm.__dict__
- had_module_level_aclient = "module_level_aclient" in litellm.__dict__
- original_module_level_client = litellm.__dict__.get("module_level_client")
- original_module_level_aclient = litellm.__dict__.get("module_level_aclient")
-
- # Flush cache before test (critical for respx mocks)
- if hasattr(litellm, "in_memory_llm_clients_cache"):
- litellm.in_memory_llm_clients_cache.flush_cache()
- image_handling_module.in_memory_cache.flush_cache()
- _reset_module_level_aws_auth_caches()
- # litellm.get_model_info() memoizes ModelInfo built from litellm.model_cost, so a
- # test that rebinds the cost map leaves later tests pricing against the old map.
- litellm_utils_module._invalidate_model_cost_lowercase_map()
-
- # Clear all callback lists to prevent cross-test contamination
- if hasattr(litellm, "callbacks"):
- litellm.callbacks = []
- if hasattr(litellm, "success_callback"):
- litellm.success_callback = []
- if hasattr(litellm, "failure_callback"):
- litellm.failure_callback = []
- if hasattr(litellm, "input_callback"):
- litellm.input_callback = []
- if hasattr(litellm, "_async_success_callback"):
- litellm._async_success_callback = []
- if hasattr(litellm, "_async_failure_callback"):
- litellm._async_failure_callback = []
- if hasattr(litellm, "_async_input_callback"):
- litellm._async_input_callback = []
-
- # Clear routing globals
- if hasattr(litellm, "model_fallbacks"):
- litellm.model_fallbacks = None
- if hasattr(litellm, "cache"):
- litellm.cache = None
- litellm.__dict__.pop("module_level_client", None)
- litellm.__dict__.pop("module_level_aclient", None)
- tool_registry_writer_module._tool_policy_registry = None
-
- yield
-
- # Cleanup after test
- if hasattr(litellm, "in_memory_llm_clients_cache"):
- litellm.in_memory_llm_clients_cache.flush_cache()
- image_handling_module.in_memory_cache.flush_cache()
- _reset_module_level_aws_auth_caches()
- current_module_level_client = litellm.__dict__.get("module_level_client")
- current_module_level_aclient = litellm.__dict__.get("module_level_aclient")
-
- # Restore all callback lists to original state
- for attr_name, original_value in original_state.items():
- if hasattr(litellm, attr_name):
- setattr(litellm, attr_name, original_value)
-
- litellm_utils_module._runtime_registered_model_cost.clear()
- litellm_utils_module._runtime_registered_model_cost.update(original_runtime_registered_model_cost)
- litellm_utils_module._invalidate_model_cost_lowercase_map()
-
- for _router in tuple(litellm_router_module._live_routers):
- litellm_router_module._live_routers.discard(_router)
- for _router in original_live_routers:
- litellm_router_module._live_routers.add(_router)
-
- # Restore logger configuration mutated by logging-focused tests.
- for logger in ALL_LOGGERS:
- original_logger_state = logger_state.get(logger.name)
- if original_logger_state is None:
- continue
- logger.setLevel(original_logger_state["level"])
- logger.disabled = original_logger_state["disabled"]
- logger.propagate = original_logger_state["propagate"]
- logger.handlers = list(original_logger_state["handlers"])
- logger.filters = list(original_logger_state["filters"])
-
- tool_registry_writer_module._tool_policy_registry = original_tool_policy_registry
- if current_module_level_client is not original_module_level_client:
- _close_handler_if_needed(current_module_level_client)
- if current_module_level_aclient is not original_module_level_aclient:
- _close_handler_if_needed(current_module_level_aclient)
- if had_module_level_client:
- litellm.__dict__["module_level_client"] = original_module_level_client
- else:
- litellm.__dict__.pop("module_level_client", None)
- if had_module_level_aclient:
- litellm.__dict__["module_level_aclient"] = original_module_level_aclient
- else:
- litellm.__dict__.pop("module_level_aclient", None)
-
-
[email protected](scope="module", autouse=True)
-def setup_and_teardown():
- """
- Module-scoped setup/teardown for heavy initialization.
-
- Use this sparingly - most state should be handled by isolate_litellm_state.
- Only reload modules here if absolutely necessary.
- """
-
- import litellm
-
- # Only reload if NOT running in parallel (module reload + parallel = bad)
- worker_id = os.environ.get("PYTEST_XDIST_WORKER", None)
- if worker_id is None:
- # Single process mode - safe to reload
- importlib.reload(litellm)
-
- 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}")
-
- # Flush cache after reload (prevents stale client instances)
- if hasattr(litellm, "in_memory_llm_clients_cache"):
- litellm.in_memory_llm_clients_cache.flush_cache()
-
- print(f"[conftest] Module setup complete (worker: {worker_id or 'master'})")
-
- yield
-
- # Teardown - no need to manually manage event loops with pytest-asyncio auto mode
- print(f"[conftest] Module teardown complete (worker: {worker_id or 'master'})")
-
-
-def pytest_collectstart():
- _remove_restrictions()
-
-
-def pytest_runtest_setup():
- _remove_restrictions()
-
-
-def pytest_collection_modifyitems(config, items):
- """
- Customize test collection order.
-
- - Separate tests marked with 'no_parallel' from parallelizable tests
- - Sort custom_logger tests first (they tend to interfere with other tests)
- """
- # Separate no_parallel tests
- no_parallel_tests = [
- item
- for item in items
- if any(mark.name == "no_parallel" for mark in item.iter_markers())
- ]
-
- # Separate custom_logger tests
- custom_logger_tests = [
- item
- for item in items
- if "custom_logger" in item.parent.name and item not in no_parallel_tests
- ]
-
- # Everything else
- other_tests = [
- item
- for item in items
- if item not in no_parallel_tests and item not in custom_logger_tests
- ]
-
- # Sort each group
- custom_logger_tests.sort(key=lambda x: x.name)
- other_tests.sort(key=lambda x: x.name)
- no_parallel_tests.sort(key=lambda x: x.name)
-
- # Reorder: custom_logger first (isolated), then other tests, then no_parallel tests last
- items[:] = custom_logger_tests + other_tests + no_parallel_tests
-
-
-def pytest_configure(config):
- """
- Configure pytest with custom settings.
- """
- # Add marker for flaky tests (for documentation purposes)
- config.addinivalue_line(
- "markers", "flaky: mark test as potentially flaky (should use --reruns)"
- )
-
- # Detect if running in CI
- is_ci = os.environ.get("CI") == "true" or os.environ.get("LITELLM_CI") == "true"
- if is_ci:
- print("[conftest] Running in CI mode - enabling stricter test isolation")
-
-
-# Optional: Add a fixture for tests that need even stricter isolation
-def strict_isolation():
- """
- Use this fixture for tests that need extra strict isolation.
-
- Example:
- def test_something(strict_isolation):
- # Test code with guaranteed clean state
- pass
- """
- # Force flush all caches
- if hasattr(litellm, "in_memory_llm_clients_cache"):
- litellm.in_memory_llm_clients_cache.flush_cache()
-
- # Reset all global state
- if hasattr(litellm, "disable_aiohttp_transport"):
- original_aiohttp = litellm.disable_aiohttp_transport
- litellm.disable_aiohttp_transport = False
- else:
- original_aiohttp = None
-
- if hasattr(litellm, "set_verbose"):
- original_verbose = litellm.set_verbose
- litellm.set_verbose = False
- else:
- original_verbose = None
-
- yield
-
- # Restore original state
- if original_aiohttp is not None:
- litellm.disable_aiohttp_transport = original_aiohttp
- if original_verbose is not None:
- litellm.set_verbose = original_verbose
-
- # Final cache flush
- if hasattr(litellm, "in_memory_llm_clients_cache"):
- litellm.in_memory_llm_clients_cache.flush_cache()
-
-
-def pytest_sessionfinish(session, exitstatus):
- """Close any globally cached HTTP clients so xdist workers exit cleanly."""
- _close_handler_if_needed(litellm.__dict__.get("module_level_client"))
- _close_handler_if_needed(litellm.__dict__.get("module_level_aclient"))
- litellm.__dict__.pop("module_level_client", None)
- litellm.__dict__.pop("module_level_aclient", None)
- _close_handler_if_needed(getattr(litellm, "base_llm_aiohttp_handler", None))
- _close_handler_if_needed(getattr(litellm, "httpx_client", None))
- _close_handler_if_needed(getattr(litellm, "aclient", None))
- _close_handler_if_needed(getattr(litellm, "client", None))
- _run_coroutine_if_needed(close_litellm_async_clients())
-
-
-ONE_PIXEL_PNG = base64.b64decode(
- "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="
-)
-
-
-def async_only_image_fetch(monkeypatch):
- from litellm.litellm_core_utils.prompt_templates import factory, image_handling
- from litellm.llms.gemini.chat import transformation as gemini_chat_transformation
-
- fetch = SimpleNamespace(
- fetched=[],
- base64_png=base64.b64encode(ONE_PIXEL_PNG).decode(),
- data_url="data:image/png;base64," + base64.b64encode(ONE_PIXEL_PNG).decode(),
- )
-
- def forbid_sync_fetch(client, url, **kwargs):
- raise litellm.ImageFetchError(f"sync image fetch ran on the event loop: {url}")
-
- async def serve_png(client, url, **kwargs):
- fetch.fetched.append(url)
- return httpx.Response(
- 200,
- content=ONE_PIXEL_PNG,
- headers={"content-type": "image/png"},
- request=httpx.Request("GET", url),
- )
-
- def forbid_sync_convert(url, *args, **kwargs):
- if url.startswith(("http://", "https://")):
- raise litellm.ImageFetchError(f"sync convert_url_to_base64 ran on the request path: {url}")
- return url
-
- monkeypatch.setattr(image_handling, "safe_get", forbid_sync_fetch)
- monkeypatch.setattr(image_handling, "async_safe_get", serve_png)
- for module in (image_handling, factory, gemini_chat_transformation):
- monkeypatch.setattr(module, "convert_url_to_base64", forbid_sync_convert)
- return fetch
diff --git a/tests/test_litellm/readme.md b/tests/test_litellm/readme.md
deleted file mode 100644
index d126ea8e75b..00000000000
--- a/tests/test_litellm/readme.md
+++ /dev/null
@@ -1,24 +0,0 @@
-# Testing for `litellm/`
-
-This directory 1:1 maps the the `litellm/` directory, and can only contain mocked tests.
-
-The point of this is to:
-1. Increase test coverage of `litellm/`
-2. Make it easy for contributors to add tests for the `litellm/` package and easily run tests without needing LLM API keys.
-
-
-## File name conventions
-
-- `litellm/proxy/test_caching_routes.py` maps to `litellm/proxy/caching_routes.py`
-- `test_<filename>.py` maps to `litellm/<filename>.py`
-
-
-
-
-
-
-
-
-
-
-
diff --git a/tests/unit/a2a_protocol/test_completion_bridge_streaming.py b/tests/unit/a2a_protocol/test_completion_bridge_streaming.py
index 913c917bd2d..5ed2cf0aeb6 100644
--- a/tests/unit/a2a_protocol/test_completion_bridge_streaming.py
+++ b/tests/unit/a2a_protocol/test_completion_bridge_streaming.py
@@ -363,3 +363,79 @@ async def test_handle_streaming_keeps_agent_card_path_out_of_the_completion_call
assert len(events) == 4
assert "agent_card_path" not in mock_acompletion.call_args.kwargs
+
+
+AGENTCORE_ARN = "arn:aws:bedrock-agentcore:us-west-2:123456789012:runtime/unit-agent-abc123"
+AGENTCORE_INVOCATIONS_URL = (
+ "https://bedrock-agentcore.us-west-2.amazonaws.com/runtimes/"
+ + AGENTCORE_ARN.replace(":", "%3A").replace("/", "%2F")
+ + "/invocations"
+)
+
+
+async def test_a2a_completion_bridge_bedrock_agentcore(respx_mock, monkeypatch):
+ """
+ A2A streaming via the completion bridge against a scripted Bedrock AgentCore
+ upstream: asserts the outbound invocation request and the emitted A2A event
+ sequence.
+ """
+ import litellm
+
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ import httpx
+ from a2a.compat.v0_3.types import MessageSendParams, SendStreamingMessageRequest
+ from uuid import uuid4
+
+ from litellm.a2a_protocol import asend_message_streaming
+
+ sse_body = (
+ 'data: {"id":"chatcmpl-1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":"Machine "}}]}\n\n'
+ 'data: {"id":"chatcmpl-1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"learning."}}]}\n\n'
+ 'data: {"id":"chatcmpl-1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}\n\n'
+ "data: [DONE]\n\n"
+ )
+ invoke_route = respx_mock.post(
+ url__regex=r"https://bedrock-agentcore\.us-west-2\.amazonaws\.com/runtimes/.*/invocations.*"
+ ).mock(
+ return_value=httpx.Response(200, content=sse_body.encode(), headers={"content-type": "text/event-stream"})
+ )
+
+ send_message_payload = {
+ "message": {
+ "role": "user",
+ "parts": [{"kind": "text", "text": "Explain machine learning in simple terms"}],
+ "messageId": uuid4().hex,
+ }
+ }
+ request = SendStreamingMessageRequest(
+ id=str(uuid4()),
+ params=MessageSendParams(**send_message_payload), # type: ignore
+ )
+
+ chunks = []
+ async for chunk in asend_message_streaming(
+ request=request,
+ api_base=None,
+ litellm_params={
+ "custom_llm_provider": "bedrock",
+ "model": f"bedrock/agentcore/{AGENTCORE_ARN}",
+ "api_key": "unit-jwt-token",
+ },
+ ):
+ chunks.append(chunk)
+
+ assert invoke_route.call_count == 1
+ invoke_request = invoke_route.calls.last.request
+ encoded_arn = AGENTCORE_ARN.replace(":", "%3A").replace("/", "%2F")
+ assert encoded_arn in str(invoke_request.url)
+ assert invoke_request.headers["authorization"] == "Bearer unit-jwt-token"
+
+ assert len(chunks) == 3
+ content = "".join(
+ chunk["choices"][0]["delta"]["content"]
+ for chunk in chunks
+ if chunk["choices"][0].get("delta", {}).get("content")
+ )
+ assert content == "Machine learning."
+ assert chunks[-1]["choices"][0].get("finish_reason") == "stop"
diff --git a/tests/unit/caching/test_disk_cache.py b/tests/unit/caching/test_disk_cache.py
index 084370726b1..243f194cc7a 100644
--- a/tests/unit/caching/test_disk_cache.py
+++ b/tests/unit/caching/test_disk_cache.py
@@ -7,6 +7,7 @@ import pytest
pytest.importorskip("diskcache")
from litellm.caching.disk_cache import DiskCache
+from tests._wait_helpers import await_until
class _SlowInt(int):
@@ -65,3 +66,93 @@ async def test_async_increment_adds_to_existing_int(cache):
async def test_async_increment_treats_non_int_cached_value_as_zero(cache):
await cache.async_set_cache("counter", "corrupt")
assert await cache.async_increment("counter", 9) == 9
+
+
+def disk_cache(tmp_path):
+ import litellm
+ from litellm.caching import Cache
+
+ litellm.cache = Cache(type="disk", disk_cache_dir=str(tmp_path))
+ yield litellm.cache
+ litellm.cache = None
+
+
+COMPLETION_MESSAGES = [{"role": "user", "content": "write a one sentence poem about: disk-cache-unit-key"}]
+
+
+def test_completion_is_served_from_disk_cache_until_params_change(disk_cache):
+ import litellm
+
+ first = litellm.completion(
+ "gpt-3.5-turbo", messages=COMPLETION_MESSAGES, caching=True, max_tokens=20, mock_response="first"
+ )
+ repeat = litellm.completion(
+ "gpt-3.5-turbo", messages=COMPLETION_MESSAGES, caching=True, max_tokens=20, mock_response="second"
+ )
+ changed = litellm.completion(
+ "gpt-3.5-turbo", messages=COMPLETION_MESSAGES, caching=True, temperature=0.5, mock_response="third"
+ )
+
+ assert (repeat.choices[0].message.content, repeat.id, repeat.created) == (
+ first.choices[0].message.content,
+ first.id,
+ first.created,
+ )
+ assert changed.choices[0].message.content == "third"
+
+
+async def test_async_completion_is_served_from_disk_cache_until_params_change(disk_cache):
+ import litellm
+
+ first = await litellm.acompletion(
+ "gpt-3.5-turbo", messages=COMPLETION_MESSAGES, caching=True, max_tokens=20, mock_response="first"
+ )
+ await await_until(lambda: len(disk_cache.cache.disk_cache) == 1, message="the first completion is cached")
+ repeat = await litellm.acompletion(
+ "gpt-3.5-turbo", messages=COMPLETION_MESSAGES, caching=True, max_tokens=20, mock_response="second"
+ )
+ changed = await litellm.acompletion(
+ "gpt-3.5-turbo", messages=COMPLETION_MESSAGES, caching=True, temperature=0.5, mock_response="third"
+ )
+
+ assert (repeat.choices[0].message.content, repeat.id, repeat.created) == (
+ first.choices[0].message.content,
+ first.id,
+ first.created,
+ )
+ assert changed.choices[0].message.content == "third"
+
+
+async def test_embedding_is_served_from_disk_cache_until_params_change(disk_cache, respx_mock, monkeypatch):
+ import httpx
+
+ import litellm
+
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ input_text = ["hello disk-embedding-unit-key"]
+ embeddings_route = respx_mock.post("https://api.openai.com/v1/embeddings").mock(
+ return_value=httpx.Response(
+ 200,
+ json={
+ "object": "list",
+ "data": [{"object": "embedding", "index": 0, "embedding": [0.1, 0.2, 0.3]}],
+ "model": "text-embedding-ada-002",
+ "usage": {"prompt_tokens": 2, "total_tokens": 2},
+ },
+ )
+ )
+
+ await litellm.aembedding("openai/text-embedding-ada-002", input=input_text, caching=True, api_key="sk-unit")
+ await await_until(lambda: len(disk_cache.cache.disk_cache) == 1, message="the first embedding is cached")
+ cached = await litellm.aembedding(
+ "openai/text-embedding-ada-002", input=input_text, caching=True, api_key="sk-unit"
+ )
+ assert cached._hidden_params["cache_hit"] is True
+ assert cached.data[0]["embedding"] == [0.1, 0.2, 0.3]
+ assert embeddings_route.call_count == 1
+
+ await litellm.aembedding(
+ "openai/text-embedding-ada-002", input=input_text, caching=True, user="charlie", api_key="sk-unit"
+ )
+ assert embeddings_route.call_count == 2
diff --git a/tests/unit/caching/test_gcs_cache.py b/tests/unit/caching/test_gcs_cache.py
index fe5df6526be..0887d3d155e 100644
--- a/tests/unit/caching/test_gcs_cache.py
+++ b/tests/unit/caching/test_gcs_cache.py
@@ -103,3 +103,81 @@ async def test_gcs_cache_async_set_encodes_object_name_in_query(mock_gcs_depende
called_url = mock_gcs_dependencies["async_client"].post.call_args.kwargs["url"]
assert "name=my_cache%2Fabc123" in called_url
+
+
+async def test_gcs_cache_completion_hit_and_param_sensitivity(mock_gcs_dependencies):
+ """Same params hit the injected GCS cache client; different params do not."""
+ import asyncio
+
+ import litellm
+ from litellm.caching import Cache
+
+ store = {}
+
+ import json as _json
+ from urllib.parse import parse_qs, unquote, urlparse
+
+ def _store(url, data=None, json=None, content=None, **kw):
+ object_name = parse_qs(urlparse(url).query).get("name", [None])[0]
+ if object_name is not None:
+ store[unquote(object_name)] = data if isinstance(data, (str, bytes)) else json
+ resp = AsyncMock()
+ resp.status_code = 200
+ resp.text = "{}"
+ return resp
+
+ def _get(url, **kw):
+ object_name = unquote(url.split("/o/")[-1].split("?")[0])
+ resp = AsyncMock()
+ if object_name in store:
+ stored = store[object_name]
+ resp.status_code = 200
+ resp.text = stored if isinstance(stored, str) else _json.dumps(stored)
+ else:
+ resp.status_code = 404
+ resp.text = "not found"
+ return resp
+
+ mock_gcs_dependencies["async_client"].post.side_effect = _store
+ mock_gcs_dependencies["async_client"].get.side_effect = _get
+ mock_gcs_dependencies["sync_client"].post.side_effect = _store
+ mock_gcs_dependencies["sync_client"].get.side_effect = _get
+
+ messages = [{"role": "user", "content": "write a one sentence poem about: gcs-cache-unit-key"}]
+ litellm.cache = Cache(type="gcs", gcs_bucket_name="test-bucket")
+ try:
+ response1 = await litellm.acompletion(
+ "gpt-3.5-turbo",
+ messages=messages,
+ caching=True,
+ max_tokens=20,
+ mock_response="This number is so great!",
+ )
+ deadline = asyncio.get_event_loop().time() + 10
+ while not store and asyncio.get_event_loop().time() < deadline:
+ await asyncio.sleep(0.05)
+ assert store
+ response2 = await litellm.acompletion(
+ "gpt-3.5-turbo",
+ messages=messages,
+ caching=True,
+ max_tokens=20,
+ mock_response="This number is great!",
+ )
+ assert response1.choices[0].message.content == response2.choices[0].message.content
+
+ response3 = await litellm.acompletion(
+ "gpt-3.5-turbo",
+ messages=messages,
+ caching=True,
+ temperature=0.5,
+ mock_response="This number is awful!",
+ )
+ assert response1.choices[0].message.content != response3.choices[0].message.content
+ finally:
+ litellm.cache = None
+ litellm.success_callback = []
+ litellm._async_success_callback = []
+
+
diff --git a/tests/local_testing/create_mock_standard_logging_payload.py b/tests/unit/create_mock_standard_logging_payload.py
similarity index 100%
rename from tests/local_testing/create_mock_standard_logging_payload.py
rename to tests/unit/create_mock_standard_logging_payload.py
diff --git a/tests/unit/integrations/clickhouse/__init__.py b/tests/unit/integrations/clickhouse/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/tests/test_litellm/integrations/clickhouse/test_clickhouse_batch_logger.py b/tests/unit/integrations/clickhouse/test_clickhouse_batch_logger.py
similarity index 100%
rename from tests/test_litellm/integrations/clickhouse/test_clickhouse_batch_logger.py
rename to tests/unit/integrations/clickhouse/test_clickhouse_batch_logger.py
diff --git a/tests/test_litellm/integrations/clickhouse/test_clickhouse_spend_logger.py b/tests/unit/integrations/clickhouse/test_clickhouse_spend_logger.py
similarity index 95%
rename from tests/test_litellm/integrations/clickhouse/test_clickhouse_spend_logger.py
rename to tests/unit/integrations/clickhouse/test_clickhouse_spend_logger.py
index fe47c1a59f3..563937decb9 100644
--- a/tests/test_litellm/integrations/clickhouse/test_clickhouse_spend_logger.py
+++ b/tests/unit/integrations/clickhouse/test_clickhouse_spend_logger.py
@@ -20,8 +20,6 @@ from litellm.integrations.clickhouse.clickhouse_spend_logger import (
strip_cache_hit_suffix,
)
from litellm.integrations.clickhouse.context import lens_analysis
-from litellm.integrations.clickhouse.schema import SPEND_LOGS_TABLE
-from litellm.integrations.custom_batch_logger import CustomBatchLogger
from litellm.litellm_core_utils import litellm_logging
from litellm.litellm_core_utils.secret_redaction import REDACTED
from litellm.tracing.types import SpendLogRecord
@@ -151,11 +149,6 @@ def _standard_payload(
return payload
-def test_is_a_custom_batch_logger():
- assert issubclass(ClickHouseSpendLogger, CustomBatchLogger)
- assert ClickHouseSpendLogger.table == SPEND_LOGS_TABLE
-
-
def test_success_row_mapping():
row: Final = spend_log_row_from_payload(cast(StandardLoggingPayload, _payload()), {"response_cost": 0.00042})
@@ -517,25 +510,6 @@ async def test_success_and_failure_events_write_scoped_spend_rows():
assert {key: row[key] for key in original_fields} == original_fields
-async def test_trace_ingest_and_invalid_payload_do_not_write_spend():
- storage = MagicMock()
- storage.ensure_schema = AsyncMock()
- logger = ClickHouseSpendLogger(storage=storage)
- now = datetime.now(timezone.utc)
-
- await logger.async_log_success_event(
- {"standard_logging_object": {**_minimal_payload("trace", status="success", cost=0), "call_type": "/v1/traces"}},
- None,
- now,
- now,
- )
- await logger.async_log_success_event({"standard_logging_object": "invalid"}, None, now, now)
-
- assert logger.log_queue == []
- storage.ensure_schema.assert_not_awaited()
-
-
@pytest.mark.parametrize(
"status,llm_cost,guardrail_cost,expected",
[
diff --git a/tests/unit/litellm_core_utils/test_litellm_logging.py b/tests/unit/litellm_core_utils/test_litellm_logging.py
index f8ed11bdca3..7dbb7cc3924 100644
--- a/tests/unit/litellm_core_utils/test_litellm_logging.py
+++ b/tests/unit/litellm_core_utils/test_litellm_logging.py
@@ -10439,7 +10439,7 @@ def test_truncate_standard_logging_payload():
1. the payload passed in is never modified, since every callback of the request shares it
2. the `messages`, `response`, and `error_str` in the returned payload are truncated
"""
- from tests.local_testing.create_mock_standard_logging_payload import (
+ from tests.unit.create_mock_standard_logging_payload import (
create_standard_logging_payload_with_long_content,
)
diff --git a/tests/unit/llms/azure_ai/vector_stores/__init__.py b/tests/unit/llms/azure_ai/vector_stores/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/tests/vector_store_tests/test_azure_ai_vector_store.py b/tests/unit/llms/azure_ai/vector_stores/test_azure_ai_vector_stores_transformation.py
similarity index 68%
rename from tests/vector_store_tests/test_azure_ai_vector_store.py
rename to tests/unit/llms/azure_ai/vector_stores/test_azure_ai_vector_stores_transformation.py
index daa0c9b6ed0..7a0df7d96f0 100644
--- a/tests/vector_store_tests/test_azure_ai_vector_store.py
+++ b/tests/unit/llms/azure_ai/vector_stores/test_azure_ai_vector_stores_transformation.py
@@ -1,5 +1,4 @@
import json
-import os
from unittest.mock import MagicMock
import httpx
@@ -19,31 +18,68 @@ from litellm.vector_stores import (
@pytest.mark.parametrize("sync_mode", [True, False])
@pytest.mark.asyncio
-async def test_basic_search_vector_store(sync_mode):
- litellm.turn_on_debug()
- litellm.set_verbose = True
+async def test_basic_search_vector_store(
+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch, sync_mode
+):
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ query_vector = [0.5, -0.25, 0.125]
+ search_url = (
+ "https://azure-kb-search.search.windows.net/indexes/my-vector-index/docs/search?api-version=2024-07-01"
+ )
+ embedding_route = respx_mock.post(url__regex=r"https://azure-embed\.example\.com/.*/embeddings.*").mock(
+ return_value=httpx.Response(
+ 200,
+ json={
+ "object": "list",
+ "data": [{"object": "embedding", "index": 0, "embedding": query_vector}],
+ "model": "text-embedding-3-large",
+ "usage": {"prompt_tokens": 2, "total_tokens": 2},
+ },
+ )
+ )
+ search_route = respx_mock.post(search_url).mock(
+ return_value=httpx.Response(
+ 200,
+ json={
+ "value": [
+ {
+ "@search.score": 0.95,
+ "id": "doc-1",
+ "content": "azure search document text",
+ }
+ ]
+ },
+ )
+ )
base_request_args = {
"vector_store_id": "my-vector-index",
"custom_llm_provider": "azure_ai",
"azure_search_service_name": "azure-kb-search",
"litellm_embedding_model": "azure_ai/text-embedding-3-large",
"litellm_embedding_config": {
- "api_base": os.getenv("AZURE_AI_API_BASE"),
- "api_key": os.getenv("AZURE_AI_API_KEY"),
+ "api_base": "https://azure-embed.example.com",
+ "api_key": "mock_azure_ai_api_key",
},
- "api_key": os.getenv("AZURE_SEARCH_API_KEY"),
+ "api_key": "mock_azure_search_api_key",
}
- default_query = base_request_args.pop("query", "Basic ping")
- print(f"base_request_args: {base_request_args}")
- try:
- if sync_mode:
- response = vector_store_search(query=default_query, **base_request_args)
- else:
- response = await vector_store_asearch(query=default_query, **base_request_args)
- except litellm.InternalServerError:
- pytest.skip("Skipping test due to litellm.InternalServerError")
-
- print("litellm response=", json.dumps(response, indent=4, default=str))
+ if sync_mode:
+ response = vector_store_search(query="Basic ping", **base_request_args)
+ else:
+ response = await vector_store_asearch(query="Basic ping", **base_request_args)
+
+ embedding_request = embedding_route.calls.last.request
+ assert embedding_request.headers["api-key"] == "mock_azure_ai_api_key"
+ assert json.loads(embedding_request.read())["input"] == ["Basic ping"]
+
+ search_request = search_route.calls.last.request
+ assert search_request.headers["api-key"] == "mock_azure_search_api_key"
+ search_body = json.loads(search_request.read())
+ assert search_body["vectorQueries"][0]["vector"] == query_vector
+
+ assert response is not None
+ assert response["object"] == "vector_store.search_results.page" # type: ignore
+ assert len(response["data"]) == 1 # type: ignore
+ assert response["data"][0]["content"][0]["text"] == "azure search document text" # type: ignore
class RecordingEmbeddingExecutor:
diff --git a/tests/unit/llms/base_llm/vector_store/__init__.py b/tests/unit/llms/base_llm/vector_store/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/tests/unit/llms/base_llm/vector_store/test_base_vector_store.py b/tests/unit/llms/base_llm/vector_store/test_base_vector_store.py
new file mode 100644
index 00000000000..c2305861eb2
--- /dev/null
+++ b/tests/unit/llms/base_llm/vector_store/test_base_vector_store.py
@@ -0,0 +1,98 @@
+"""Cross-provider base vector store contract tests.
+
+Exercises litellm.vector_stores create/search against a real request/response
+cycle with the upstream scripted at the provider's own URL.
+"""
+
+import json
+from typing import Final
+
+import httpx
+import pytest
+import respx
+
+import litellm
+
+OPENAI_VECTOR_STORES_URL: Final = "https://api.openai.com/v1/vector_stores"
+OPENAI_VECTOR_STORE_SEARCH_URL: Final = "https://api.openai.com/v1/vector_stores/vs_abc123/search"
+
+
+async def test_basic_create_vector_store(respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ create_route = respx_mock.post(OPENAI_VECTOR_STORES_URL).mock(
+ return_value=httpx.Response(
+ 200,
+ json={
+ "id": "vs_abc123",
+ "object": "vector_store",
+ "created_at": 1745836841,
+ "name": "support-docs",
+ "usage_bytes": 0,
+ "file_counts": {"in_progress": 0, "completed": 0, "failed": 0, "cancelled": 0, "total": 0},
+ "status": "completed",
+ "last_active_at": 1745836841,
+ "metadata": {},
+ },
+ )
+ )
+
+ response = await litellm.vector_stores.acreate(
+ name="support-docs",
+ custom_llm_provider="openai",
+ api_key="sk-unit-test",
+ )
+
+ create_request = create_route.calls.last.request
+ assert create_request.headers["authorization"] == "Bearer sk-unit-test"
+ create_body = json.loads(create_request.read())
+ assert create_body["name"] == "support-docs"
+
+ assert isinstance(response, dict)
+ assert response["id"] == "vs_abc123"
+ assert response["object"] == "vector_store"
+ assert response["name"] == "support-docs"
+ assert response["created_at"] == 1745836841
+
+
+async def test_basic_search_vector_store(respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ search_route = respx_mock.post(OPENAI_VECTOR_STORE_SEARCH_URL).mock(
+ return_value=httpx.Response(
+ 200,
+ json={
+ "object": "vector_store.search_results.page",
+ "search_query": "what is machine learning?",
+ "data": [
+ {
+ "file_id": "file-1",
+ "filename": "ml-notes.txt",
+ "score": 0.87,
+ "attributes": {},
+ "content": [{"type": "text", "text": "machine learning answer chunk"}],
+ }
+ ],
+ },
+ )
+ )
+
+ response = await litellm.vector_stores.asearch(
+ query="what is machine learning?",
+ vector_store_id="vs_abc123",
+ custom_llm_provider="openai",
+ api_key="sk-unit-test",
+ )
+
+ search_request = search_route.calls.last.request
+ assert search_request.headers["authorization"] == "Bearer sk-unit-test"
+ assert json.loads(search_request.read())["query"] == "what is machine learning?"
+
+ assert response["object"] == "vector_store.search_results.page"
+ assert len(response["data"]) == 1
+ first_result = response["data"][0]
+ assert first_result["file_id"] == "file-1"
+ assert first_result["filename"] == "ml-notes.txt"
+ assert first_result["score"] == 0.87
+ assert first_result["content"][0]["type"] == "text"
+ assert first_result["content"][0]["text"] == "machine learning answer chunk"
diff --git a/tests/unit/llms/bedrock/vector_stores/test_bedrock_vector_store_transformation.py b/tests/unit/llms/bedrock/vector_stores/test_bedrock_vector_store_transformation.py
index b45e70e31d3..87c57023c17 100644
--- a/tests/unit/llms/bedrock/vector_stores/test_bedrock_vector_store_transformation.py
+++ b/tests/unit/llms/bedrock/vector_stores/test_bedrock_vector_store_transformation.py
@@ -1,6 +1,11 @@
+import json
from typing import Final
from unittest.mock import MagicMock
+import httpx
+import pytest
+import respx
+
from litellm.llms.bedrock.vector_stores.transformation import BedrockVectorStoreConfig
@@ -196,3 +201,177 @@ def test_transform_search_request_prefers_extra_body_user_context_over_top_level
)
assert body["userContext"] == {"userId": "[email protected]"}
+
+
+def test_get_file_id_from_metadata():
+ """Test that file_id is correctly extracted from metadata."""
+ config = BedrockVectorStoreConfig()
+
+ metadata_with_uri = {
+ "x-amz-bedrock-kb-source-uri": "https://www.litellm.ai",
+ "x-amz-bedrock-kb-chunk-id": "1%3A0%3AjNYPg5YByRuP5PdK96co",
+ }
+ file_id = config._get_file_id_from_metadata(metadata_with_uri)
+ assert file_id == "https://www.litellm.ai"
+
+ metadata_without_uri = {"x-amz-bedrock-kb-chunk-id": "1%3A0%3AjNYPg5YByRuP5PdK96co"}
+ file_id = config._get_file_id_from_metadata(metadata_without_uri)
+ assert file_id == "bedrock-kb-1%3A0%3AjNYPg5YByRuP5PdK96co"
+
+ file_id = config._get_file_id_from_metadata({})
+ assert file_id == "bedrock-kb-unknown"
+
+
+def test_get_filename_from_metadata():
+ """Test that filename is correctly extracted from metadata."""
+ config = BedrockVectorStoreConfig()
+
+ metadata_with_path = {"x-amz-bedrock-kb-source-uri": "https://docs.litellm.ai/tutorial/setup.html"}
+ filename = config._get_filename_from_metadata(metadata_with_path)
+ assert filename == "setup.html"
+
+ metadata_domain_only = {"x-amz-bedrock-kb-source-uri": "https://www.litellm.ai"}
+ filename = config._get_filename_from_metadata(metadata_domain_only)
+ assert filename == "www.litellm.ai"
+
+ metadata_without_uri = {"x-amz-bedrock-kb-data-source-id": "CCEJIRXXFI"}
+ filename = config._get_filename_from_metadata(metadata_without_uri)
+ assert filename == "bedrock-kb-document-CCEJIRXXFI"
+
+ filename = config._get_filename_from_metadata({})
+ assert filename == "bedrock-kb-document-unknown"
+
+
+def test_get_attributes_from_metadata():
+ """Test that attributes are correctly extracted from metadata."""
+ config = BedrockVectorStoreConfig()
+
+ metadata = {
+ "x-amz-bedrock-kb-source-uri": "https://www.litellm.ai",
+ "x-amz-bedrock-kb-chunk-id": "1%3A0%3AjNYPg5YByRuP5PdK96co",
+ "x-amz-bedrock-kb-data-source-id": "CCEJIRXXFI",
+ }
+ attributes = config._get_attributes_from_metadata(metadata)
+ assert attributes == metadata
+ assert attributes is not metadata
+
+ attributes = config._get_attributes_from_metadata({})
+ assert attributes == {}
+
+ attributes = config._get_attributes_from_metadata(None)
+ assert attributes == {}
+
+
+BEDROCK_RETRIEVE_URL = "https://bedrock-agent-runtime.us-east-1.amazonaws.com/knowledgebases/T37J8R4WTM/retrieve"
+BEDROCK_RETRIEVE_RESPONSE = {
+ "retrievalResults": [
+ {
+ "content": {"text": "Mock search result"},
+ "location": {"type": "S3", "s3Location": {"uri": "s3://docs/setup.html"}},
+ "metadata": {
+ "x-amz-bedrock-kb-source-uri": "https://docs.litellm.ai/setup.html",
+ "x-amz-bedrock-kb-chunk-id": "chunk-1",
+ },
+ "score": 0.9,
+ }
+ ]
+}
+
+
+async def test_bedrock_search_with_router(respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch):
+ import litellm
+ from litellm.router import Router
+
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+
+ retrieve_route = respx_mock.post(BEDROCK_RETRIEVE_URL).mock(
+ return_value=httpx.Response(200, json=BEDROCK_RETRIEVE_RESPONSE)
+ )
+
+ _router = Router(model_list=[])
+ search_response = await _router.avector_store_search(
+ query="what happens after we add a model",
+ vector_store_id="T37J8R4WTM",
+ custom_llm_provider="bedrock",
+ aws_access_key_id="test_access_key",
+ aws_secret_access_key="test_secret_key",
+ aws_region_name="us-east-1",
+ )
+
+ assert retrieve_route.call_count == 1
+ request = retrieve_route.calls.last.request
+ assert "AWS4-HMAC-SHA256 Credential=test_access_key" in request.headers["authorization"]
+ body = json.loads(request.read())
+ assert body["retrievalQuery"]["text"] == "what happens after we add a model"
+
+ assert search_response is not None
+ assert search_response["object"] == "vector_store.search_results.page"
+ assert len(search_response["data"]) == 1
+ assert search_response["data"][0]["score"] == 0.9
+ assert search_response["data"][0]["content"][0]["text"] == "Mock search result"
+
+
+async def test_bedrock_search_with_credentials_managed_registry(
+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
+):
+ """
+ Test that the vector store search uses the credential accessor from the registry
+ when AWS environment variables are not set, ensuring credentials are managed properly.
+ """
+ from datetime import datetime, timezone
+
+ import litellm
+ from litellm.router import Router
+ from litellm.types.utils import CredentialItem
+ from litellm.types.vector_stores import LiteLLM_ManagedVectorStore
+ from litellm.vector_stores.vector_store_registry import VectorStoreRegistry
+
+ test_credentials = CredentialItem(
+ credential_name="bedrock-litellm-website-knowledgebase",
+ credential_info={
+ "provider": "aws",
+ "description": "Test AWS credentials for bedrock",
+ },
+ credential_values={
+ "aws_access_key_id": "test_access_key",
+ "aws_secret_access_key": "test_secret_key",
+ "aws_region_name": "us-east-1",
+ },
+ )
+
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ monkeypatch.setattr(litellm, "credential_list", [test_credentials])
+ monkeypatch.delenv("AWS_ACCESS_KEY_ID", raising=False)
+ monkeypatch.delenv("AWS_SECRET_ACCESS_KEY", raising=False)
+ monkeypatch.delenv("AWS_REGION_NAME", raising=False)
+
+ vector_store = LiteLLM_ManagedVectorStore(
+ vector_store_id="T37J8R4WTM",
+ custom_llm_provider="bedrock",
+ created_at=datetime.now(timezone.utc),
+ updated_at=datetime.now(timezone.utc),
+ litellm_credential_name="bedrock-litellm-website-knowledgebase",
+ )
+
+ registry = VectorStoreRegistry([vector_store])
+ monkeypatch.setattr(litellm, "vector_store_registry", registry)
+
+ retrieve_route = respx_mock.post(BEDROCK_RETRIEVE_URL).mock(
+ return_value=httpx.Response(200, json=BEDROCK_RETRIEVE_RESPONSE)
+ )
+
+ _router = Router(model_list=[])
+ search_response = await _router.avector_store_search(
+ query="what happens after we add a model",
+ vector_store_id="T37J8R4WTM",
+ custom_llm_provider="bedrock",
+ )
+
+ assert retrieve_route.call_count == 1
+ request = retrieve_route.calls.last.request
+ assert "AWS4-HMAC-SHA256 Credential=test_access_key" in request.headers["authorization"]
+
+ assert search_response["data"][0]["score"] == 0.9
+ assert search_response["data"][0]["content"][0]["text"] == "Mock search result"
diff --git a/tests/unit/llms/milvus/__init__.py b/tests/unit/llms/milvus/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/tests/unit/llms/milvus/vector_stores/__init__.py b/tests/unit/llms/milvus/vector_stores/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/tests/unit/llms/milvus/vector_stores/test_milvus_vector_stores_transformation.py b/tests/unit/llms/milvus/vector_stores/test_milvus_vector_stores_transformation.py
new file mode 100644
index 00000000000..01da16a6efd
--- /dev/null
+++ b/tests/unit/llms/milvus/vector_stores/test_milvus_vector_stores_transformation.py
@@ -0,0 +1,476 @@
+"""
+Tests for Milvus Vector Store
+"""
+
+import json
+from unittest.mock import MagicMock
+
+import httpx
+import pytest
+import respx
+
+import litellm
+from litellm import Router
+from litellm.llms.milvus.vector_stores.transformation import MilvusVectorStoreConfig
+from litellm.types.utils import EmbeddingResponse
+from litellm.vector_stores import asearch as vector_store_asearch
+from litellm.vector_stores import search as vector_store_search
+
+MOCK_MILVUS_SEARCH_RESPONSE = {
+ "code": 0,
+ "cost": 6,
+ "data": [
+ {
+ "book_id": 0,
+ "book_intro_text": "abababababa_0562efee-0f1f-4b6b-9ca3-1a160f124ad8",
+ "distance": 10.240219,
+ },
+ {
+ "book_id": 1,
+ "book_intro_text": "abababababa_9a13e8f3-bb1e-487f-b555-b8ae4b127243",
+ "distance": 10.240219,
+ },
+ {
+ "book_id": 2,
+ "book_intro_text": "abababababa_870f47f1-23ec-4364-ad30-6d364ba8ddb5",
+ "distance": 10.240219,
+ },
+ {
+ "book_id": 1000,
+ "book_intro_text": "abababababa_8ea2d76a-3fdf-49b3-8f16-a91638361bba",
+ "distance": 8.531628,
+ },
+ {
+ "book_id": 1001,
+ "book_intro_text": "abababababa_24758251-e740-4183-8649-2f742f676ca0",
+ "distance": 8.531628,
+ },
+ {
+ "book_id": 1002,
+ "book_intro_text": "abababababa_faa55789-220d-4ef1-b5bf-a72f2fbd061b",
+ "distance": 8.531628,
+ },
+ {
+ "book_id": 0,
+ "book_intro_text": "abababababa_0562efee-0f1f-4b6b-9ca3-1a160f124ad8",
+ "distance": 8.236887,
+ },
+ {
+ "book_id": 1,
+ "book_intro_text": "abababababa_9a13e8f3-bb1e-487f-b555-b8ae4b127243",
+ "distance": 8.236887,
+ },
+ {
+ "book_id": 2,
+ "book_intro_text": "abababababa_870f47f1-23ec-4364-ad30-6d364ba8ddb5",
+ "distance": 8.236887,
+ },
+ ],
+ "topks": [3, 3, 3],
+}
+
+
+class RecordingEmbeddingExecutor:
+ def __init__(self, response):
+ self.response = response
+ self.calls = []
+
+ def embed(self, model, query, configuration):
+ self.calls.append((model, query, dict(configuration)))
+ return self.response
+
+ async def aembed(self, model, query, configuration):
+ self.calls.append((model, query, dict(configuration)))
+ return self.response
+
+
+ALIAS_QUERY_VECTOR = [0.5, -0.25, 0.125]
+ALIAS_EMBEDDING_RESPONSE = EmbeddingResponse(
+ data=[{"embedding": ALIAS_QUERY_VECTOR, "index": 0, "object": "embedding"}]
+)
+OPENAI_EMBEDDINGS_URL = "https://api.openai.com/v1/embeddings"
+MILVUS_SEARCH_URL = "https://milvus.example/v2/vectordb/entities/search"
+ZILLIZ_SEARCH_URL = (
+ "https://in03-test.serverless.aws-eu-central-1.cloud.zilliz.com/v2/vectordb/entities/search"
+)
+ALIAS_SEARCH_KWARGS = {
+ "query": "what is machine learning?",
+ "vector_store_id": "book_2",
+ "custom_llm_provider": "milvus",
+ "api_base": "https://milvus.example",
+ "api_key": "mock_milvus_api_key",
+ "litellm_embedding_model": "multilingual-e5-large",
+ "milvus_text_field": "book_intro_text",
+}
+ZILLIZ_SEARCH_KWARGS = {
+ "query": "what is machine learning?",
+ "vector_store_id": "book_2",
+ "custom_llm_provider": "milvus",
+ "api_base": "https://in03-test.serverless.aws-eu-central-1.cloud.zilliz.com",
+ "api_key": "mock_milvus_api_key",
+ "litellm_embedding_model": "text-embedding-3-large",
+ "litellm_embedding_config": {
+ "api_key": "mock_openai_api_key",
+ },
+ "outputFields": ["book_intro_text"],
+ "annsField": "book_intro_vector",
+ "milvus_text_field": "book_intro_text",
+}
+
+
+def _alias_router():
+ return Router(
+ model_list=[
+ {
+ "model_name": "multilingual-e5-large",
+ "litellm_params": {
+ "model": "openai/text-embedding-3-small",
+ "api_key": "deployment-key",
+ },
+ }
+ ]
+ )
+
+
+def _mock_embedding_route(respx_mock: respx.MockRouter) -> respx.Route:
+ return respx_mock.post(OPENAI_EMBEDDINGS_URL).mock(
+ return_value=httpx.Response(
+ 200,
+ json={
+ "object": "list",
+ "data": [{"object": "embedding", "index": 0, "embedding": ALIAS_QUERY_VECTOR}],
+ "model": "text-embedding-3-small",
+ "usage": {"prompt_tokens": 2, "total_tokens": 2},
+ },
+ )
+ )
+
+
+def _mock_search_route(respx_mock: respx.MockRouter) -> respx.Route:
+ return respx_mock.post(MILVUS_SEARCH_URL).mock(return_value=httpx.Response(200, json=MOCK_MILVUS_SEARCH_RESPONSE))
+
+
+def _mock_zilliz_search_route(respx_mock: respx.MockRouter) -> respx.Route:
+ return respx_mock.post(ZILLIZ_SEARCH_URL).mock(return_value=httpx.Response(200, json=MOCK_MILVUS_SEARCH_RESPONSE))
+
+
+def _search_request_body(search_route: respx.Route):
+ return json.loads(search_route.calls.last.request.read())
+
+
+class TestMilvusVectorStore:
+ """Test Milvus Vector Store with mocked responses"""
+
+ @pytest.mark.asyncio
+ async def test_basic_search_with_mock_async(self, respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch):
+ """Test basic vector search with mocked backend response (async)"""
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ embedding_route = _mock_embedding_route(respx_mock)
+ search_route = _mock_zilliz_search_route(respx_mock)
+
+ response = await vector_store_asearch(**ZILLIZ_SEARCH_KWARGS)
+
+ embedding_request = embedding_route.calls.last.request
+ assert embedding_request.headers["authorization"] == "Bearer mock_openai_api_key"
+ embedding_body = json.loads(embedding_request.read())
+ assert embedding_body["model"] == "text-embedding-3-large"
+ assert embedding_body["input"] == ["what is machine learning?"]
+
+ search_request = search_route.calls.last.request
+ request_data = json.loads(search_request.read())
+ assert request_data["collectionName"] == "book_2"
+ assert request_data["data"] == [ALIAS_QUERY_VECTOR]
+ assert request_data["annsField"] == "book_intro_vector"
+ assert request_data["outputFields"] == ["book_intro_text"]
+ assert "v2/vectordb/entities/search" in str(search_request.url)
+
+ assert response is not None
+ assert response["object"] == "vector_store.search_results.page" # type: ignore
+ assert len(response["data"]) == 9 # type: ignore
+
+ first_result = response["data"][0] # type: ignore
+ assert first_result["score"] == 10.240219 # type: ignore
+ assert len(first_result["content"]) > 0 # type: ignore
+ assert first_result["content"][0]["type"] == "text" # type: ignore
+ assert first_result["content"][0]["text"] == "abababababa_0562efee-0f1f-4b6b-9ca3-1a160f124ad8" # type: ignore
+ assert first_result["attributes"]["book_id"] == 0 # type: ignore
+ assert "book_intro_text" not in first_result["attributes"] # type: ignore
+
+ def test_basic_search_with_mock_sync(self, respx_mock: respx.MockRouter):
+ """Test basic vector search with mocked backend response (sync)"""
+ embedding_route = _mock_embedding_route(respx_mock)
+ search_route = _mock_zilliz_search_route(respx_mock)
+
+ response = vector_store_search(**ZILLIZ_SEARCH_KWARGS)
+
+ assert embedding_route.call_count == 1
+ assert search_route.call_count == 1
+
+ request_data = _search_request_body(search_route)
+ assert request_data["collectionName"] == "book_2"
+ assert request_data["data"] == [ALIAS_QUERY_VECTOR]
+ assert request_data["annsField"] == "book_intro_vector"
+ assert request_data["outputFields"] == ["book_intro_text"]
+
+ assert response is not None
+ assert response["object"] == "vector_store.search_results.page" # type: ignore
+ assert len(response["data"]) == 9 # type: ignore
+ assert "search_query" in response # type: ignore
+
+ expected_results = [
+ {
+ "book_id": 0,
+ "text": "abababababa_0562efee-0f1f-4b6b-9ca3-1a160f124ad8",
+ "distance": 10.240219,
+ },
+ {
+ "book_id": 1,
+ "text": "abababababa_9a13e8f3-bb1e-487f-b555-b8ae4b127243",
+ "distance": 10.240219,
+ },
+ {
+ "book_id": 2,
+ "text": "abababababa_870f47f1-23ec-4364-ad30-6d364ba8ddb5",
+ "distance": 10.240219,
+ },
+ ]
+
+ for idx, expected in enumerate(expected_results):
+ result = response["data"][idx] # type: ignore
+ assert result["score"] == expected["distance"] # type: ignore
+ assert len(result["content"]) > 0 # type: ignore
+ assert result["content"][0]["type"] == "text" # type: ignore
+ assert result["content"][0]["text"] == expected["text"] # type: ignore
+ assert result["attributes"]["book_id"] == expected["book_id"] # type: ignore
+ assert "book_intro_text" not in result["attributes"] # type: ignore
+
+ def test_user_supplied_db_and_partition_are_dropped(self, respx_mock: respx.MockRouter):
+ """User-supplied dbName / partitionNames must not be forwarded to Milvus."""
+ _mock_embedding_route(respx_mock)
+ search_route = _mock_zilliz_search_route(respx_mock)
+
+ vector_store_search(
+ **ZILLIZ_SEARCH_KWARGS,
+ dbName="other_tenant_db",
+ partitionNames=["other_tenant_partition"],
+ )
+
+ request_data = _search_request_body(search_route)
+ assert "dbName" not in request_data
+ assert "partitionNames" not in request_data
+ assert request_data["collectionName"] == "book_2"
+ assert request_data["annsField"] == "book_intro_vector"
+ assert request_data["outputFields"] == ["book_intro_text"]
+
+ def test_backend_configured_db_and_partition_are_forwarded(self, respx_mock: respx.MockRouter):
+ """milvus_db_name / milvus_partition_names from litellm_params must be sent."""
+ _mock_embedding_route(respx_mock)
+ search_route = _mock_zilliz_search_route(respx_mock)
+
+ vector_store_search(
+ **ZILLIZ_SEARCH_KWARGS,
+ milvus_db_name="tenant_a_db",
+ milvus_partition_names=["tenant_a_partition"],
+ )
+
+ request_data = _search_request_body(search_route)
+ assert request_data["dbName"] == "tenant_a_db"
+ assert request_data["partitionNames"] == ["tenant_a_partition"]
+
+ def test_user_params_cannot_override_backend_db_and_partition(self, respx_mock: respx.MockRouter):
+ """Backend-config dbName/partitionNames must win over user-supplied values."""
+ _mock_embedding_route(respx_mock)
+ search_route = _mock_zilliz_search_route(respx_mock)
+
+ vector_store_search(
+ **ZILLIZ_SEARCH_KWARGS,
+ milvus_db_name="tenant_a_db",
+ milvus_partition_names=["tenant_a_partition"],
+ dbName="other_tenant_db",
+ partitionNames=["other_tenant_partition"],
+ )
+
+ request_data = _search_request_body(search_route)
+ assert request_data["dbName"] == "tenant_a_db"
+ assert request_data["partitionNames"] == ["tenant_a_partition"]
+
+
+def _assert_alias_resolved(embedding_route: respx.Route, search_route: respx.Route, response):
+ embedding_request = embedding_route.calls.last.request
+ assert embedding_request.headers["authorization"] == "Bearer deployment-key"
+ embedding_body = json.loads(embedding_request.read())
+ assert embedding_body["model"] == "text-embedding-3-small"
+ assert embedding_body["input"] == ["what is machine learning?"]
+ search_request = search_route.calls.last.request
+ assert search_request.headers["authorization"] == "Bearer mock_milvus_api_key"
+ assert json.loads(search_request.read())["data"] == [ALIAS_QUERY_VECTOR]
+ assert len(response["data"]) == len(MOCK_MILVUS_SEARCH_RESPONSE["data"])
+ assert response["data"][0]["content"][0]["text"] == MOCK_MILVUS_SEARCH_RESPONSE["data"][0]["book_intro_text"]
+
+
+def test_router_search_resolves_bare_embedding_alias_sync(
+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
+):
+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)
+ embedding_route = _mock_embedding_route(respx_mock)
+ search_route = _mock_search_route(respx_mock)
+
+ response = _alias_router().vector_store_search(**ALIAS_SEARCH_KWARGS)
+
+ _assert_alias_resolved(embedding_route, search_route, response)
+
+
+async def test_router_search_resolves_bare_embedding_alias_async(
+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
+):
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)
+ embedding_route = _mock_embedding_route(respx_mock)
+ search_route = _mock_search_route(respx_mock)
+
+ response = await _alias_router().avector_store_search(**ALIAS_SEARCH_KWARGS)
+
+ _assert_alias_resolved(embedding_route, search_route, response)
+
+
+def test_sdk_search_with_router_kwarg_resolves_bare_embedding_alias_sync(
+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
+):
+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)
+ embedding_route = _mock_embedding_route(respx_mock)
+ search_route = _mock_search_route(respx_mock)
+
+ response = litellm.vector_stores.search(router=_alias_router(), **ALIAS_SEARCH_KWARGS)
+
+ _assert_alias_resolved(embedding_route, search_route, response)
+
+
+async def test_sdk_search_with_router_kwarg_resolves_bare_embedding_alias_async(
+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
+):
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)
+ embedding_route = _mock_embedding_route(respx_mock)
+ search_route = _mock_search_route(respx_mock)
+
+ response = await litellm.vector_stores.asearch(router=_alias_router(), **ALIAS_SEARCH_KWARGS)
+
+ _assert_alias_resolved(embedding_route, search_route, response)
+
+
+def _team_alias_router():
+ return Router(
+ model_list=[
+ {
+ "model_name": "team-a-embedder",
+ "litellm_params": {
+ "model": "openai/text-embedding-3-small",
+ "api_key": "deployment-key",
+ },
+ "model_info": {"team_id": "team-a", "team_public_model_name": "multilingual-e5-large"},
+ }
+ ]
+ )
+
+
+async def test_sdk_search_with_router_kwarg_resolves_team_alias_from_request_metadata(
+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
+):
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)
+ embedding_route = _mock_embedding_route(respx_mock)
+ search_route = _mock_search_route(respx_mock)
+
+ response = await litellm.vector_stores.asearch(
+ router=_team_alias_router(), metadata={"user_api_key_team_id": "team-a"}, **ALIAS_SEARCH_KWARGS
+ )
+
+ _assert_alias_resolved(embedding_route, search_route, response)
+
+
+async def test_sdk_search_with_router_kwarg_rejects_team_alias_without_team_metadata(
+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
+):
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)
+ embedding_route = _mock_embedding_route(respx_mock)
+ _mock_search_route(respx_mock)
+
+ with pytest.raises(litellm.APIConnectionError):
+ await litellm.vector_stores.asearch(router=_team_alias_router(), **ALIAS_SEARCH_KWARGS)
+
+ assert embedding_route.call_count == 0
+
+
+async def test_transform_uses_injected_executor_without_embedding_config(respx_mock: respx.MockRouter):
+ executor = RecordingEmbeddingExecutor(ALIAS_EMBEDDING_RESPONSE)
+ config = MilvusVectorStoreConfig()
+ logging_obj = MagicMock()
+ logging_obj.model_call_details = {}
+ transform_kwargs = {
+ "vector_store_id": "book_2",
+ "query": ["what is", "milvus?"],
+ "vector_store_search_optional_params": {"limit": 3},
+ "api_base": "https://milvus.example",
+ "litellm_logging_obj": logging_obj,
+ "litellm_params": {"litellm_embedding_model": "multilingual-e5-large", "milvus_db_name": "docs"},
+ "embedding_executor": executor,
+ }
+
+ url, sync_body = config.transform_search_vector_store_request(**transform_kwargs)
+ _, async_body = await config.atransform_search_vector_store_request(**transform_kwargs)
+
+ assert respx_mock.calls.call_count == 0
+ assert executor.calls == [("multilingual-e5-large", "what is milvus?", {})] * 2
+ assert url == MILVUS_SEARCH_URL
+ assert sync_body == async_body
+ assert sync_body == {
+ "collectionName": "book_2",
+ "data": [ALIAS_QUERY_VECTOR],
+ "annsField": "book_intro_vector",
+ "limit": 3,
+ "dbName": "docs",
+ }
+ assert logging_obj.model_call_details["input"] == "what is milvus?"
+ assert logging_obj.model_call_details["embedding_model"] == "multilingual-e5-large"
+
+
+def test_transform_falls_back_to_sdk_embedding_without_executor_or_config(
+ respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
+):
+ monkeypatch.setenv("OPENAI_API_KEY", "env-key")
+ embedding_route = _mock_embedding_route(respx_mock)
+ logging_obj = MagicMock()
+ logging_obj.model_call_details = {}
+
+ _, body = MilvusVectorStoreConfig().transform_search_vector_store_request(
+ vector_store_id="book_2",
+ query="q",
+ vector_store_search_optional_params={},
+ api_base="https://milvus.example",
+ litellm_logging_obj=logging_obj,
+ litellm_params={"litellm_embedding_model": "openai/text-embedding-3-small"},
+ )
+
+ embedding_request = embedding_route.calls.last.request
+ assert embedding_request.headers["authorization"] == "Bearer env-key"
+ assert json.loads(embedding_request.read())["input"] == ["q"]
+ assert body["data"] == [ALIAS_QUERY_VECTOR]
+
+
+def test_transform_requires_embedding_model():
+ with pytest.raises(ValueError, match="litellm_embedding_model is required"):
+ MilvusVectorStoreConfig().transform_search_vector_store_request(
+ vector_store_id="book_2",
+ query="q",
+ vector_store_search_optional_params={},
+ api_base="https://milvus.example",
+ litellm_logging_obj=MagicMock(),
+ litellm_params={"litellm_embedding_config": {"api_key": "store-key"}},
+ embedding_executor=RecordingEmbeddingExecutor(ALIAS_EMBEDDING_RESPONSE),
+ )
diff --git a/tests/unit/llms/ragflow/vector_stores/__init__.py b/tests/unit/llms/ragflow/vector_stores/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/tests/unit/llms/ragflow/vector_stores/test_ragflow_vector_stores_transformation.py b/tests/unit/llms/ragflow/vector_stores/test_ragflow_vector_stores_transformation.py
new file mode 100644
index 00000000000..f1fc34100d1
--- /dev/null
+++ b/tests/unit/llms/ragflow/vector_stores/test_ragflow_vector_stores_transformation.py
@@ -0,0 +1,253 @@
+"""
+Test RAGFlow Vector Store helper functions and transformation.
+"""
+
+import os
+from unittest.mock import MagicMock, Mock, patch
+
+import httpx
+import pytest
+
+from litellm.llms.base_llm.chat.transformation import BaseLLMException
+from litellm.llms.ragflow.vector_stores.transformation import RAGFlowVectorStoreConfig
+from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+from litellm.types.vector_stores import VectorStoreCreateOptionalRequestParams
+
+
+def test_get_auth_credentials():
+ """Test that auth credentials are correctly extracted."""
+ config = RAGFlowVectorStoreConfig()
+
+ litellm_params = {"api_key": "test-api-key-123"}
+ credentials = config.get_auth_credentials(litellm_params)
+ assert "headers" in credentials
+ assert credentials["headers"]["Authorization"] == "Bearer test-api-key-123"
+
+ with pytest.raises(ValueError, match="api_key is required"):
+ config.get_auth_credentials({})
+
+
+def test_get_complete_url():
+ """Test that complete URL is correctly constructed."""
+ config = RAGFlowVectorStoreConfig()
+
+ litellm_params = {"api_base": "http://custom-host:9999"}
+ url = config.get_complete_url(api_base=None, litellm_params=litellm_params)
+ assert url == "http://custom-host:9999/api/v1/datasets"
+
+ url = config.get_complete_url(api_base="http://test-host:8888", litellm_params={})
+ assert url == "http://test-host:8888/api/v1/datasets"
+
+ with patch.dict(os.environ, {}, clear=True):
+ url = config.get_complete_url(api_base=None, litellm_params={})
+ assert url == "http://localhost:9380/api/v1/datasets"
+
+ url = config.get_complete_url(api_base="http://test-host:8888/", litellm_params={})
+ assert url == "http://test-host:8888/api/v1/datasets"
+
+
+def test_validate_environment():
+ """Test environment validation and header setting."""
+ config = RAGFlowVectorStoreConfig()
+ from litellm.types.router import GenericLiteLLMParams
+
+ litellm_params = GenericLiteLLMParams(api_key="test-key")
+ headers = config.validate_environment({}, litellm_params)
+ assert headers["Authorization"] == "Bearer test-key"
+ assert headers["Content-Type"] == "application/json"
+
+ with pytest.raises(ValueError, match="RAGFLOW_API_KEY"):
+ config.validate_environment({}, GenericLiteLLMParams())
+
+
+def test_get_vector_store_endpoints_by_type():
+ """Test that endpoints are correctly configured (empty for management only)."""
+ config = RAGFlowVectorStoreConfig()
+ endpoints = config.get_vector_store_endpoints_by_type()
+ assert endpoints["read"] == []
+ assert endpoints["write"] == []
+
+
+def test_transform_create_vector_store_request_basic():
+ """Test basic dataset creation request transformation."""
+ config = RAGFlowVectorStoreConfig()
+
+ params: VectorStoreCreateOptionalRequestParams = {"name": "test-dataset"}
+
+ url, body = config.transform_create_vector_store_request(
+ params, "http://localhost:9380/api/v1/datasets"
+ )
+
+ assert url == "http://localhost:9380/api/v1/datasets"
+ assert body["name"] == "test-dataset"
+ assert body["chunk_method"] == "naive"
+
+
+def test_transform_create_vector_store_request_with_metadata():
+ """Test dataset creation with RAGFlow-specific metadata."""
+ config = RAGFlowVectorStoreConfig()
+
+ params: VectorStoreCreateOptionalRequestParams = {
+ "name": "test-dataset-advanced",
+ "metadata": {
+ "description": "Test dataset",
+ "embedding_model": "BAAI/bge-large-zh-v1.5@BAAI",
+ "permission": "me",
+ "chunk_method": "naive",
+ "parser_config": {"chunk_token_num": 512, "delimiter": "\n"},
+ },
+ }
+
+ url, body = config.transform_create_vector_store_request(
+ params, "http://localhost:9380/api/v1/datasets"
+ )
+
+ assert body["name"] == "test-dataset-advanced"
+ assert body["description"] == "Test dataset"
+ assert body["embedding_model"] == "BAAI/bge-large-zh-v1.5@BAAI"
+ assert body["permission"] == "me"
+ assert body["chunk_method"] == "naive"
+ assert "parser_config" in body
+ assert body["parser_config"]["chunk_token_num"] == 512
+
+
+def test_transform_create_vector_store_request_missing_name():
+ """Test that missing name raises ValueError."""
+ config = RAGFlowVectorStoreConfig()
+
+ params: VectorStoreCreateOptionalRequestParams = {}
+
+ with pytest.raises(ValueError, match="name is required"):
+ config.transform_create_vector_store_request(
+ params, "http://localhost:9380/api/v1/datasets"
+ )
+
+
+def test_transform_create_vector_store_request_mutually_exclusive():
+ """Test that chunk_method and pipeline_id are mutually exclusive."""
+ config = RAGFlowVectorStoreConfig()
+
+ params: VectorStoreCreateOptionalRequestParams = {
+ "name": "test-dataset",
+ "metadata": {
+ "chunk_method": "naive",
+ "pipeline_id": "d0bebe30ae2211f0970942010a8e0005",
+ },
+ }
+
+ with pytest.raises(ValueError, match="mutually exclusive"):
+ config.transform_create_vector_store_request(
+ params, "http://localhost:9380/api/v1/datasets"
+ )
+
+
+def test_transform_create_vector_store_request_with_pipeline():
+ """Test dataset creation with ingestion pipeline."""
+ config = RAGFlowVectorStoreConfig()
+
+ params: VectorStoreCreateOptionalRequestParams = {
+ "name": "test-pipeline-dataset",
+ "metadata": {
+ "parse_type": 2,
+ "pipeline_id": "d0bebe30ae2211f0970942010a8e0005",
+ },
+ }
+
+ url, body = config.transform_create_vector_store_request(
+ params, "http://localhost:9380/api/v1/datasets"
+ )
+
+ assert body["name"] == "test-pipeline-dataset"
+ assert body["parse_type"] == 2
+ assert body["pipeline_id"] == "d0bebe30ae2211f0970942010a8e0005"
+ assert "chunk_method" not in body
+
+
+def test_transform_create_vector_store_response_success():
+ """Test successful response transformation."""
+ config = RAGFlowVectorStoreConfig()
+
+ mock_response = Mock(spec=httpx.Response)
+ mock_response.status_code = 200
+ mock_response.headers = {}
+ mock_response.json.return_value = {
+ "code": 0,
+ "data": {
+ "id": "3b4de7d4241d11f0a6a79f24fc270c7f",
+ "name": "test-dataset",
+ "create_time": 1745836841611,
+ "chunk_method": "naive",
+ "embedding_model": "BAAI/bge-large-zh-v1.5@BAAI",
+ },
+ }
+
+ response = config.transform_create_vector_store_response(mock_response)
+
+ assert response["id"] == "3b4de7d4241d11f0a6a79f24fc270c7f"
+ assert response["name"] == "test-dataset"
+ assert response["object"] == "vector_store"
+ assert response["status"] == "completed"
+ assert response["created_at"] == 1745836841
+ assert response["bytes"] == 0
+ assert "file_counts" in response
+
+
+def test_transform_create_vector_store_response_error():
+ """Test error response transformation."""
+ config = RAGFlowVectorStoreConfig()
+
+ mock_response = Mock(spec=httpx.Response)
+ mock_response.status_code = 400
+ mock_response.headers = {}
+ mock_response.json.return_value = {
+ "code": 101,
+ "message": "Dataset name 'test-dataset' already exists",
+ }
+
+ with pytest.raises(BaseLLMException):
+ config.transform_create_vector_store_response(mock_response)
+
+
+def test_transform_create_vector_store_response_missing_id():
+ """Test response with missing dataset ID."""
+ config = RAGFlowVectorStoreConfig()
+
+ mock_response = Mock(spec=httpx.Response)
+ mock_response.status_code = 200
+ mock_response.headers = {}
+ mock_response.json.return_value = {
+ "code": 0,
+ "data": {
+ "name": "test-dataset"
+ },
+ }
+
+ with pytest.raises(ValueError, match="missing dataset id"):
+ config.transform_create_vector_store_response(mock_response)
+
+
+def test_transform_search_vector_store_request_not_implemented():
+ """Test that search operations raise NotImplementedError."""
+ config = RAGFlowVectorStoreConfig()
+ logging_obj = MagicMock(spec=LiteLLMLoggingObj)
+
+ with pytest.raises(NotImplementedError, match="management only"):
+ config.transform_search_vector_store_request(
+ vector_store_id="test-id",
+ query="test query",
+ vector_store_search_optional_params={},
+ api_base="http://localhost:9380",
+ litellm_logging_obj=logging_obj,
+ litellm_params={},
+ extra_body=None,
+ )
+
+
+def test_transform_search_vector_store_response_not_implemented():
+ """Test that search response transformation raises NotImplementedError."""
+ config = RAGFlowVectorStoreConfig()
+ logging_obj = MagicMock(spec=LiteLLMLoggingObj)
+ mock_response = Mock(spec=httpx.Response)
+
+ with pytest.raises(NotImplementedError, match="management only"):
+ config.transform_search_vector_store_response(mock_response, logging_obj)
diff --git a/tests/unit/llms/vertex_ai/test_vertex_ai_search_vector_store_transformation.py b/tests/unit/llms/vertex_ai/test_vertex_ai_search_vector_store_transformation.py
index f3a276f7e46..256bebc1c75 100644
--- a/tests/unit/llms/vertex_ai/test_vertex_ai_search_vector_store_transformation.py
+++ b/tests/unit/llms/vertex_ai/test_vertex_ai_search_vector_store_transformation.py
@@ -1,7 +1,11 @@
+import json
from collections.abc import Mapping
from types import SimpleNamespace
+from typing import Final
+import httpx
import pytest
+import respx
from litellm.exceptions import BadRequestError
from litellm.llms.vertex_ai.vector_stores.search_api.transformation import (
@@ -484,3 +488,138 @@ def test_search_response_keeps_link_metadata_and_positional_scores():
def test_search_response_without_results_key_is_empty():
assert _search_response({"totalSize": 0})["data"] == []
+
+
+MOCK_VERTEX_SEARCH_RESPONSE: Final = {
+ "results": [
+ {
+ "id": "0",
+ "document": {
+ "name": "projects/648660250433/locations/global/collections/default_collection/dataStores/litellm-docs_1761094140318/branches/0/documents/0",
+ "id": "0",
+ "derivedStructData": {
+ "htmlTitle": "<b>LiteLLM</b> - Getting Started | <b>liteLLM</b>",
+ "snippets": [
+ {
+ "htmlSnippet": "https://github.com/BerriAI/<b>litellm</b>.",
+ "snippet": "https://github.com/BerriAI/litellm.",
+ }
+ ],
+ "title": "LiteLLM - Getting Started | liteLLM",
+ "link": "https://docs.litellm.ai/docs/",
+ "displayLink": "docs.litellm.ai",
+ },
+ },
+ },
+ {
+ "id": "1",
+ "document": {
+ "name": "projects/648660250433/locations/global/collections/default_collection/dataStores/litellm-docs_1761094140318/branches/0/documents/1",
+ "id": "1",
+ "derivedStructData": {
+ "title": "Using Vector Stores (Knowledge Bases) | liteLLM",
+ "link": "https://docs.litellm.ai/docs/completion/knowledgebase",
+ "snippets": [
+ {
+ "snippet": "LiteLLM integrates with vector stores, allowing your models to access your organization's data."
+ }
+ ],
+ },
+ },
+ },
+ ],
+ "totalSize": 299,
+ "attributionToken": "mock_token",
+ "summary": {},
+}
+GOOGLE_TOKEN_URL: Final = "https://oauth2.googleapis.com/token"
+VERTEX_AUTHORIZED_USER_CREDENTIALS: Final = json.dumps(
+ {
+ "type": "authorized_user",
+ "client_id": "unit-client-id",
+ "client_secret": "unit-client-secret",
+ "refresh_token": "unit-refresh-token",
+ "quota_project_id": "test-vector-store-db",
+ }
+)
+
+
+def _mock_google_token_refresh(requests_mock) -> None:
+ requests_mock.post(
+ GOOGLE_TOKEN_URL,
+ json={"access_token": "ya29.unit-token", "expires_in": 3600, "token_type": "Bearer"},
+ )
+
+
+def _mock_vertex_search(respx_mock) -> "respx.Route":
+ return respx_mock.post(url__regex=r"https://discoveryengine\.googleapis\.com/.*:search.*").mock(
+ return_value=httpx.Response(200, json=MOCK_VERTEX_SEARCH_RESPONSE)
+ )
+
+
+async def test_basic_search_with_mock(respx_mock, requests_mock, monkeypatch: pytest.MonkeyPatch):
+ """Test basic vector search with mocked backend response"""
+ import litellm
+
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ _mock_google_token_refresh(requests_mock)
+ search_route = _mock_vertex_search(respx_mock)
+
+ response = await litellm.vector_stores.asearch(
+ query="what is LiteLLM?",
+ vector_store_id="test-litellm-app_1761094730750",
+ custom_llm_provider="vertex_ai/search_api",
+ vertex_project="test-vector-store-db",
+ vertex_location="us-central1",
+ vertex_credentials=VERTEX_AUTHORIZED_USER_CREDENTIALS,
+ )
+
+ assert response is not None
+ assert response["object"] == "vector_store.search_results.page"
+ assert len(response["data"]) > 0
+ assert "search_query" in response
+
+ first_result = response["data"][0]
+ assert len(first_result["content"]) > 0
+ assert first_result["content"][0]["type"] == "text"
+ assert "text" in first_result["content"][0]
+
+ search_request = search_route.calls.last.request
+ url = str(search_request.url)
+ assert "discoveryengine.googleapis.com" in url
+ assert "test-vector-store-db" in url
+ assert "test-litellm-app_1761094730750" in url
+ assert search_request.headers["authorization"] == "Bearer ya29.unit-token"
+
+
+def test_basic_search_sync_with_mock(respx_mock, requests_mock):
+ """Test basic vector search (sync) with mocked backend response"""
+ _mock_google_token_refresh(requests_mock)
+ search_route = _mock_vertex_search(respx_mock)
+
+ response = __import__("litellm").vector_stores.search(
+ query="what is LiteLLM?",
+ vector_store_id="test-litellm-app_1761094730750",
+ custom_llm_provider="vertex_ai/search_api",
+ vertex_project="test-vector-store-db",
+ vertex_location="us-central1",
+ vertex_credentials=VERTEX_AUTHORIZED_USER_CREDENTIALS,
+ )
+
+ assert response is not None
+ assert response["object"] == "vector_store.search_results.page"
+ assert len(response["data"]) > 0
+ assert "search_query" in response
+
+ first_result = response["data"][0]
+ assert len(first_result["content"]) > 0
+ assert first_result["content"][0]["type"] == "text"
+ assert "text" in first_result["content"][0]
+
+ assert "document_id" in first_result["attributes"]
+ assert "link" in first_result["attributes"]
+ assert "title" in first_result["attributes"]
+
+ assert search_route.call_count == 1
+ assert search_route.calls.last.request.headers["authorization"] == "Bearer ya29.unit-token"
diff --git a/tests/unit/proxy/pass_through_endpoints/test_llm_passthrough_endpoints.py b/tests/unit/proxy/pass_through_endpoints/test_llm_passthrough_endpoints.py
index 59239786584..98ea2269252 100644
--- a/tests/unit/proxy/pass_through_endpoints/test_llm_passthrough_endpoints.py
+++ b/tests/unit/proxy/pass_through_endpoints/test_llm_passthrough_endpoints.py
@@ -1,8 +1,10 @@
import asyncio
import importlib
import json
+from typing import Final
import pytest
+import respx
import litellm
from litellm import Router
@@ -198,3 +200,60 @@ def setup_and_teardown():
yield
loop.close()
asyncio.set_event_loop(None)
+
+
+async def test_gemini_pass_through_endpoint_forwards_key_and_body(
+ respx_mock: "respx.MockRouter", httpx_transport: None, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ import httpx
+ from fastapi import Request, Response
+
+ from litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints import (
+ gemini_proxy_route,
+ )
+
+ monkeypatch.setenv("GEMINI_API_KEY", "gemini-test-key")
+ endpoint: Final = "v1beta/models/gemini-2.5-flash:countTokens"
+ upstream: Final = respx_mock.post(
+ url__startswith=f"https://generativelanguage.googleapis.com/{endpoint}"
+ ).mock(
+ return_value=httpx.Response(
+ 200,
+ json={"totalTokens": 9},
+ )
+ )
+ body: Final = json.dumps(
+ {"contents": [{"parts": [{"text": "The quick brown fox jumps over the lazy dog."}]}]}
+ ).encode()
+ scope: Final = {
+ "type": "http",
+ "http_version": "1.1",
+ "method": "POST",
+ "scheme": "http",
+ "path": f"/gemini/{endpoint}",
+ "raw_path": f"/gemini/{endpoint}".encode(),
+ "root_path": "",
+ "query_string": b"key=sk-9876",
+ "headers": [(b"content-type", b"application/json")],
+ "client": ("127.0.0.1", 51234),
+ "server": ("proxy.local", 4000),
+ "state": {},
+ }
+
+ async def receive() -> dict:
+ return {"type": "http.request", "body": body, "more_body": False}
+
+ response: Final = await gemini_proxy_route(
+ endpoint=f"{endpoint}?key=sk-9876",
+ request=Request(scope, receive),
+ fastapi_response=Response(),
+ )
+
+ assert response.status_code == 200
+ assert json.loads(response.body) == {"totalTokens": 9}
+ assert upstream.call_count == 1
+ outbound: Final = upstream.calls[0].request
+ assert outbound.url.path == f"/{endpoint}"
+ assert outbound.url.params["key"] == "gemini-test-key"
+ assert json.loads(outbound.content) == json.loads(body)
diff --git a/tests/proxy_unit_tests/test_configs/custom_callbacks.py b/tests/unit/proxy/test_configs/custom_callbacks.py
similarity index 98%
rename from tests/proxy_unit_tests/test_configs/custom_callbacks.py
rename to tests/unit/proxy/test_configs/custom_callbacks.py
index c7d66c068e9..20d8088b30d 100644
--- a/tests/proxy_unit_tests/test_configs/custom_callbacks.py
+++ b/tests/unit/proxy/test_configs/custom_callbacks.py
@@ -1,3 +1,5 @@
+import threading
+
from litellm.integrations.custom_logger import CustomLogger
import inspect
import litellm
@@ -20,6 +22,7 @@ class testCustomCallbackProxy(CustomLogger):
self.async_embedding_kwargs_fail = None # type: ignore
self.streaming_response_obj = None # type: ignore
+ self.done_event = threading.Event()
blue_color_code = "\033[94m"
reset_color_code = "\033[0m"
print(f"{blue_color_code}Initialized LiteLLM custom logger")
@@ -74,6 +77,7 @@ class testCustomCallbackProxy(CustomLogger):
self.streaming_response_obj = response_obj
self.async_completion_kwargs = kwargs
+ self.done_event.set()
model = kwargs.get("model", None)
messages = kwargs.get("messages", None)
diff --git a/tests/proxy_unit_tests/test_configs/test_bad_config.yaml b/tests/unit/proxy/test_configs/test_bad_config.yaml
similarity index 70%
rename from tests/proxy_unit_tests/test_configs/test_bad_config.yaml
rename to tests/unit/proxy/test_configs/test_bad_config.yaml
index 4bc4c7cc541..72ceefcda2d 100644
--- a/tests/proxy_unit_tests/test_configs/test_bad_config.yaml
+++ b/tests/unit/proxy/test_configs/test_bad_config.yaml
@@ -6,16 +6,15 @@ model_list:
- model_name: working-azure-gpt-3.5-turbo
litellm_params:
model: azure/gpt-4.1-mini
- api_base: os.environ/AZURE_AI_API_BASE
- api_key: os.environ/AZURE_AI_API_KEY
+ api_base: https://azure-unit.example.com
+ api_key: bad-key
- model_name: azure-gpt-3.5-turbo
litellm_params:
model: azure/gpt-4.1-mini
- api_base: os.environ/AZURE_AI_API_BASE
+ api_base: https://azure-unit.example.com
api_key: bad-key
- model_name: azure-embedding
litellm_params:
model: azure/text-embedding-ada-002
- api_base: os.environ/AZURE_AI_API_BASE
+ api_base: https://azure-unit.example.com
api_key: bad-key
-
\ No newline at end of file
diff --git a/tests/proxy_unit_tests/test_configs/test_custom_logger.yaml b/tests/unit/proxy/test_configs/test_custom_logger.yaml
similarity index 70%
rename from tests/proxy_unit_tests/test_configs/test_custom_logger.yaml
rename to tests/unit/proxy/test_configs/test_custom_logger.yaml
index 6ff1b086357..c58df01b602 100644
--- a/tests/proxy_unit_tests/test_configs/test_custom_logger.yaml
+++ b/tests/unit/proxy/test_configs/test_custom_logger.yaml
@@ -1,8 +1,8 @@
-model_list:
+model_list:
- model_name: Azure OpenAI GPT-4 Canada
litellm_params:
model: gpt-4.1-nano
- api_key: os.environ/OPENAI_API_KEY
+ api_key: sk-unit-fake
model_info:
mode: chat
input_cost_per_token: 0.0002
@@ -10,7 +10,7 @@ model_list:
- model_name: azure-embedding-model
litellm_params:
model: text-embedding-ada-002
- api_key: os.environ/OPENAI_API_KEY
+ api_key: sk-unit-fake
model_info:
mode: embedding
input_cost_per_token: 0.002
@@ -18,5 +18,4 @@ model_list:
litellm_settings:
drop_params: True
- set_verbose: True
- callbacks: custom_callbacks.my_custom_logger
\ No newline at end of file
+ callbacks: custom_callbacks.my_custom_logger
diff --git a/tests/unit/proxy/test_proxy_server_custom_logger.py b/tests/unit/proxy/test_proxy_server_custom_logger.py
new file mode 100644
index 00000000000..a9cf111880e
--- /dev/null
+++ b/tests/unit/proxy/test_proxy_server_custom_logger.py
@@ -0,0 +1,203 @@
+import asyncio
+import json
+import os
+from pathlib import Path
+from typing import Final
+
+import httpx
+import pytest
+import respx
+from fastapi.testclient import TestClient
+
+import litellm
+
+CONFIG_DIR: Final = Path(__file__).resolve().parent / "test_configs"
+CUSTOM_CALLBACKS_PATH: Final = CONFIG_DIR / "custom_callbacks.py"
+OPENAI_BASE: Final = "https://api.openai.com/v1"
+
+CHAT_COMPLETION_BODY: Final = {
+ "id": "chatcmpl-unit-1",
+ "object": "chat.completion",
+ "created": 1700000000,
+ "model": "gpt-4.1-nano",
+ "choices": [
+ {
+ "index": 0,
+ "message": {"role": "assistant", "content": "litellm poem"},
+ "finish_reason": "stop",
+ }
+ ],
+ "usage": {"prompt_tokens": 9, "completion_tokens": 3, "total_tokens": 12},
+}
+
+EMBEDDING_BODY: Final = {
+ "object": "list",
+ "data": [{"object": "embedding", "index": 0, "embedding": [0.1, 0.2, 0.3]}],
+ "model": "text-embedding-ada-002",
+ "usage": {"prompt_tokens": 1, "total_tokens": 1},
+}
+
+STREAM_CHUNK_1: Final = {
+ "id": "chatcmpl-unit-stream",
+ "object": "chat.completion.chunk",
+ "created": 1700000000,
+ "model": "gpt-4.1-nano",
+ "choices": [
+ {"index": 0, "delta": {"role": "assistant", "content": "Lite"}, "finish_reason": None}
+ ],
+}
+STREAM_CHUNK_2: Final = {
+ "id": "chatcmpl-unit-stream",
+ "object": "chat.completion.chunk",
+ "created": 1700000000,
+ "model": "gpt-4.1-nano",
+ "choices": [{"index": 0, "delta": {"content": "LLM"}, "finish_reason": "stop"}],
+}
+STREAM_BODY: Final = (
+ f"data: {json.dumps(STREAM_CHUNK_1)}\n\n"
+ f"data: {json.dumps(STREAM_CHUNK_2)}\n\n"
+ "data: [DONE]\n\n"
+).encode()
+
+
+def client(monkeypatch: pytest.MonkeyPatch, httpx_transport: None) -> TestClient:
+ from litellm.proxy.proxy_server import (
+ app,
+ cleanup_router_config_variables,
+ initialize,
+ )
+
+ monkeypatch.setenv("LITELLM_DANGEROUSLY_PERMIT_WEAK_OR_UNSET_MASTER_KEY", "true")
+ cleanup_router_config_variables()
+ asyncio.run(initialize(config=str(CONFIG_DIR / "test_custom_logger.yaml")))
+ return TestClient(app)
+
+
+def _custom_logger() -> object:
+ from litellm.proxy.types_utils.utils import get_instance_fn
+
+ return get_instance_fn(
+ value="custom_callbacks.my_custom_logger",
+ config_file_path=str(CUSTOM_CALLBACKS_PATH),
+ )
+
+
+def test_chat_completion(client: TestClient, respx_mock: respx.MockRouter) -> None:
+ upstream: Final = respx_mock.post(f"{OPENAI_BASE}/chat/completions").mock(
+ return_value=httpx.Response(200, json=CHAT_COMPLETION_BODY)
+ )
+ my_custom_logger = _custom_logger()
+ litellm.callbacks = [my_custom_logger]
+
+ response: Final = client.post(
+ "/chat/completions",
+ json={
+ "model": "Azure OpenAI GPT-4 Canada",
+ "messages": [{"role": "user", "content": "write a litellm poem"}],
+ "max_tokens": 10,
+ },
+ )
+
+ assert response.status_code == 200, response.text
+ assert my_custom_logger.done_event.wait(10)
+ assert my_custom_logger.async_success is True
+ assert my_custom_logger.async_completion_kwargs["model"] == "gpt-4.1-nano"
+ litellm_params: Final = my_custom_logger.async_completion_kwargs["litellm_params"]
+
+ metadata: Final = litellm_params.get("metadata")
+ assert "user_api_key" in metadata
+ assert "user_api_key_metadata" in metadata
+ assert "headers" in metadata
+
+ model_info: Final = litellm_params.get("model_info")
+ assert model_info.get("id") == "gm"
+ assert model_info.get("mode") == "chat"
+ assert model_info.get("input_cost_per_token") == 0.0002
+
+ proxy_server_request: Final = litellm_params.get("proxy_server_request")
+ assert proxy_server_request.get("url") == "http://testserver/chat/completions"
+ assert proxy_server_request.get("method") == "POST"
+ assert "authorization" not in proxy_server_request["headers"]
+ body: Final = proxy_server_request["body"]
+ assert body.get("model") == "Azure OpenAI GPT-4 Canada"
+ assert body.get("messages") == [
+ {"role": "user", "content": "write a litellm poem"}
+ ]
+ assert body.get("max_tokens") == 10
+ assert upstream.call_count == 1
+
+
+def test_chat_completion_stream(client: TestClient, respx_mock: respx.MockRouter) -> None:
+ upstream: Final = respx_mock.post(f"{OPENAI_BASE}/chat/completions").mock(
+ return_value=httpx.Response(
+ 200, content=STREAM_BODY, headers={"content-type": "text/event-stream"}
+ )
+ )
+ my_custom_logger = _custom_logger()
+ litellm.callbacks = [my_custom_logger]
+ assert my_custom_logger.streaming_response_obj is None
+
+ response: Final = client.post(
+ "/chat/completions",
+ json={
+ "model": "Azure OpenAI GPT-4 Canada",
+ "messages": [{"role": "user", "content": "write 1 line poem about LiteLLM"}],
+ "max_tokens": 40,
+ "stream": True,
+ },
+ )
+
+ assert response.status_code == 200, response.text
+ complete_response: Final = "".join(
+ json.loads(data)["choices"][0]["delta"].get("content") or ""
+ for data in (
+ line.replace("data: ", "") for line in response.iter_lines() if line
+ )
+ if "[DONE]" not in data
+ )
+
+ assert complete_response == "LiteLLM"
+ assert my_custom_logger.done_event.wait(10)
+ assert (
+ complete_response
+ == my_custom_logger.streaming_response_obj["choices"][0]["message"]["content"]
+ )
+ assert upstream.call_count == 1
+
+
+def test_embedding(client: TestClient, respx_mock: respx.MockRouter) -> None:
+ upstream: Final = respx_mock.post(f"{OPENAI_BASE}/embeddings").mock(
+ return_value=httpx.Response(200, json=EMBEDDING_BODY)
+ )
+ my_custom_logger = _custom_logger()
+ litellm.callbacks = [my_custom_logger]
+ assert my_custom_logger.async_success_embedding is False
+
+ response: Final = client.post(
+ "/embeddings",
+ json={"model": "azure-embedding-model", "input": ["hello"]},
+ )
+
+ assert response.status_code == 200, response.text
+ assert my_custom_logger.done_event.wait(10)
+ assert my_custom_logger.async_success_embedding is True
+ assert my_custom_logger.async_embedding_kwargs["model"] == "text-embedding-ada-002"
+ litellm_params: Final = my_custom_logger.async_embedding_kwargs["litellm_params"]
+
+ metadata: Final = litellm_params.get("metadata")
+ assert "user_api_key" in metadata
+ assert "headers" in metadata
+
+ proxy_server_request: Final = litellm_params.get("proxy_server_request")
+ assert proxy_server_request.get("url") == "http://testserver/embeddings"
+ assert proxy_server_request.get("method") == "POST"
+ body: Final = proxy_server_request["body"]
+ assert body.get("model") == "azure-embedding-model"
+ assert body.get("input") == ["hello"]
+
+ model_info: Final = litellm_params.get("model_info")
+ assert model_info.get("mode") == "embedding"
+ assert model_info.get("id") == "hello"
+ assert model_info.get("input_cost_per_token") == 0.002
+ assert upstream.call_count == 1
diff --git a/tests/unit/proxy/test_proxy_server_exception_mapping.py b/tests/unit/proxy/test_proxy_server_exception_mapping.py
new file mode 100644
index 00000000000..dbb595f129a
--- /dev/null
+++ b/tests/unit/proxy/test_proxy_server_exception_mapping.py
@@ -0,0 +1,211 @@
+import asyncio
+import json
+from pathlib import Path
+from typing import Final
+
+import httpx
+import openai
+import pytest
+import respx
+from fastapi.testclient import TestClient
+
+CONFIG_DIR: Final = Path(__file__).resolve().parent / "test_configs"
+OPENAI_CHAT_COMPLETIONS: Final = "https://api.openai.com/v1/chat/completions"
+AZURE_CHAT_COMPLETIONS: Final = (
+ "https://azure-unit.example.com/openai/deployments/gpt-4.1-mini/chat/completions"
+)
+AZURE_EMBEDDINGS: Final = (
+ "https://azure-unit.example.com/openai/deployments/text-embedding-ada-002/embeddings"
+)
+
+AZURE_401_BODY: Final = {
+ "error": {"code": "401", "message": "Access denied due to invalid subscription key."}
+}
+CONTEXT_LENGTH_EXCEEDED_BODY: Final = {
+ "error": {
+ "message": "This model's maximum context length is 4096 tokens. However, your messages resulted in 10007 tokens. Please reduce the length of the messages.",
+ "type": "invalid_request_error",
+ "param": "messages",
+ "code": "context_length_exceeded",
+ }
+}
+
+
+def client(monkeypatch: pytest.MonkeyPatch, httpx_transport: None) -> TestClient:
+ from litellm.proxy.proxy_server import (
+ app,
+ cleanup_router_config_variables,
+ initialize,
+ )
+
+ monkeypatch.setenv("LITELLM_DANGEROUSLY_PERMIT_WEAK_OR_UNSET_MASTER_KEY", "true")
+ cleanup_router_config_variables()
+ asyncio.run(initialize(config=str(CONFIG_DIR / "test_bad_config.yaml")))
+ return TestClient(app)
+
+
+def _openai_exception(response: httpx.Response) -> openai.APIStatusError:
+ return openai.OpenAI(api_key="anything")._make_status_error_from_response(
+ response=response
+ )
+
+
+def test_chat_completion_exception(
+ client: TestClient, respx_mock: respx.MockRouter
+) -> None:
+ respx_mock.post(OPENAI_CHAT_COMPLETIONS).mock(
+ return_value=httpx.Response(
+ 401,
+ json={
+ "error": {
+ "message": "Incorrect API key provided: bad-key. You can find your API key at https://platform.openai.com/account/api-keys.",
+ "type": "invalid_request_error",
+ "param": None,
+ "code": "invalid_api_key",
+ }
+ },
+ )
+ )
+
+ response: Final = client.post(
+ "/chat/completions",
+ json={
+ "model": "gpt-3.5-turbo",
+ "messages": [{"role": "user", "content": "hi"}],
+ "max_tokens": 10,
+ },
+ )
+
+ json_response: Final = response.json()
+ assert json_response.keys() == {"error"}
+ assert "litellm.AuthenticationError: AuthenticationError" in json_response["error"]["message"]
+ assert type(json_response["error"]["code"]) is str
+ assert isinstance(_openai_exception(response), openai.AuthenticationError)
+
+
+def test_chat_completion_exception_azure(
+ client: TestClient, respx_mock: respx.MockRouter
+) -> None:
+ upstream: Final = respx_mock.post(AZURE_CHAT_COMPLETIONS).mock(
+ return_value=httpx.Response(401, json=AZURE_401_BODY)
+ )
+
+ response: Final = client.post(
+ "/chat/completions",
+ json={
+ "model": "azure-gpt-3.5-turbo",
+ "messages": [{"role": "user", "content": "hi"}],
+ "max_tokens": 10,
+ },
+ )
+
+ assert response.status_code == 401, response.text
+ json_response: Final = response.json()
+ assert json_response.keys() == {"error"}
+ assert "litellm.AuthenticationError" in json_response["error"]["message"]
+ assert upstream.call_count == 1
+ outbound: Final = upstream.calls[0].request
+ assert json.loads(outbound.content)["messages"] == [
+ {"role": "user", "content": "hi"}
+ ]
+ assert outbound.headers["api-key"] == "bad-key"
+ assert isinstance(_openai_exception(response), openai.AuthenticationError)
+
+
+def test_embedding_auth_exception_azure(
+ client: TestClient, respx_mock: respx.MockRouter
+) -> None:
+ upstream: Final = respx_mock.post(AZURE_EMBEDDINGS).mock(
+ return_value=httpx.Response(401, json=AZURE_401_BODY)
+ )
+
+ response: Final = client.post(
+ "/embeddings",
+ json={"model": "azure-embedding", "input": ["hi"]},
+ )
+
+ assert response.status_code == 401, response.text
+ json_response: Final = response.json()
+ assert json_response.keys() == {"error"}
+ assert upstream.call_count == 1
+ outbound: Final = upstream.calls[0].request
+ assert json.loads(outbound.content)["input"] == ["hi"]
+ assert outbound.headers["api-key"] == "bad-key"
+ assert isinstance(_openai_exception(response), openai.AuthenticationError)
+
+
+def test_exception_openai_bad_model(client: TestClient) -> None:
+ response: Final = client.post(
+ "/chat/completions",
+ json={
+ "model": "azure/GPT-12",
+ "messages": [{"role": "user", "content": "hi"}],
+ "max_tokens": 10,
+ },
+ )
+
+ json_response: Final = response.json()
+ assert json_response.keys() == {"error"}
+ assert isinstance(_openai_exception(response), openai.BadRequestError)
+
+
+def test_chat_completion_exception_any_model(client: TestClient) -> None:
+ response: Final = client.post(
+ "/chat/completions",
+ json={
+ "model": "Lite-GPT-12",
+ "messages": [{"role": "user", "content": "hi"}],
+ "max_tokens": 10,
+ },
+ )
+
+ json_response: Final = response.json()
+ assert json_response.keys() == {"error"}
+ openai_exception: Final = _openai_exception(response)
+ assert isinstance(openai_exception, openai.BadRequestError)
+ assert "/chat/completions: Invalid model name passed in model=Lite-GPT-12" in str(
+ openai_exception.message
+ )
+
+
+def test_embedding_exception_any_model(client: TestClient) -> None:
+ response: Final = client.post(
+ "/embeddings",
+ json={"model": "Lite-GPT-12", "input": ["hi"]},
+ )
+
+ json_response: Final = response.json()
+ assert json_response.keys() == {"error"}
+ openai_exception: Final = _openai_exception(response)
+ assert isinstance(openai_exception, openai.BadRequestError)
+ assert "/embeddings: Invalid model name passed in model=Lite-GPT-12" in str(
+ openai_exception.message
+ )
+
+
+def test_chat_completion_exception_azure_context_window(
+ client: TestClient, respx_mock: respx.MockRouter
+) -> None:
+ upstream: Final = respx_mock.post(AZURE_CHAT_COMPLETIONS).mock(
+ return_value=httpx.Response(400, json=CONTEXT_LENGTH_EXCEEDED_BODY)
+ )
+
+ response: Final = client.post(
+ "/chat/completions",
+ json={
+ "model": "working-azure-gpt-3.5-turbo",
+ "messages": [{"role": "user", "content": "hi" * 10000}],
+ "max_tokens": 10,
+ },
+ )
+
+ assert response.status_code == 400, response.text
+ json_response: Final = response.json()
+ assert json_response.keys() == {"error"}
+ assert upstream.call_count == 1
+ error: Final = json_response["error"]
+ assert "ContextWindowExceededError" in error["message"]
+ assert "maximum context length is 4096 tokens" in error["message"]
+ assert type(error["code"]) is str
+ assert isinstance(_openai_exception(response), openai.BadRequestError)
diff --git a/tests/unit/router_strategy/test_lowest_tpm_rpm_v2.py b/tests/unit/router_strategy/test_lowest_tpm_rpm_v2.py
index bbba7e5e20e..129bb10eccc 100644
--- a/tests/unit/router_strategy/test_lowest_tpm_rpm_v2.py
+++ b/tests/unit/router_strategy/test_lowest_tpm_rpm_v2.py
@@ -43,7 +43,7 @@ def restore_verbose_logger_level() -> Iterator[None]:
@pytest.mark.usefixtures("restore_verbose_logger_level")
def test_tpm_rpm_updated():
- from tests.local_testing.create_mock_standard_logging_payload import create_standard_logging_payload
+ from tests.unit.create_mock_standard_logging_payload import create_standard_logging_payload
test_cache = DualCache()
lowest_tpm_logger = LowestTPMLoggingHandler(router_cache=test_cache)
@@ -98,7 +98,7 @@ def test_tpm_rpm_updated():
@pytest.mark.usefixtures("restore_verbose_logger_level")
def test_get_available_deployments():
- from tests.local_testing.create_mock_standard_logging_payload import create_standard_logging_payload
+ from tests.unit.create_mock_standard_logging_payload import create_standard_logging_payload
test_cache = DualCache()
model_list = [
@@ -190,7 +190,7 @@ def test_router_get_available_deployments():
"""
Test if routers 'get_available_deployments' returns the lowest tpm deployment
"""
- from tests.local_testing.create_mock_standard_logging_payload import create_standard_logging_payload
+ from tests.unit.create_mock_standard_logging_payload import create_standard_logging_payload
model_list = [
{
@@ -287,7 +287,7 @@ def test_router_skip_rate_limited_deployments():
"""
Test if routers 'get_available_deployments' raises No Models Available error if max tpm would be reached by message
"""
- from tests.local_testing.create_mock_standard_logging_payload import create_standard_logging_payload
+ from tests.unit.create_mock_standard_logging_payload import create_standard_logging_payload
model_list = [
{
diff --git a/tests/unit/router_utils/test_prompt_caching_cache.py b/tests/unit/router_utils/test_prompt_caching_cache.py
index b0bf03498d4..3a1132354c4 100644
--- a/tests/unit/router_utils/test_prompt_caching_cache.py
+++ b/tests/unit/router_utils/test_prompt_caching_cache.py
@@ -1,8 +1,19 @@
+import asyncio
from typing import Final
+import pytest
+
from litellm.router_utils.prompt_caching_cache import PromptCachingCache
+async def _first_non_none(read):
+ while True:
+ value = await read()
+ if value is not None:
+ return value
+ await asyncio.sleep(0)
+
+
def test_extract_cacheable_prefix_with_string_content_and_message_level_cache_control():
"""
Test that extract_cacheable_prefix correctly handles messages where:
@@ -87,3 +98,89 @@ def test_extract_cacheable_prefix_mixed_string_and_list_content():
assert result[0]["role"] == "system"
assert result[1]["content"] == "First cached message"
assert isinstance(result[2]["content"], list)
+
+
+async def test_same_cacheable_prefix_routes_to_same_deployment() -> None:
+ from litellm import Router
+
+ def _messages(user_content: str):
+ return [
+ {
+ "role": "system",
+ "content": [
+ {
+ "type": "text",
+ "text": "You are an AI assistant tasked with analyzing legal documents.",
+ },
+ {
+ "type": "text",
+ "text": "Here is the full text of a complex legal agreement" * 400,
+ "cache_control": {"type": "ephemeral"},
+ },
+ ],
+ },
+ {"role": "user", "content": user_content},
+ ]
+
+ router: Final = Router(
+ model_list=[
+ {
+ "model_name": "test-model",
+ "litellm_params": {
+ "model": "gpt-5-mini",
+ "api_key": f"test-key-{i}",
+ },
+ "model_info": {"id": f"deployment-{i}"},
+ }
+ for i in range(1, 4)
+ ],
+ routing_strategy="simple-shuffle",
+ optional_pre_call_checks=["prompt_caching"],
+ )
+
+ messages1: Final = _messages("what are the key terms and conditions in this agreement?")
+ messages2: Final = _messages("how many words are there?")
+ messages3: Final = _messages("how many sentences are there?")
+
+ key1: Final = PromptCachingCache.get_prompt_caching_cache_key(messages1, None)
+ key2: Final = PromptCachingCache.get_prompt_caching_cache_key(messages2, None)
+ key3: Final = PromptCachingCache.get_prompt_caching_cache_key(messages3, None)
+
+ assert key1 is not None
+ assert key1 == key2 == key3
+
+ response1: Final = await router.acompletion(
+ model="test-model", messages=messages1, mock_response="ok"
+ )
+ model_id_1: Final = response1._hidden_params["model_id"]
+ assert model_id_1 in {"deployment-1", "deployment-2", "deployment-3"}
+
+ from litellm.integrations.anthropic_cache_control_hook import (
+ AnthropicCacheControlHook,
+ )
+
+ affinity_messages: Final = AnthropicCacheControlHook.messages_with_default_injections(
+ messages=messages2,
+ models=("gpt-5-mini",),
+ tools=None,
+ enable_prompt_caching=None,
+ request_kwargs={},
+ )
+ cache: Final = PromptCachingCache(cache=router.cache)
+ cached_2: Final = await asyncio.wait_for(
+ _first_non_none(lambda: cache.async_get_model_id(affinity_messages, None)),
+ timeout=10,
+ )
+ assert cached_2 == {"model_id": model_id_1}
+
+ response2: Final = await router.acompletion(
+ model="test-model", messages=messages2, mock_response="ok"
+ )
+ response3: Final = await router.acompletion(
+ model="test-model", messages=messages3, mock_response="ok"
+ )
+ model_id_2: Final = response2._hidden_params["model_id"]
+ model_id_3: Final = response3._hidden_params["model_id"]
+
+ assert model_id_1 == model_id_2 == model_id_3
diff --git a/tests/unit/test_assert_ci_coverage.py b/tests/unit/test_assert_ci_coverage.py
index 4c9fe1739e6..a3c2e933a46 100644
--- a/tests/unit/test_assert_ci_coverage.py
+++ b/tests/unit/test_assert_ci_coverage.py
@@ -433,7 +433,7 @@ def test_a_dockerfile_directory_entry_is_stale_because_only_an_exact_path_exempt
def test_a_workflow_that_names_a_file_clears_it_from_the_slice_check():
named = coverage._workflow_named_tokens()
assert named, "the workflows must name some test paths or the check proves nothing"
- assert any(coverage._token_covers(token, "tests/proxy_unit_tests/test_proxy_custom_logger.py") for token in named)
+ assert any(coverage._token_covers(token, "tests/unit/proxy/test_proxy_server_custom_logger.py") for token in named)
def test_the_slice_check_credits_only_workflows_never_the_circleci_config():
diff --git a/tests/test_litellm/test_check_unbounded_in_lists.py b/tests/unit/test_check_unbounded_in_lists.py
similarity index 100%
rename from tests/test_litellm/test_check_unbounded_in_lists.py
rename to tests/unit/test_check_unbounded_in_lists.py
diff --git a/tests/unit/test_circleci_path_filter.py b/tests/unit/test_circleci_path_filter.py
index fa30d878f9f..8962cded715 100644
--- a/tests/unit/test_circleci_path_filter.py
+++ b/tests/unit/test_circleci_path_filter.py
@@ -113,11 +113,6 @@ CI = [".github/workflows/test-unit.yml"]
("cost-map-only", ["model_prices_and_context_window.json"], "run"),
("cost-map-only", ["litellm/model_prices_and_context_window_backup.json"], "run"),
("cost-map-only", ["model_prices_and_context_window.schema.json"], "run"),
- (
- "cost-map-only",
- ["model_prices_and_context_window.json", "tests/test_litellm/test_x.py"],
- "run",
- ),
(
"cost-map-only",
["model_prices_and_context_window.json", "tests/unit/proxy/test_y.py"],
@@ -128,7 +123,7 @@ CI = [".github/workflows/test-unit.yml"]
["model_prices_and_context_window.json", "litellm/utils.py"],
"skip",
),
- ("cost-map-only", ["tests/test_litellm/test_x.py"], "skip"),
+ ("cost-map-only", ["tests/unit/proxy/test_y.py"], "skip"),
("cost-map-only", ["model_prices_and_context_window.json", "docs/pricing.md"], "skip"),
("cost-map-only", ["model_prices_and_context_window.json", "docs/foo.mdx"], "skip"),
("cost-map-only", [], "skip"),
diff --git a/tests/test_litellm/tracing/test_otlp_http.py b/tests/unit/tracing/test_otlp_http.py
similarity index 100%
rename from tests/test_litellm/tracing/test_otlp_http.py
rename to tests/unit/tracing/test_otlp_http.py
diff --git a/tests/vector_store_tests/base_vector_store_test.py b/tests/vector_store_tests/base_vector_store_test.py
deleted file mode 100644
index 1e61613decf..00000000000
--- a/tests/vector_store_tests/base_vector_store_test.py
+++ /dev/null
@@ -1,318 +0,0 @@
-import httpx
-import json
-import pytest
-from typing import Any, Dict, List
-from unittest.mock import MagicMock, Mock, patch
-from litellm._uuid import uuid
-import time
-import base64
-
-import litellm
-from abc import ABC, abstractmethod
-from litellm.integrations.custom_logger import CustomLogger
-from litellm.types.utils import StandardLoggingPayload
-
-
-class BaseVectorStoreTest(ABC):
- """
- Abstract base test class that enforces a common test across all test classes.
- """
-
- @abstractmethod
- def get_base_request_args(self) -> dict:
- """Must return the base request args"""
- pass
-
- @abstractmethod
- def get_base_create_vector_store_args(self) -> dict:
- """Must return the base create vector store args"""
- pass
-
- @pytest.mark.parametrize("sync_mode", [True, False])
- @pytest.mark.asyncio
- async def test_basic_search_vector_store(self, sync_mode):
- litellm.turn_on_debug()
- litellm.set_verbose = True
- base_request_args = self.get_base_request_args()
- default_query = base_request_args.pop("query", "Basic ping")
- try:
- if sync_mode:
- response = litellm.vector_stores.search(
- query=default_query, **base_request_args
- )
- else:
- response = await litellm.vector_stores.asearch(
- query=default_query, **base_request_args
- )
- except litellm.InternalServerError:
- pytest.skip("Skipping test due to litellm.InternalServerError")
-
- print("litellm response=", json.dumps(response, indent=4, default=str))
-
- # Validate response structure
- self._validate_vector_store_response(response)
-
- @pytest.mark.parametrize("sync_mode", [True, False])
- @pytest.mark.asyncio
- async def test_basic_create_vector_store(self, sync_mode):
- litellm.turn_on_debug()
- litellm.set_verbose = True
- base_request_args = self.get_base_create_vector_store_args()
-
- # Extract custom_llm_provider from base args if present
- create_args = base_request_args
- try:
- if sync_mode:
- response = litellm.vector_stores.create(
- name="Test Vector Store", **create_args
- )
- else:
- response = await litellm.vector_stores.acreate(
- name="Test Vector Store", **create_args
- )
- except litellm.InternalServerError:
- pytest.skip("Skipping test due to litellm.InternalServerError")
- except Exception as e:
- # If this is an authentication or permission error, skip the test
- if (
- "authentication" in str(e).lower()
- or "permission" in str(e).lower()
- or "unauthorized" in str(e).lower()
- ):
- pytest.skip(
- f"Skipping test due to authentication/permission error: {e}"
- )
- raise
-
- print("litellm create response=", json.dumps(response, indent=4, default=str))
-
- # Validate response structure
- self._validate_vector_store_create_response(response)
-
- def _validate_vector_store_response(self, response):
- """Validate the structure and content of a vector store search response"""
-
- # Check that response is a dictionary
- assert isinstance(
- response, dict
- ), f"Response should be a dict, got {type(response)}"
-
- # Check required top-level fields
- required_fields = ["object", "search_query", "data"]
- for field in required_fields:
- assert field in response, f"Missing required field '{field}' in response"
-
- # Validate object field
- assert (
- response["object"] == "vector_store.search_results.page"
- ), f"Expected object to be 'vector_store.search_results.page', got '{response['object']}'"
-
- # Validate search_query field
- assert isinstance(
- response["search_query"], str
- ), f"search_query should be a list, got {type(response['search_query'])}"
- assert len(response["search_query"]) > 0, "search_query should not be empty"
- assert all(
- isinstance(query, str) for query in response["search_query"]
- ), "All items in search_query should be strings"
-
- # Validate data field
- assert isinstance(
- response["data"], list
- ), f"data should be a list, got {type(response['data'])}"
-
- # Validate each result in data
- for i, result in enumerate(response["data"]):
- self._validate_search_result(result, i)
-
- print(
- f"✅ Response validation passed: Found {len(response['data'])} search results"
- )
-
- def _validate_vector_store_create_response(self, response):
- """Validate the structure and content of a vector store create response"""
-
- # Check that response is a dictionary
- assert isinstance(
- response, dict
- ), f"Response should be a dict, got {type(response)}"
-
- # Check required top-level fields for create response
- required_fields = ["id", "object", "created_at"]
- for field in required_fields:
- assert (
- field in response
- ), f"Missing required field '{field}' in create response"
-
- # Validate object field
- assert (
- response["object"] == "vector_store"
- ), f"Expected object to be 'vector_store', got '{response['object']}'"
-
- # Validate id field
- assert isinstance(
- response["id"], str
- ), f"id should be a string, got {type(response['id'])}"
- assert len(response["id"]) > 0, "id should not be empty"
- assert response["id"].startswith(
- "vs_"
- ), f"id should start with 'vs_', got '{response['id']}'"
-
- # Validate created_at field
- assert isinstance(
- response["created_at"], int
- ), f"created_at should be an integer, got {type(response['created_at'])}"
- assert response["created_at"] > 0, "created_at should be a positive timestamp"
-
- # Validate optional fields if present
- if "name" in response:
- assert isinstance(
- response["name"], str
- ), f"name should be a string, got {type(response['name'])}"
-
- if "bytes" in response:
- assert isinstance(
- response["bytes"], int
- ), f"bytes should be an integer, got {type(response['bytes'])}"
- assert response["bytes"] >= 0, "bytes should be non-negative"
-
- if "file_counts" in response:
- self._validate_file_counts(response["file_counts"])
-
- if "status" in response:
- valid_statuses = ["expired", "in_progress", "completed"]
- assert (
- response["status"] in valid_statuses
- ), f"status should be one of {valid_statuses}, got '{response['status']}'"
-
- if "expires_at" in response and response["expires_at"] is not None:
- assert isinstance(
- response["expires_at"], int
- ), f"expires_at should be an integer, got {type(response['expires_at'])}"
-
- if "last_active_at" in response and response["last_active_at"] is not None:
- assert isinstance(
- response["last_active_at"], int
- ), f"last_active_at should be an integer, got {type(response['last_active_at'])}"
-
- if "metadata" in response and response["metadata"] is not None:
- assert isinstance(
- response["metadata"], dict
- ), f"metadata should be a dict, got {type(response['metadata'])}"
-
- print(
- f"✅ Create response validation passed: Vector store '{response['id']}' created successfully"
- )
-
- def _validate_file_counts(self, file_counts):
- """Validate file_counts structure"""
- assert isinstance(
- file_counts, dict
- ), f"file_counts should be a dict, got {type(file_counts)}"
-
- required_count_fields = [
- "in_progress",
- "completed",
- "failed",
- "cancelled",
- "total",
- ]
- for field in required_count_fields:
- assert (
- field in file_counts
- ), f"Missing required field '{field}' in file_counts"
- assert isinstance(
- file_counts[field], int
- ), f"{field} should be an integer, got {type(file_counts[field])}"
- assert file_counts[field] >= 0, f"{field} should be non-negative"
-
- # Validate that total equals sum of other counts
- calculated_total = (
- file_counts["in_progress"]
- + file_counts["completed"]
- + file_counts["failed"]
- + file_counts["cancelled"]
- )
- assert (
- file_counts["total"] == calculated_total
- ), f"total should equal sum of other counts ({calculated_total}), got {file_counts['total']}"
-
- def _validate_search_result(self, result, index):
- """Validate an individual search result"""
-
- # Check that result is a dictionary
- assert isinstance(
- result, dict
- ), f"Result {index} should be a dict, got {type(result)}"
-
- # Check required fields in each result
- required_result_fields = [
- "file_id",
- "filename",
- "score",
- "attributes",
- "content",
- ]
- for field in required_result_fields:
- assert (
- field in result
- ), f"Missing required field '{field}' in result {index}"
-
- # Validate file_id
- assert isinstance(
- result["file_id"], str
- ), f"file_id should be a string, got {type(result['file_id'])} in result {index}"
- assert (
- len(result["file_id"]) > 0
- ), f"file_id should not be empty in result {index}"
-
- # Validate filename
- assert isinstance(
- result["filename"], str
- ), f"filename should be a string, got {type(result['filename'])} in result {index}"
- assert (
- len(result["filename"]) > 0
- ), f"filename should not be empty in result {index}"
-
- # Validate score
- assert isinstance(
- result["score"], (int, float)
- ), f"score should be a number, got {type(result['score'])} in result {index}"
- assert (
- 0.0 <= result["score"] <= 1.0
- ), f"score should be between 0.0 and 1.0, got {result['score']} in result {index}"
-
- # Validate attributes
- assert isinstance(
- result["attributes"], dict
- ), f"attributes should be a dict, got {type(result['attributes'])} in result {index}"
-
- # Validate content
- assert isinstance(
- result["content"], list
- ), f"content should be a list, got {type(result['content'])} in result {index}"
- assert (
- len(result["content"]) > 0
- ), f"content should not be empty in result {index}"
-
- # Validate each content item
- for j, content_item in enumerate(result["content"]):
- assert isinstance(
- content_item, dict
- ), f"Content item {j} in result {index} should be a dict, got {type(content_item)}"
- assert (
- "type" in content_item
- ), f"Content item {j} in result {index} missing 'type' field"
- assert (
- "text" in content_item
- ), f"Content item {j} in result {index} missing 'text' field"
- assert isinstance(
- content_item["text"], str
- ), f"Content text should be a string in item {j} of result {index}"
- assert (
- len(content_item["text"]) > 0
- ), f"Content text should not be empty in item {j} of result {index}"
-
- print(
- f"✅ Result {index} validation passed: {result['filename']} (score: {result['score']:.4f})"
- )
diff --git a/tests/vector_store_tests/conftest.py b/tests/vector_store_tests/conftest.py
deleted file mode 100644
index 8c1e70b14bc..00000000000
--- a/tests/vector_store_tests/conftest.py
+++ /dev/null
@@ -1,53 +0,0 @@
-# conftest.py
-
-import importlib
-import os
-
-import pytest
-
-import litellm
-
-
[email protected](scope="function", autouse=True)
-def setup_and_teardown():
- """
- This fixture reloads litellm before every function. To speed up testing by removing callbacks being chained.
- """
- curr_dir = os.getcwd() # Get the current working directory
-
- from litellm import Router
-
- importlib.reload(litellm)
-
- try:
- if hasattr(litellm, "proxy") and hasattr(litellm.proxy, "proxy_server"):
- importlib.reload(litellm.proxy.proxy_server)
- except Exception as e:
- print(f"Error reloading litellm.proxy.proxy_server: {e}")
-
- 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
- custom_logger_tests = [
- item for item in items if "custom_logger" in item.parent.name
- ]
- other_tests = [item for item in items if "custom_logger" not in item.parent.name]
-
- # Sort tests based on their names
- custom_logger_tests.sort(key=lambda x: x.name)
- other_tests.sort(key=lambda x: x.name)
-
- # Reorder the items list
- items[:] = custom_logger_tests + other_tests
diff --git a/tests/vector_store_tests/rag/base_rag_tests.py b/tests/vector_store_tests/rag/base_rag_tests.py
deleted file mode 100644
index 70a78144b80..00000000000
--- a/tests/vector_store_tests/rag/base_rag_tests.py
+++ /dev/null
@@ -1,171 +0,0 @@
-"""
-Base RAG test class that enforces common tests across all providers.
-
-Providers should inherit from BaseRAGTest and implement the abstract methods.
-"""
-
-import uuid
-from abc import ABC, abstractmethod
-from typing import Any, Dict, Optional
-
-import pytest
-
-
-import litellm
-from litellm.types.rag import (
- RAGIngestOptions,
- OpenAIVectorStoreOptions,
- BedrockVectorStoreOptions,
-)
-
-
-class BaseRAGTest(ABC):
- """
- Abstract base test class for RAG ingestion tests.
-
- Providers should inherit from this class and implement:
- - get_base_ingest_options(): Returns provider-specific ingest options
- - query_vector_store(): Queries the vector store after ingestion
- """
-
- @abstractmethod
- def get_base_ingest_options(self) -> RAGIngestOptions:
- """
- Must return the base ingest options for the provider.
-
- Example for OpenAI:
- return {
- "vector_store": OpenAIVectorStoreOptions(
- custom_llm_provider="openai",
- )
- }
-
- Example for Bedrock:
- return {
- "vector_store": BedrockVectorStoreOptions(
- custom_llm_provider="bedrock",
- )
- }
- """
- pass
-
- @abstractmethod
- async def query_vector_store(
- self,
- vector_store_id: str,
- query: str,
- ) -> Optional[Dict[str, Any]]:
- """
- Query the vector store to verify ingestion.
-
- Args:
- vector_store_id: The ID of the vector store to query
- query: The search query
-
- Returns:
- Search results dict or None if no results found
- """
- pass
-
- def get_unique_filename(self, prefix: str = "test") -> str:
- """Generate a unique filename for test documents."""
- unique_id = uuid.uuid4().hex[:8]
- return f"{prefix}_{unique_id}.txt", unique_id
-
- @pytest.mark.asyncio
- async def test_basic_ingest(self):
- """
- Test basic text file ingestion to vector store.
- """
- litellm.turn_on_debug()
-
- filename, unique_id = self.get_unique_filename("basic_ingest")
- text_content = f"Test document {unique_id} for RAG ingestion.".encode("utf-8")
- file_data = (filename, text_content, "text/plain")
-
- ingest_options = self.get_base_ingest_options()
- ingest_options["name"] = f"test-basic-ingest-{unique_id}"
-
- try:
- response = await litellm.rag.aingest(
- ingest_options=ingest_options,
- file_data=file_data,
- )
-
- print(f"RAG Ingest Response: {response}")
-
- assert "id" in response
- assert response["id"].startswith("ingest_")
- assert "status" in response
- assert response["status"] in ["completed", "failed"]
- assert "vector_store_id" in response
-
- if response["status"] == "completed":
- assert response["vector_store_id"]
- print(f"Vector store ID: {response['vector_store_id']}")
-
- except litellm.InternalServerError:
- pytest.skip("Skipping test due to litellm.InternalServerError")
-
- @pytest.mark.asyncio
- async def test_ingest_and_query(self):
- """
- Test full RAG flow: ingest a document and then query it.
- """
- import asyncio
-
- litellm.turn_on_debug()
-
- filename, unique_id = self.get_unique_filename("ingest_query")
- text_content = f"""
- Test document {unique_id} for RAG ingestion and query.
- LiteLLM provides a unified interface for 100+ LLMs.
- This content should be retrievable via semantic search.
- """.encode(
- "utf-8"
- )
- file_data = (filename, text_content, "text/plain")
-
- ingest_options = self.get_base_ingest_options()
- ingest_options["name"] = f"test-ingest-query-{unique_id}"
-
- try:
- # Step 1: Ingest
- ingest_response = await litellm.rag.aingest(
- ingest_options=ingest_options,
- file_data=file_data,
- )
-
- print(f"Ingest Response: {ingest_response}")
- assert ingest_response["status"] == "completed"
- vector_store_id = ingest_response["vector_store_id"]
- assert vector_store_id
-
- # Step 2: Query with retry (indexing may take time)
- search_results = None
- max_retries = 10
- for attempt in range(max_retries):
- await asyncio.sleep(3)
-
- search_results = await self.query_vector_store(
- vector_store_id=vector_store_id,
- query=f"Test document {unique_id}",
- )
-
- if search_results:
- break
-
- print(
- f"Attempt {attempt + 1}/{max_retries}: "
- "Waiting for document to be indexed..."
- )
-
- print(f"Search Results: {search_results}")
-
- # Validate search results
- assert search_results is not None, "Document not found after retries"
-
- print("Query successful!")
-
- except litellm.InternalServerError:
- pytest.skip("Skipping test due to litellm.InternalServerError")
diff --git a/tests/vector_store_tests/rag/test_document.txt b/tests/vector_store_tests/rag/test_document.txt
deleted file mode 100644
index 3570e715e83..00000000000
--- a/tests/vector_store_tests/rag/test_document.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-Test document abc123 for RAG ingestion.
-This is a sample document to test the RAG ingest API.
-LiteLLM provides a unified interface for vector stores.
-
diff --git a/tests/vector_store_tests/rag/test_rag_bedrock.py b/tests/vector_store_tests/rag/test_rag_bedrock.py
deleted file mode 100644
index 90cf4a3a44e..00000000000
--- a/tests/vector_store_tests/rag/test_rag_bedrock.py
+++ /dev/null
@@ -1,88 +0,0 @@
-"""
-Bedrock Knowledge Base RAG ingestion tests.
-
-Requires environment variables:
-- AWS_ACCESS_KEY_ID
-- AWS_SECRET_ACCESS_KEY
-- AWS_REGION_NAME (optional, defaults to us-west-2)
-
-Optional (for using existing KB instead of auto-creating):
-- BEDROCK_KNOWLEDGE_BASE_ID
-"""
-
-import os
-from typing import Any, Dict, Optional
-
-import pytest
-
-
-import litellm
-from litellm.types.rag import RAGIngestOptions, BedrockVectorStoreOptions
-from tests.vector_store_tests.rag.base_rag_tests import BaseRAGTest
-
-
-class TestRAGBedrock(BaseRAGTest):
- """Test RAG Ingest with Bedrock Knowledge Base."""
-
- @pytest.fixture(autouse=True)
- def check_env_vars(self):
- """Check required environment variables before each test."""
- aws_key = os.environ.get("AWS_ACCESS_KEY_ID")
- aws_secret = os.environ.get("AWS_SECRET_ACCESS_KEY")
-
- if not aws_key or not aws_secret:
- pytest.skip("Skipping Bedrock test: AWS credentials required")
-
- def get_base_ingest_options(self) -> RAGIngestOptions:
- """
- Return Bedrock-specific ingest options.
-
- Uses unified interface - no vector_store_id means auto-create KB.
- If BEDROCK_KNOWLEDGE_BASE_ID is set, uses existing KB.
- """
- # Use existing KB if provided, otherwise auto-create
- existing_kb_id = os.environ.get("BEDROCK_KNOWLEDGE_BASE_ID")
-
- return {
- "vector_store": BedrockVectorStoreOptions(
- custom_llm_provider="bedrock",
- vector_store_id=existing_kb_id, # None = auto-create
- # wait_for_ingestion defaults to False - returns immediately
- ),
- }
-
- async def query_vector_store(
- self,
- vector_store_id: str,
- query: str,
- ) -> Optional[Dict[str, Any]]:
- """Query Bedrock Knowledge Base."""
- try:
- import boto3
- except ImportError:
- pytest.skip("boto3 required for Bedrock tests")
-
- session = boto3.Session(
- aws_access_key_id=os.environ.get("AWS_ACCESS_KEY_ID"),
- aws_secret_access_key=os.environ.get("AWS_SECRET_ACCESS_KEY"),
- region_name=os.environ.get("AWS_REGION_NAME", "us-west-2"),
- )
- bedrock_agent_runtime = session.client("bedrock-agent-runtime")
-
- response = bedrock_agent_runtime.retrieve(
- knowledgeBaseId=vector_store_id,
- retrievalQuery={"text": query},
- retrievalConfiguration={
- "vectorSearchConfiguration": {"numberOfResults": 5}
- },
- )
-
- if response.get("retrievalResults") and len(response["retrievalResults"]) > 0:
- # Check if query terms appear in results
- for result in response["retrievalResults"]:
- # Extract unique_id from query if present
- if query in result["content"]["text"]:
- return response
- # Return results even if exact match not found
- return response
- return None
diff --git a/tests/vector_store_tests/rag/test_rag_openai.py b/tests/vector_store_tests/rag/test_rag_openai.py
deleted file mode 100644
index f90519a17e6..00000000000
--- a/tests/vector_store_tests/rag/test_rag_openai.py
+++ /dev/null
@@ -1,140 +0,0 @@
-"""
-OpenAI RAG ingestion tests.
-"""
-
-from typing import Any, Dict, Optional
-
-import pytest
-
-
-import litellm
-from litellm.types.rag import RAGIngestOptions, OpenAIVectorStoreOptions
-from tests.vector_store_tests.rag.base_rag_tests import BaseRAGTest
-
-
-class TestRAGOpenAI(BaseRAGTest):
- """Test RAG Ingest with OpenAI provider."""
-
- def get_base_ingest_options(self) -> RAGIngestOptions:
- """Return OpenAI-specific ingest options."""
- return {
- "vector_store": OpenAIVectorStoreOptions(
- custom_llm_provider="openai",
- ),
- }
-
- async def query_vector_store(
- self,
- vector_store_id: str,
- query: str,
- ) -> Optional[Dict[str, Any]]:
- """Query OpenAI vector store."""
- search_response = await litellm.vector_stores.asearch(
- vector_store_id=vector_store_id,
- query=query,
- custom_llm_provider="openai",
- )
-
- if search_response.get("data") and len(search_response["data"]) > 0:
- return search_response
- return None
-
- @pytest.mark.asyncio
- async def test_rag_query_basic(self):
- """Test basic RAG query flow."""
- import asyncio
-
- litellm.turn_on_debug()
-
- # First ingest a document
- filename, unique_id = self.get_unique_filename("rag_query")
- text_content = (
- f"LiteLLM is a unified interface for 100+ LLMs. ID: {unique_id}".encode()
- )
-
- ingest_response = await litellm.rag.aingest(
- ingest_options=self.get_base_ingest_options(),
- file_data=(filename, text_content, "text/plain"),
- )
-
- # Check if ingestion succeeded
- if ingest_response["status"] != "completed":
- pytest.fail(
- f"Ingestion failed with status: {ingest_response['status']}, "
- f"error: {ingest_response.get('error', 'Unknown')}"
- )
-
- vector_store_id = ingest_response["vector_store_id"]
- assert vector_store_id, "vector_store_id should not be empty"
-
- # Wait for indexing
- await asyncio.sleep(10)
-
- # Query with RAG
- response = await litellm.rag.aquery(
- model="gpt-4o-mini",
- messages=[{"role": "user", "content": "What is LiteLLM?"}],
- retrieval_config={
- "vector_store_id": vector_store_id,
- "custom_llm_provider": "openai",
- "top_k": 5,
- },
- )
-
- print(f"RAG Query Response: {response}")
-
- assert response.choices[0].message.content
- assert "search_results" in response.choices[0].message.provider_specific_fields
-
- @pytest.mark.asyncio
- async def test_rag_query_with_rerank(self):
- """Test RAG query with reranking."""
- import asyncio
-
- litellm.turn_on_debug()
-
- # First ingest a document
- filename, unique_id = self.get_unique_filename("rag_query_rerank")
- text_content = (
- f"LiteLLM is a unified interface for 100+ LLMs. ID: {unique_id}".encode()
- )
-
- ingest_response = await litellm.rag.aingest(
- ingest_options=self.get_base_ingest_options(),
- file_data=(filename, text_content, "text/plain"),
- )
-
- # Check if ingestion succeeded
- if ingest_response["status"] != "completed":
- pytest.fail(
- f"Ingestion failed with status: {ingest_response['status']}, "
- f"error: {ingest_response.get('error', 'Unknown')}"
- )
-
- vector_store_id = ingest_response["vector_store_id"]
- assert vector_store_id, "vector_store_id should not be empty"
-
- # Wait for indexing
- await asyncio.sleep(10)
-
- # Query with RAG and rerank
- response = await litellm.rag.aquery(
- model="gpt-4o-mini",
- messages=[{"role": "user", "content": "What is LiteLLM?"}],
- retrieval_config={
- "vector_store_id": vector_store_id,
- "custom_llm_provider": "openai",
- "top_k": 5,
- },
- rerank={
- "enabled": True,
- "model": "cohere/rerank-english-v3.0",
- "top_n": 3,
- },
- )
-
- print(f"RAG Query Response with Rerank: {response.model_dump_json(indent=4)}")
-
- assert response.choices[0].message.content
- assert "search_results" in response.choices[0].message.provider_specific_fields
- assert "rerank_results" in response.choices[0].message.provider_specific_fields
diff --git a/tests/vector_store_tests/rag/test_rag_s3_vectors.py b/tests/vector_store_tests/rag/test_rag_s3_vectors.py
deleted file mode 100644
index d950bc0f644..00000000000
--- a/tests/vector_store_tests/rag/test_rag_s3_vectors.py
+++ /dev/null
@@ -1,105 +0,0 @@
-"""
-S3 Vectors RAG ingestion tests.
-
-Requires environment variables:
-- AWS_ACCESS_KEY_ID
-- AWS_SECRET_ACCESS_KEY
-- AWS_REGION_NAME (optional, defaults to us-west-2)
-
-Optional:
-- S3_VECTOR_BUCKET_NAME (optional, auto-generates if not set)
-"""
-
-import os
-from typing import Any, Dict, Optional
-
-import pytest
-
-
-import litellm
-from litellm.types.rag import RAGIngestOptions
-from tests.vector_store_tests.rag.base_rag_tests import BaseRAGTest
-
-
-class TestRAGS3Vectors(BaseRAGTest):
- """Test RAG Ingest with AWS S3 Vectors."""
-
- @pytest.fixture(autouse=True)
- def check_env_vars(self):
- """Check required environment variables before each test."""
- aws_key = os.environ.get("AWS_ACCESS_KEY_ID")
- aws_secret = os.environ.get("AWS_SECRET_ACCESS_KEY")
-
- if not aws_key or not aws_secret:
- pytest.skip("Skipping S3 Vectors test: AWS credentials required")
-
- def get_base_ingest_options(self) -> RAGIngestOptions:
- """
- Return S3 Vectors-specific ingest options.
-
- Chunking is configured via chunking_strategy (unified interface).
- Embeddings are generated using LiteLLM's embedding API.
- """
- vector_bucket_name = os.environ.get(
- "S3_VECTOR_BUCKET_NAME", "test-litellm-vectors"
- )
- aws_region = os.environ.get("AWS_REGION_NAME", "us-west-2")
-
- return {
- "chunking_strategy": {
- "chunk_size": 512,
- "chunk_overlap": 100,
- },
- "embedding": {
- "model": "text-embedding-3-small" # Can use any LiteLLM-supported model
- },
- "vector_store": {
- "custom_llm_provider": "s3_vectors",
- "vector_bucket_name": vector_bucket_name,
- "index_name": "test-index",
- # dimension is auto-detected from embedding model (text-embedding-3-small = 1536)
- "distance_metric": "cosine",
- "non_filterable_metadata_keys": ["source_text"],
- "aws_region_name": aws_region,
- },
- }
-
- async def query_vector_store(
- self,
- vector_store_id: str,
- query: str,
- ) -> Optional[Dict[str, Any]]:
- """Query S3 Vectors index."""
- try:
- # Import the ingestion class to use its query method
- from litellm.rag.ingestion.s3_vectors_ingestion import (
- S3VectorsRAGIngestion,
- )
- except ImportError:
- pytest.skip("S3 Vectors ingestion not available")
-
- vector_bucket_name = os.environ.get(
- "S3_VECTOR_BUCKET_NAME", "test-litellm-vectors"
- )
- aws_region = os.environ.get("AWS_REGION_NAME", "us-west-2")
-
- # Create ingestion instance to use query method
- ingest_options = {
- "embedding": {"model": "text-embedding-3-small"},
- "vector_store": {
- "custom_llm_provider": "s3_vectors",
- "vector_bucket_name": vector_bucket_name,
- "aws_region_name": aws_region,
- },
- }
-
- ingestion = S3VectorsRAGIngestion(ingest_options=ingest_options)
-
- # Query the index
- results = await ingestion.query_vector_store(
- vector_store_id=vector_store_id,
- query=query,
- top_k=5,
- )
-
- return results
diff --git a/tests/vector_store_tests/rag/test_rag_vertex_ai.py b/tests/vector_store_tests/rag/test_rag_vertex_ai.py
deleted file mode 100644
index 67e0a25782b..00000000000
--- a/tests/vector_store_tests/rag/test_rag_vertex_ai.py
+++ /dev/null
@@ -1,243 +0,0 @@
-"""
-Vertex AI RAG Engine ingestion tests.
-
-Tests the Vertex AI RAG ingestion implementation that:
-- Creates RAG corpora automatically (or uses existing ones)
-- Uploads files directly to Vertex AI RAG Engine
-- Handles long-running operations for corpus creation
-- Supports both file upload and GCS import
-
-Requires:
-- gcloud auth application-default login (for ADC authentication)
-
-Environment variables:
-- VERTEX_PROJECT: GCP project ID (required)
-- VERTEX_LOCATION: GCP region (optional, defaults to us-central1)
-- VERTEX_CORPUS_ID: Existing RAG corpus ID (optional - will create if not provided)
-"""
-
-import os
-from typing import Any, Dict, Optional
-
-import pytest
-
-
-import litellm
-from litellm.types.rag import RAGIngestOptions
-from tests.vector_store_tests.rag.base_rag_tests import BaseRAGTest
-
-
-class TestRAGVertexAI(BaseRAGTest):
- """Test RAG Ingest with Vertex AI RAG Engine."""
-
- @pytest.fixture(autouse=True)
- def check_env_vars(self):
- """Check required environment variables before each test."""
- vertex_project = os.environ.get("VERTEX_PROJECT")
-
- if not vertex_project:
- pytest.skip("Skipping Vertex AI test: VERTEX_PROJECT required")
-
- def get_base_ingest_options(self) -> RAGIngestOptions:
- """
- Return Vertex AI-specific ingest options.
-
- Chunking is configured via chunking_strategy (unified interface),
- not inside vector_store.
-
- If VERTEX_CORPUS_ID is not set, a new corpus will be created automatically.
- """
- vertex_project = os.environ.get("VERTEX_PROJECT")
- vertex_location = os.environ.get("VERTEX_LOCATION", "us-central1")
- corpus_id = os.environ.get("VERTEX_CORPUS_ID") # Optional
-
- options: RAGIngestOptions = {
- "chunking_strategy": {
- "chunk_size": 512,
- "chunk_overlap": 100,
- },
- "vector_store": {
- "custom_llm_provider": "vertex_ai",
- "vertex_project": vertex_project,
- "vertex_location": vertex_location,
- },
- }
-
- # Add corpus ID if provided (otherwise will create new corpus)
- if corpus_id:
- options["vector_store"]["vector_store_id"] = corpus_id
-
- return options
-
- async def query_vector_store(
- self,
- vector_store_id: str,
- query: str,
- ) -> Optional[Dict[str, Any]]:
- """
- Query Vertex AI RAG corpus using LiteLLM's vector store search.
-
- Args:
- vector_store_id: The RAG corpus ID (can be full path or just the ID)
- query: The search query
-
- Returns:
- Search results dict or None if no results found
- """
- vertex_project = os.environ.get("VERTEX_PROJECT")
- vertex_location = os.environ.get("VERTEX_LOCATION", "us-central1")
-
- try:
- # Use LiteLLM's vector store search
- search_response = await litellm.vector_stores.asearch(
- vector_store_id=vector_store_id,
- query=query,
- max_num_results=5,
- custom_llm_provider="vertex_ai",
- vertex_project=vertex_project,
- vertex_location=vertex_location,
- )
-
- # Check if we got results
- if search_response and search_response.get("data"):
- results = []
- for item in search_response["data"]:
- # Extract text from content
- text = ""
- if item.get("content"):
- for content_item in item["content"]:
- if content_item.get("text"):
- text += content_item["text"]
-
- results.append(
- {
- "text": text,
- "score": item.get("score", 0.0),
- "file_id": item.get("file_id", ""),
- "filename": item.get("filename", ""),
- }
- )
-
- # Check if query terms appear in results
- for result in results:
- if query.lower() in result["text"].lower():
- return {"results": results}
-
- # Return results even if exact match not found
- return {"results": results}
-
- return None
-
- except Exception as e:
- print(f"Query failed: {e}")
- return None
-
- @pytest.mark.asyncio
- async def test_create_corpus_and_ingest(self):
- """
- Test creating a new RAG corpus and ingesting a file.
-
- This test specifically validates:
- - Automatic corpus creation when vector_store_id is not provided
- - Long-running operation polling for corpus creation
- - File upload to the newly created corpus
- """
- litellm.turn_on_debug()
-
- filename, unique_id = self.get_unique_filename("create_corpus")
- text_content = f"""
- Test document {unique_id} for Vertex AI RAG corpus creation.
- This tests the automatic corpus creation feature.
- The corpus should be created and the file should be uploaded successfully.
- """.encode(
- "utf-8"
- )
- file_data = (filename, text_content, "text/plain")
-
- # Get base options WITHOUT corpus_id to trigger creation
- ingest_options = self.get_base_ingest_options()
- # Remove corpus_id if it was set from env var
- if "vector_store_id" in ingest_options.get("vector_store", {}):
- del ingest_options["vector_store"]["vector_store_id"]
-
- ingest_options["name"] = f"test-create-corpus-{unique_id}"
-
- try:
- response = await litellm.rag.aingest(
- ingest_options=ingest_options,
- file_data=file_data,
- )
-
- print(f"Create Corpus Response: {response}")
-
- # Validate response
- assert "id" in response
- assert response["id"].startswith("ingest_")
- assert "status" in response
- assert (
- response["status"] == "completed"
- ), f"Expected completed, got {response['status']}"
- assert "vector_store_id" in response
- assert response["vector_store_id"], "vector_store_id should not be empty"
-
- # The vector_store_id should be a full corpus path
- corpus_id = response["vector_store_id"]
- assert "projects/" in corpus_id, "Corpus ID should be a full resource path"
- assert "ragCorpora/" in corpus_id, "Corpus ID should contain ragCorpora"
-
- print(f"✓ Successfully created corpus: {corpus_id}")
- print(f"✓ Successfully uploaded file: {response.get('file_id')}")
-
- except litellm.InternalServerError as e:
- pytest.skip(f"Skipping test due to litellm.InternalServerError: {e}")
- except Exception as e:
- print(f"Test failed with error: {e}")
- raise
-
- @pytest.mark.asyncio
- async def test_ingest_with_existing_corpus(self):
- """
- Test ingesting a file to an existing RAG corpus.
-
- This test validates:
- - Using an existing corpus_id from environment variable
- - Direct file upload without corpus creation
- """
- corpus_id = os.environ.get("VERTEX_CORPUS_ID")
- if not corpus_id:
- pytest.skip("Skipping test: VERTEX_CORPUS_ID not set")
-
- litellm.turn_on_debug()
-
- filename, unique_id = self.get_unique_filename("existing_corpus")
- text_content = f"""
- Test document {unique_id} for existing Vertex AI RAG corpus.
- This tests file upload to a pre-existing corpus.
- """.encode(
- "utf-8"
- )
- file_data = (filename, text_content, "text/plain")
-
- ingest_options = self.get_base_ingest_options()
- ingest_options["name"] = f"test-existing-corpus-{unique_id}"
-
- try:
- response = await litellm.rag.aingest(
- ingest_options=ingest_options,
- file_data=file_data,
- )
-
- print(f"Existing Corpus Ingest Response: {response}")
-
- assert response["status"] == "completed"
- assert (
- response["vector_store_id"] == corpus_id
- or corpus_id in response["vector_store_id"]
- )
- assert response.get("file_id"), "file_id should be present"
-
- print(f"✓ Successfully uploaded to existing corpus: {corpus_id}")
- print(f"✓ File ID: {response.get('file_id')}")
-
- except litellm.InternalServerError as e:
- pytest.skip(f"Skipping test due to litellm.InternalServerError: {e}")
diff --git a/tests/vector_store_tests/test_azure_vector_store.py b/tests/vector_store_tests/test_azure_vector_store.py
deleted file mode 100644
index 851492474cc..00000000000
--- a/tests/vector_store_tests/test_azure_vector_store.py
+++ /dev/null
@@ -1,25 +0,0 @@
-from base_vector_store_test import BaseVectorStoreTest
-import os
-import pytest
-
-
-class TestAzureOpenAIVectorStore(BaseVectorStoreTest):
- def get_base_request_args(self) -> dict:
- """Must return the base request args"""
- return {}
-
- @pytest.mark.parametrize("sync_mode", [True, False])
- @pytest.mark.asyncio
- async def test_basic_search_vector_store(self, sync_mode):
- pass
-
- def get_base_create_vector_store_args(self) -> dict:
- """
- This is a real vector store on Azure
- """
- return {
- "custom_llm_provider": "azure",
- "api_base": os.getenv("AZURE_API_BASE"),
- "api_key": os.getenv("AZURE_API_KEY"),
- "api_version": "2025-04-01-preview",
- }
diff --git a/tests/vector_store_tests/test_bedrock_vector_store.py b/tests/vector_store_tests/test_bedrock_vector_store.py
deleted file mode 100644
index d8af1c7188b..00000000000
--- a/tests/vector_store_tests/test_bedrock_vector_store.py
+++ /dev/null
@@ -1,236 +0,0 @@
-"""
-Test Bedrock Vector Store helper functions and transformation.
-"""
-
-import pytest
-from unittest.mock import Mock
-import httpx
-
-from tests.vector_store_tests.base_vector_store_test import BaseVectorStoreTest
-from litellm.llms.bedrock.vector_stores.transformation import BedrockVectorStoreConfig
-from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
-
-
-class TestBedrockVectorStore(BaseVectorStoreTest):
- """
- Test the Bedrock vector store transformation functionality.
- """
-
- def get_base_create_vector_store_args(self) -> dict:
- """Must return the base create vector store args"""
- return {}
-
- def get_base_request_args(self):
- return {
- "vector_store_id": "T37J8R4WTM",
- "custom_llm_provider": "bedrock",
- "query": "what happens after we add a model",
- }
-
- def test_get_file_id_from_metadata(self):
- """Test that file_id is correctly extracted from metadata."""
- config = BedrockVectorStoreConfig()
-
- # Test with source URI
- metadata_with_uri = {
- "x-amz-bedrock-kb-source-uri": "https://www.litellm.ai",
- "x-amz-bedrock-kb-chunk-id": "1%3A0%3AjNYPg5YByRuP5PdK96co",
- }
- file_id = config._get_file_id_from_metadata(metadata_with_uri)
- assert file_id == "https://www.litellm.ai"
-
- # Test without source URI but with chunk ID
- metadata_without_uri = {
- "x-amz-bedrock-kb-chunk-id": "1%3A0%3AjNYPg5YByRuP5PdK96co"
- }
- file_id = config._get_file_id_from_metadata(metadata_without_uri)
- assert file_id == "bedrock-kb-1%3A0%3AjNYPg5YByRuP5PdK96co"
-
- # Test with empty metadata
- file_id = config._get_file_id_from_metadata({})
- assert file_id == "bedrock-kb-unknown"
-
- def test_get_filename_from_metadata(self):
- """Test that filename is correctly extracted from metadata."""
- config = BedrockVectorStoreConfig()
-
- # Test with source URI containing path
- metadata_with_path = {
- "x-amz-bedrock-kb-source-uri": "https://docs.litellm.ai/tutorial/setup.html"
- }
- filename = config._get_filename_from_metadata(metadata_with_path)
- assert filename == "setup.html"
-
- # Test with source URI without path (domain only)
- metadata_domain_only = {"x-amz-bedrock-kb-source-uri": "https://www.litellm.ai"}
- filename = config._get_filename_from_metadata(metadata_domain_only)
- assert filename == "www.litellm.ai"
-
- # Test without source URI but with data source ID
- metadata_without_uri = {"x-amz-bedrock-kb-data-source-id": "CCEJIRXXFI"}
- filename = config._get_filename_from_metadata(metadata_without_uri)
- assert filename == "bedrock-kb-document-CCEJIRXXFI"
-
- # Test with empty metadata
- filename = config._get_filename_from_metadata({})
- assert filename == "bedrock-kb-document-unknown"
-
- def test_get_attributes_from_metadata(self):
- """Test that attributes are correctly extracted from metadata."""
- config = BedrockVectorStoreConfig()
-
- # Test with full metadata
- metadata = {
- "x-amz-bedrock-kb-source-uri": "https://www.litellm.ai",
- "x-amz-bedrock-kb-chunk-id": "1%3A0%3AjNYPg5YByRuP5PdK96co",
- "x-amz-bedrock-kb-data-source-id": "CCEJIRXXFI",
- }
- attributes = config._get_attributes_from_metadata(metadata)
- assert attributes == metadata
- assert attributes is not metadata # Should be a copy
-
- # Test with empty metadata
- attributes = config._get_attributes_from_metadata({})
- assert attributes == {}
-
- # Test with None
- attributes = config._get_attributes_from_metadata(None)
- assert attributes == {}
-
-
-async def test_bedrock_search_with_router():
- from litellm.router import Router
-
- # init router
- _router = Router(model_list=[])
- search_response = await _router.avector_store_search(
- query="what happens after we add a model",
- vector_store_id="T37J8R4WTM",
- custom_llm_provider="bedrock",
- )
- print(search_response)
-
-
-async def test_bedrock_search_with_credentials_managed_registry():
- """
- Test that the vector store search uses the credential accessor from the registry
- when AWS environment variables are not set, ensuring credentials are managed properly.
- """
- from unittest.mock import patch, MagicMock
- from litellm.router import Router
- from litellm.types.vector_stores import LiteLLM_ManagedVectorStore
- from litellm.types.utils import CredentialItem
- from litellm.vector_stores.vector_store_registry import VectorStoreRegistry
- from datetime import datetime, timezone
- import litellm
-
- # Store original registry and credential list
- original_registry = getattr(litellm, "vector_store_registry", None)
- original_credential_list = getattr(litellm, "credential_list", [])
-
- try:
- # Set up test AWS credentials in the credential system
- test_credentials = CredentialItem(
- credential_name="bedrock-litellm-website-knowledgebase",
- credential_info={
- "provider": "aws",
- "description": "Test AWS credentials for bedrock",
- },
- credential_values={
- "aws_access_key_id": "test_access_key",
- "aws_secret_access_key": "test_secret_key",
- "aws_region_name": "us-east-1",
- },
- )
-
- # Set up the credential list
- litellm.credential_list = [test_credentials]
-
- # Create vector store with credential reference
- vector_store = LiteLLM_ManagedVectorStore(
- vector_store_id="T37J8R4WTM",
- custom_llm_provider="bedrock",
- created_at=datetime.now(timezone.utc),
- updated_at=datetime.now(timezone.utc),
- litellm_credential_name="bedrock-litellm-website-knowledgebase",
- )
-
- # Set up registry
- registry = VectorStoreRegistry([vector_store])
- litellm.vector_store_registry = registry
-
- # Verify credentials can be retrieved from registry
- retrieved_credentials = registry.get_credentials_for_vector_store("T37J8R4WTM")
- assert retrieved_credentials, "Should retrieve credentials from registry"
- assert retrieved_credentials.get("aws_access_key_id") == "test_access_key"
- assert retrieved_credentials.get("aws_secret_access_key") == "test_secret_key"
- assert retrieved_credentials.get("aws_region_name") == "us-east-1"
-
- # Create router and perform search
- _router = Router(model_list=[])
-
- # Mock the credential injection process to verify it's called
- with patch.object(
- registry,
- "get_credentials_for_vector_store",
- wraps=registry.get_credentials_for_vector_store,
- ) as mock_get_creds:
- # Mock the actual search call to avoid making real API calls
- with patch(
- "litellm.vector_stores.main.base_llm_http_handler.vector_store_search_handler"
- ) as mock_handler:
- mock_handler.return_value = {
- "data": [
- {
- "id": "test_result",
- "text": "Mock search result",
- "score": 0.9,
- "metadata": {},
- }
- ]
- }
-
- search_response = await _router.avector_store_search(
- query="what happens after we add a model",
- vector_store_id="T37J8R4WTM",
- custom_llm_provider="bedrock",
- )
-
- # Verify the search was called
- mock_handler.assert_called_once()
- call_kwargs = mock_handler.call_args[1]
-
- # Verify that the credential accessor was called with the correct vector store ID
- mock_get_creds.assert_called_with("T37J8R4WTM")
-
- # Verify the credentials were injected into the search call
- litellm_params = call_kwargs.get("litellm_params", {})
-
- # The key test: verify that credentials from the registry were used
- # Since we have a registry with credentials, they should be present in the params
- assert hasattr(
- litellm_params, "aws_access_key_id"
- ), "aws_access_key_id should be in litellm_params"
- assert hasattr(
- litellm_params, "aws_secret_access_key"
- ), "aws_secret_access_key should be in litellm_params"
- assert hasattr(
- litellm_params, "aws_region_name"
- ), "aws_region_name should be in litellm_params"
-
- # Verify we got the expected response
- assert search_response["data"][0]["id"] == "test_result"
-
- print(
- f"✅ Test passed: Credential accessor was called with vector store ID: T37J8R4WTM"
- )
- print(f"✅ Retrieved credentials: {retrieved_credentials}")
- print(f"✅ Credentials were injected into search call")
- print(f"✅ Search completed successfully using registry credentials")
-
- finally:
- # Restore original state
- litellm.vector_store_registry = original_registry
- litellm.credential_list = original_credential_list
diff --git a/tests/vector_store_tests/test_gemini_vector_store.py b/tests/vector_store_tests/test_gemini_vector_store.py
deleted file mode 100644
index 2aa2c1741a8..00000000000
--- a/tests/vector_store_tests/test_gemini_vector_store.py
+++ /dev/null
@@ -1,28 +0,0 @@
-"""
-Minimal Gemini File Search vector store tests.
-"""
-
-import os
-
-
-from base_vector_store_test import BaseVectorStoreTest
-
-
-class TestGeminiVectorStore(BaseVectorStoreTest):
- """Reuses the shared vector store smoke suite with Gemini."""
-
- def get_base_request_args(self) -> dict:
- """Provide arguments for the shared search test."""
- return {
- "vector_store_id": os.getenv(
- "GEMINI_TEST_STORE_ID", "fileSearchStores/example-test-store"
- ),
- "custom_llm_provider": "gemini",
- "query": "LiteLLM",
- }
-
- def get_base_create_vector_store_args(self) -> dict:
- """Ensure we always call Gemini when creating a vector store."""
- return {
- "custom_llm_provider": "gemini",
- }
diff --git a/tests/vector_store_tests/test_milvus_vector_store.py b/tests/vector_store_tests/test_milvus_vector_store.py
deleted file mode 100644
index 2139abb6a90..00000000000
--- a/tests/vector_store_tests/test_milvus_vector_store.py
+++ /dev/null
@@ -1,717 +0,0 @@
-"""
-Tests for Milvus Vector Store
-"""
-
-import json
-from unittest.mock import AsyncMock, MagicMock, patch
-
-import httpx
-import pytest
-import respx
-
-import litellm
-from litellm import Router
-from litellm.llms.milvus.vector_stores.transformation import MilvusVectorStoreConfig
-from litellm.types.utils import EmbeddingResponse
-from litellm.vector_stores import asearch as vector_store_asearch
-from litellm.vector_stores import search as vector_store_search
-
-# Mock response from actual Milvus API
-MOCK_MILVUS_SEARCH_RESPONSE = {
- "code": 0,
- "cost": 6,
- "data": [
- {
- "book_id": 0,
- "book_intro_text": "abababababa_0562efee-0f1f-4b6b-9ca3-1a160f124ad8",
- "distance": 10.240219,
- },
- {
- "book_id": 1,
- "book_intro_text": "abababababa_9a13e8f3-bb1e-487f-b555-b8ae4b127243",
- "distance": 10.240219,
- },
- {
- "book_id": 2,
- "book_intro_text": "abababababa_870f47f1-23ec-4364-ad30-6d364ba8ddb5",
- "distance": 10.240219,
- },
- {
- "book_id": 1000,
- "book_intro_text": "abababababa_8ea2d76a-3fdf-49b3-8f16-a91638361bba",
- "distance": 8.531628,
- },
- {
- "book_id": 1001,
- "book_intro_text": "abababababa_24758251-e740-4183-8649-2f742f676ca0",
- "distance": 8.531628,
- },
- {
- "book_id": 1002,
- "book_intro_text": "abababababa_faa55789-220d-4ef1-b5bf-a72f2fbd061b",
- "distance": 8.531628,
- },
- {
- "book_id": 0,
- "book_intro_text": "abababababa_0562efee-0f1f-4b6b-9ca3-1a160f124ad8",
- "distance": 8.236887,
- },
- {
- "book_id": 1,
- "book_intro_text": "abababababa_9a13e8f3-bb1e-487f-b555-b8ae4b127243",
- "distance": 8.236887,
- },
- {
- "book_id": 2,
- "book_intro_text": "abababababa_870f47f1-23ec-4364-ad30-6d364ba8ddb5",
- "distance": 8.236887,
- },
- ],
- "topks": [3, 3, 3],
-}
-# Mock embedding response from OpenAI
-MOCK_EMBEDDING_RESPONSE = MagicMock()
-MOCK_EMBEDDING_RESPONSE.data = [
- {
- "embedding": [
- 0.023,
- -0.019,
- 0.045,
- -0.012,
- 0.067,
- -0.034,
- 0.089,
- -0.056,
- ]
- * 128 # Simulate 1024-dimensional embedding
- }
-]
-
-
-class TestMilvusVectorStore:
- """Test Milvus Vector Store with mocked responses"""
-
- @pytest.mark.asyncio
- async def test_basic_search_with_mock_async(self):
- """Test basic vector search with mocked backend response (async)"""
-
- # Mock the HTTP response
- mock_response = MagicMock()
- mock_response.status_code = 200
- mock_response.json.return_value = MOCK_MILVUS_SEARCH_RESPONSE
- mock_response.text = json.dumps(MOCK_MILVUS_SEARCH_RESPONSE)
-
- with patch("litellm.aembedding", new_callable=AsyncMock) as mock_embedding:
- mock_embedding.return_value = MOCK_EMBEDDING_RESPONSE
-
- with patch(
- "litellm.llms.custom_httpx.http_handler.AsyncHTTPHandler.post",
- new_callable=AsyncMock,
- ) as mock_post:
- mock_post.return_value = mock_response
-
- # Make the search request
- response = await vector_store_asearch(
- query="what is machine learning?",
- vector_store_id="book_2",
- custom_llm_provider="milvus",
- api_base="https://in03-test.serverless.aws-eu-central-1.cloud.zilliz.com",
- api_key="mock_milvus_api_key",
- litellm_embedding_model="text-embedding-3-large",
- litellm_embedding_config={
- "api_key": "mock_openai_api_key",
- },
- outputFields=["book_intro_text"],
- annsField="book_intro_vector",
- milvus_text_field="book_intro_text",
- )
-
- print("Response:", json.dumps(response, indent=2, default=str))
-
- # Verify embedding was called with correct parameters
- mock_embedding.assert_called_once()
- embedding_call_args = mock_embedding.call_args
- assert embedding_call_args[1]["model"] == "text-embedding-3-large"
- assert embedding_call_args[1]["input"] == ["what is machine learning?"]
- assert embedding_call_args[1]["api_key"] == "mock_openai_api_key"
-
- # Verify the API was called
- mock_post.assert_called_once()
-
- # Verify the request payload
- call_args = mock_post.call_args
- print(f"call_args: {call_args}")
- print(f"call_args.kwargs: {call_args.kwargs}")
-
- # The post method is called with 'data' parameter (JSON string) not 'json' parameter
- request_data_str = call_args.kwargs.get("data")
- if request_data_str:
- request_data = json.loads(request_data_str)
- else:
- # Fallback: check for json kwarg or in args
- request_data = call_args.kwargs.get("json")
- if request_data is None and len(call_args.args) > 0 and isinstance(call_args.args[0], dict):
- request_data = call_args.args[0]
-
- assert request_data is not None, f"Could not extract request data. Call args: {call_args}"
- print("Request data:", json.dumps(request_data, indent=2, default=str))
-
- # Validate request structure
- assert "collectionName" in request_data
- assert request_data["collectionName"] == "book_2"
- assert "data" in request_data
- assert isinstance(request_data["data"], list)
- assert len(request_data["data"]) == 1 # Single query vector
- assert "annsField" in request_data
- assert request_data["annsField"] == "book_intro_vector"
- assert "outputFields" in request_data
- assert request_data["outputFields"] == ["book_intro_text"]
-
- # Verify the URL format
- url = call_args.kwargs.get("url", "")
- assert "v2/vectordb/entities/search" in url
-
- # Validate the response structure (LiteLLM standard format)
- assert response is not None
- assert response["object"] == "vector_store.search_results.page" # type: ignore
- assert "data" in response
- assert len(response["data"]) == 9 # type: ignore # 9 results in mock response
-
- # Validate first result
- first_result = response["data"][0] # type: ignore
- assert "score" in first_result
- assert first_result["score"] == 10.240219 # type: ignore
- assert "content" in first_result
- assert "attributes" in first_result
-
- # Validate content structure
- assert len(first_result["content"]) > 0 # type: ignore
- assert first_result["content"][0]["type"] == "text" # type: ignore
- assert "text" in first_result["content"][0] # type: ignore
- assert (
- first_result["content"][0]["text"] # type: ignore
- == "abababababa_0562efee-0f1f-4b6b-9ca3-1a160f124ad8"
- )
-
- # Validate attributes contain book_id but NOT book_intro_text (it's in content)
- assert "book_id" in first_result["attributes"] # type: ignore
- assert first_result["attributes"]["book_id"] == 0 # type: ignore
- assert "book_intro_text" not in first_result["attributes"] # type: ignore # Should be in content, not attributes
-
- def test_basic_search_with_mock_sync(self):
- """Test basic vector search with mocked backend response (sync)"""
-
- # Mock the HTTP response
- mock_response = MagicMock()
- mock_response.status_code = 200
- mock_response.json.return_value = MOCK_MILVUS_SEARCH_RESPONSE
- mock_response.text = json.dumps(MOCK_MILVUS_SEARCH_RESPONSE)
-
- with patch("litellm.embedding") as mock_embedding:
- mock_embedding.return_value = MOCK_EMBEDDING_RESPONSE
-
- with patch("litellm.llms.custom_httpx.http_handler.HTTPHandler.post") as mock_post:
- mock_post.return_value = mock_response
-
- # Make the search request
- response = vector_store_search(
- query="what is machine learning?",
- vector_store_id="book_2",
- custom_llm_provider="milvus",
- api_base="https://in03-test.serverless.aws-eu-central-1.cloud.zilliz.com",
- api_key="mock_milvus_api_key",
- litellm_embedding_model="text-embedding-3-large",
- litellm_embedding_config={
- "api_key": "mock_openai_api_key",
- },
- outputFields=["book_intro_text"],
- annsField="book_intro_vector",
- milvus_text_field="book_intro_text",
- )
-
- print("Response:", json.dumps(response, indent=2, default=str))
-
- # Verify embedding was called
- mock_embedding.assert_called_once()
-
- # Verify the API was called
- mock_post.assert_called_once()
-
- # Verify the request payload
- call_args = mock_post.call_args
-
- # The post method is called with 'data' parameter (JSON string) not 'json' parameter
- request_data_str = call_args.kwargs.get("data")
- if request_data_str:
- request_data = json.loads(request_data_str)
- else:
- # Fallback: check for json kwarg or in args
- request_data = call_args.kwargs.get("json")
- if request_data is None and len(call_args.args) > 0 and isinstance(call_args.args[0], dict):
- request_data = call_args.args[0]
-
- assert request_data is not None, f"Could not extract request data. Call args: {call_args}"
-
- # Validate request structure
- assert "collectionName" in request_data
- assert request_data["collectionName"] == "book_2"
- assert "data" in request_data
- assert isinstance(request_data["data"], list)
- assert "annsField" in request_data
- assert "outputFields" in request_data
-
- # Validate the response structure
- assert response is not None
- assert response["object"] == "vector_store.search_results.page" # type: ignore
- assert "data" in response # type: ignore
- assert len(response["data"]) == 9 # type: ignore # 9 results in mock response
- assert "search_query" in response # type: ignore
-
- # Validate first few results
- expected_results = [
- {
- "book_id": 0,
- "text": "abababababa_0562efee-0f1f-4b6b-9ca3-1a160f124ad8",
- "distance": 10.240219,
- },
- {
- "book_id": 1,
- "text": "abababababa_9a13e8f3-bb1e-487f-b555-b8ae4b127243",
- "distance": 10.240219,
- },
- {
- "book_id": 2,
- "text": "abababababa_870f47f1-23ec-4364-ad30-6d364ba8ddb5",
- "distance": 10.240219,
- },
- ]
-
- for idx, expected in enumerate(expected_results):
- result = response["data"][idx] # type: ignore
- assert "score" in result
- assert result["score"] == expected["distance"] # type: ignore
- assert "content" in result
- assert len(result["content"]) > 0 # type: ignore
- assert result["content"][0]["type"] == "text" # type: ignore
- assert "text" in result["content"][0] # type: ignore
- assert result["content"][0]["text"] == expected["text"] # type: ignore
- assert "attributes" in result
- assert result["attributes"]["book_id"] == expected["book_id"] # type: ignore
- assert "book_intro_text" not in result["attributes"] # type: ignore # Should be in content, not attributes
-
- def _extract_request_body(self, mock_post):
- call_args = mock_post.call_args
- request_data_str = call_args.kwargs.get("data")
- if request_data_str:
- return json.loads(request_data_str)
- request_data = call_args.kwargs.get("json")
- if request_data is None and len(call_args.args) > 0 and isinstance(call_args.args[0], dict):
- request_data = call_args.args[0]
- return request_data
-
- def test_user_supplied_db_and_partition_are_dropped(self):
- """User-supplied dbName / partitionNames must not be forwarded to Milvus."""
- mock_response = MagicMock()
- mock_response.status_code = 200
- mock_response.json.return_value = MOCK_MILVUS_SEARCH_RESPONSE
- mock_response.text = json.dumps(MOCK_MILVUS_SEARCH_RESPONSE)
-
- with patch("litellm.embedding") as mock_embedding:
- mock_embedding.return_value = MOCK_EMBEDDING_RESPONSE
-
- with patch("litellm.llms.custom_httpx.http_handler.HTTPHandler.post") as mock_post:
- mock_post.return_value = mock_response
-
- vector_store_search(
- query="what is machine learning?",
- vector_store_id="book_2",
- custom_llm_provider="milvus",
- api_base="https://in03-test.serverless.aws-eu-central-1.cloud.zilliz.com",
- api_key="mock_milvus_api_key",
- litellm_embedding_model="text-embedding-3-large",
- litellm_embedding_config={
- "api_key": "mock_openai_api_key",
- },
- outputFields=["book_intro_text"],
- annsField="book_intro_vector",
- milvus_text_field="book_intro_text",
- dbName="other_tenant_db",
- partitionNames=["other_tenant_partition"],
- )
-
- mock_post.assert_called_once()
- request_data = self._extract_request_body(mock_post)
- assert request_data is not None
- assert "dbName" not in request_data
- assert "partitionNames" not in request_data
- assert request_data["collectionName"] == "book_2"
- assert request_data["annsField"] == "book_intro_vector"
- assert request_data["outputFields"] == ["book_intro_text"]
-
- def test_backend_configured_db_and_partition_are_forwarded(self):
- """milvus_db_name / milvus_partition_names from litellm_params must be sent."""
- mock_response = MagicMock()
- mock_response.status_code = 200
- mock_response.json.return_value = MOCK_MILVUS_SEARCH_RESPONSE
- mock_response.text = json.dumps(MOCK_MILVUS_SEARCH_RESPONSE)
-
- with patch("litellm.embedding") as mock_embedding:
- mock_embedding.return_value = MOCK_EMBEDDING_RESPONSE
-
- with patch("litellm.llms.custom_httpx.http_handler.HTTPHandler.post") as mock_post:
- mock_post.return_value = mock_response
-
- vector_store_search(
- query="what is machine learning?",
- vector_store_id="book_2",
- custom_llm_provider="milvus",
- api_base="https://in03-test.serverless.aws-eu-central-1.cloud.zilliz.com",
- api_key="mock_milvus_api_key",
- litellm_embedding_model="text-embedding-3-large",
- litellm_embedding_config={
- "api_key": "mock_openai_api_key",
- },
- outputFields=["book_intro_text"],
- annsField="book_intro_vector",
- milvus_text_field="book_intro_text",
- milvus_db_name="tenant_a_db",
- milvus_partition_names=["tenant_a_partition"],
- )
-
- mock_post.assert_called_once()
- request_data = self._extract_request_body(mock_post)
- assert request_data is not None
- assert request_data["dbName"] == "tenant_a_db"
- assert request_data["partitionNames"] == ["tenant_a_partition"]
-
- def test_user_params_cannot_override_backend_db_and_partition(self):
- """Backend-config dbName/partitionNames must win over user-supplied values."""
- mock_response = MagicMock()
- mock_response.status_code = 200
- mock_response.json.return_value = MOCK_MILVUS_SEARCH_RESPONSE
- mock_response.text = json.dumps(MOCK_MILVUS_SEARCH_RESPONSE)
-
- with patch("litellm.embedding") as mock_embedding:
- mock_embedding.return_value = MOCK_EMBEDDING_RESPONSE
-
- with patch("litellm.llms.custom_httpx.http_handler.HTTPHandler.post") as mock_post:
- mock_post.return_value = mock_response
-
- vector_store_search(
- query="what is machine learning?",
- vector_store_id="book_2",
- custom_llm_provider="milvus",
- api_base="https://in03-test.serverless.aws-eu-central-1.cloud.zilliz.com",
- api_key="mock_milvus_api_key",
- litellm_embedding_model="text-embedding-3-large",
- litellm_embedding_config={
- "api_key": "mock_openai_api_key",
- },
- outputFields=["book_intro_text"],
- annsField="book_intro_vector",
- milvus_text_field="book_intro_text",
- milvus_db_name="tenant_a_db",
- milvus_partition_names=["tenant_a_partition"],
- dbName="other_tenant_db",
- partitionNames=["other_tenant_partition"],
- )
-
- mock_post.assert_called_once()
- request_data = self._extract_request_body(mock_post)
- assert request_data is not None
- assert request_data["dbName"] == "tenant_a_db"
- assert request_data["partitionNames"] == ["tenant_a_partition"]
-
-
-# @pytest.mark.parametrize("sync_mode", [True, False])
-# @pytest.mark.asyncio
-# async def test_basic_search_vector_store(sync_mode):
-# """Integration test with real Milvus API (requires credentials)"""
-# litellm.turn_on_debug()
-# litellm.set_verbose = True
-# base_request_args = {
-# "vector_store_id": "book_2",
-# "custom_llm_provider": "milvus",
-# "api_base": "https://in03-18505f064ffbc6f.serverless.aws-eu-central-1.cloud.zilliz.com",
-# "litellm_embedding_model": "text-embedding-3-large",
-# "litellm_embedding_config": {
-# "api_key": os.getenv("OPENAI_API_KEY"),
-# },
-# "default_output_fields": [
-# "book_intro_text"
-# ], # field containing the text to return in the response
-# "default_anns_field": "book_intro_vector",
-# }
-# default_query = base_request_args.pop("query", "Basic ping")
-# print(f"base_request_args: {base_request_args}")
-# try:
-# if sync_mode:
-# response = vector_store_search(query=default_query, **base_request_args)
-# else:
-# response = await vector_store_asearch(
-# query=default_query, **base_request_args
-# )
-# except litellm.InternalServerError:
-# pytest.skip("Skipping test due to litellm.InternalServerError")
-
-# print("litellm response=", json.dumps(response, indent=4, default=str))
-# assert len(response["data"]) > 0 # type: ignore
-
-
-if __name__ == "__main__":
- # Run tests
- import asyncio
-
- test = TestMilvusVectorStore()
-
- print("Running async mock test...")
- asyncio.run(test.test_basic_search_with_mock_async())
-
- print("\nRunning sync mock test...")
- test.test_basic_search_with_mock_sync()
-
- print("\n✅ All mock tests passed!")
-
-
-class RecordingEmbeddingExecutor:
- def __init__(self, response):
- self.response = response
- self.calls = []
-
- def embed(self, model, query, configuration):
- self.calls.append((model, query, dict(configuration)))
- return self.response
-
- async def aembed(self, model, query, configuration):
- self.calls.append((model, query, dict(configuration)))
- return self.response
-
-
-ALIAS_QUERY_VECTOR = [0.5, -0.25, 0.125]
-ALIAS_EMBEDDING_RESPONSE = EmbeddingResponse(
- data=[{"embedding": ALIAS_QUERY_VECTOR, "index": 0, "object": "embedding"}]
-)
-OPENAI_EMBEDDINGS_URL = "https://api.openai.com/v1/embeddings"
-MILVUS_SEARCH_URL = "https://milvus.example/v2/vectordb/entities/search"
-ALIAS_SEARCH_KWARGS = {
- "query": "what is machine learning?",
- "vector_store_id": "book_2",
- "custom_llm_provider": "milvus",
- "api_base": "https://milvus.example",
- "api_key": "mock_milvus_api_key",
- "litellm_embedding_model": "multilingual-e5-large",
- "milvus_text_field": "book_intro_text",
-}
-
-
-def _alias_router():
- return Router(
- model_list=[
- {
- "model_name": "multilingual-e5-large",
- "litellm_params": {
- "model": "openai/text-embedding-3-small",
- "api_key": "deployment-key",
- },
- }
- ]
- )
-
-
-def _mock_embedding_route(respx_mock: respx.MockRouter) -> respx.Route:
- return respx_mock.post(OPENAI_EMBEDDINGS_URL).mock(
- return_value=httpx.Response(
- 200,
- json={
- "object": "list",
- "data": [{"object": "embedding", "index": 0, "embedding": ALIAS_QUERY_VECTOR}],
- "model": "text-embedding-3-small",
- "usage": {"prompt_tokens": 2, "total_tokens": 2},
- },
- )
- )
-
-
-def _mock_search_route(respx_mock: respx.MockRouter) -> respx.Route:
- return respx_mock.post(MILVUS_SEARCH_URL).mock(return_value=httpx.Response(200, json=MOCK_MILVUS_SEARCH_RESPONSE))
-
-
-def _assert_alias_resolved(embedding_route: respx.Route, search_route: respx.Route, response):
- embedding_request = embedding_route.calls.last.request
- assert embedding_request.headers["authorization"] == "Bearer deployment-key"
- embedding_body = json.loads(embedding_request.read())
- assert embedding_body["model"] == "text-embedding-3-small"
- assert embedding_body["input"] == ["what is machine learning?"]
- search_request = search_route.calls.last.request
- assert search_request.headers["authorization"] == "Bearer mock_milvus_api_key"
- assert json.loads(search_request.read())["data"] == [ALIAS_QUERY_VECTOR]
- assert len(response["data"]) == len(MOCK_MILVUS_SEARCH_RESPONSE["data"])
- assert response["data"][0]["content"][0]["text"] == MOCK_MILVUS_SEARCH_RESPONSE["data"][0]["book_intro_text"]
-
-
-def test_router_search_resolves_bare_embedding_alias_sync(
- respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
-):
- monkeypatch.delenv("OPENAI_API_KEY", raising=False)
- embedding_route = _mock_embedding_route(respx_mock)
- search_route = _mock_search_route(respx_mock)
-
- response = _alias_router().vector_store_search(**ALIAS_SEARCH_KWARGS)
-
- _assert_alias_resolved(embedding_route, search_route, response)
-
-
-async def test_router_search_resolves_bare_embedding_alias_async(
- respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
-):
- monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
- monkeypatch.delenv("OPENAI_API_KEY", raising=False)
- embedding_route = _mock_embedding_route(respx_mock)
- search_route = _mock_search_route(respx_mock)
-
- response = await _alias_router().avector_store_search(**ALIAS_SEARCH_KWARGS)
-
- _assert_alias_resolved(embedding_route, search_route, response)
-
-
-def test_sdk_search_with_router_kwarg_resolves_bare_embedding_alias_sync(
- respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
-):
- monkeypatch.delenv("OPENAI_API_KEY", raising=False)
- embedding_route = _mock_embedding_route(respx_mock)
- search_route = _mock_search_route(respx_mock)
-
- response = litellm.vector_stores.search(router=_alias_router(), **ALIAS_SEARCH_KWARGS)
-
- _assert_alias_resolved(embedding_route, search_route, response)
-
-
-async def test_sdk_search_with_router_kwarg_resolves_bare_embedding_alias_async(
- respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
-):
- monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
- monkeypatch.delenv("OPENAI_API_KEY", raising=False)
- embedding_route = _mock_embedding_route(respx_mock)
- search_route = _mock_search_route(respx_mock)
-
- response = await litellm.vector_stores.asearch(router=_alias_router(), **ALIAS_SEARCH_KWARGS)
-
- _assert_alias_resolved(embedding_route, search_route, response)
-
-
-def _team_alias_router():
- return Router(
- model_list=[
- {
- "model_name": "team-a-embedder",
- "litellm_params": {
- "model": "openai/text-embedding-3-small",
- "api_key": "deployment-key",
- },
- "model_info": {"team_id": "team-a", "team_public_model_name": "multilingual-e5-large"},
- }
- ]
- )
-
-
-async def test_sdk_search_with_router_kwarg_resolves_team_alias_from_request_metadata(
- respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
-):
- monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
- monkeypatch.delenv("OPENAI_API_KEY", raising=False)
- embedding_route = _mock_embedding_route(respx_mock)
- search_route = _mock_search_route(respx_mock)
-
- response = await litellm.vector_stores.asearch(
- router=_team_alias_router(), metadata={"user_api_key_team_id": "team-a"}, **ALIAS_SEARCH_KWARGS
- )
-
- _assert_alias_resolved(embedding_route, search_route, response)
-
-
-async def test_sdk_search_with_router_kwarg_rejects_team_alias_without_team_metadata(
- respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
-):
- monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
- monkeypatch.delenv("OPENAI_API_KEY", raising=False)
- embedding_route = _mock_embedding_route(respx_mock)
- _mock_search_route(respx_mock)
-
- with pytest.raises(litellm.APIConnectionError):
- await litellm.vector_stores.asearch(router=_team_alias_router(), **ALIAS_SEARCH_KWARGS)
-
- assert embedding_route.call_count == 0
-
-
-async def test_transform_uses_injected_executor_without_embedding_config(respx_mock: respx.MockRouter):
- executor = RecordingEmbeddingExecutor(ALIAS_EMBEDDING_RESPONSE)
- config = MilvusVectorStoreConfig()
- logging_obj = MagicMock()
- logging_obj.model_call_details = {}
- transform_kwargs = {
- "vector_store_id": "book_2",
- "query": ["what is", "milvus?"],
- "vector_store_search_optional_params": {"limit": 3},
- "api_base": "https://milvus.example",
- "litellm_logging_obj": logging_obj,
- "litellm_params": {"litellm_embedding_model": "multilingual-e5-large", "milvus_db_name": "docs"},
- "embedding_executor": executor,
- }
-
- url, sync_body = config.transform_search_vector_store_request(**transform_kwargs)
- _, async_body = await config.atransform_search_vector_store_request(**transform_kwargs)
-
- assert respx_mock.calls.call_count == 0
- assert executor.calls == [("multilingual-e5-large", "what is milvus?", {})] * 2
- assert url == MILVUS_SEARCH_URL
- assert sync_body == async_body
- assert sync_body == {
- "collectionName": "book_2",
- "data": [ALIAS_QUERY_VECTOR],
- "annsField": "book_intro_vector",
- "limit": 3,
- "dbName": "docs",
- }
- assert logging_obj.model_call_details["input"] == "what is milvus?"
- assert logging_obj.model_call_details["embedding_model"] == "multilingual-e5-large"
-
-
-def test_transform_falls_back_to_sdk_embedding_without_executor_or_config(
- respx_mock: respx.MockRouter, monkeypatch: pytest.MonkeyPatch
-):
- monkeypatch.setenv("OPENAI_API_KEY", "env-key")
- embedding_route = _mock_embedding_route(respx_mock)
- logging_obj = MagicMock()
- logging_obj.model_call_details = {}
-
- _, body = MilvusVectorStoreConfig().transform_search_vector_store_request(
- vector_store_id="book_2",
- query="q",
- vector_store_search_optional_params={},
- api_base="https://milvus.example",
- litellm_logging_obj=logging_obj,
- litellm_params={"litellm_embedding_model": "openai/text-embedding-3-small"},
- )
-
- embedding_request = embedding_route.calls.last.request
- assert embedding_request.headers["authorization"] == "Bearer env-key"
- assert json.loads(embedding_request.read())["input"] == ["q"]
- assert body["data"] == [ALIAS_QUERY_VECTOR]
-
-
-def test_transform_requires_embedding_model():
- with pytest.raises(ValueError, match="litellm_embedding_model is required"):
- MilvusVectorStoreConfig().transform_search_vector_store_request(
- vector_store_id="book_2",
- query="q",
- vector_store_search_optional_params={},
- api_base="https://milvus.example",
- litellm_logging_obj=MagicMock(),
- litellm_params={"litellm_embedding_config": {"api_key": "store-key"}},
- embedding_executor=RecordingEmbeddingExecutor(ALIAS_EMBEDDING_RESPONSE),
- )
diff --git a/tests/vector_store_tests/test_openai_vector_store.py b/tests/vector_store_tests/test_openai_vector_store.py
deleted file mode 100644
index 6327b45eaa1..00000000000
--- a/tests/vector_store_tests/test_openai_vector_store.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from base_vector_store_test import BaseVectorStoreTest
-
-
-class TestOpenAIVectorStore(BaseVectorStoreTest):
- def get_base_request_args(self) -> dict:
- """
- This is a real vector store on OpenAI
- """
- return {
- "vector_store_id": "vs_685b14b1a1b88191bc27e04f1917fddd",
- "custom_llm_provider": "openai",
- }
-
- def get_base_create_vector_store_args(self) -> dict:
- """
- This is a real vector store on OpenAI
- """
- return {
- "custom_llm_provider": "openai",
- }
diff --git a/tests/vector_store_tests/test_ragflow_vector_store.py b/tests/vector_store_tests/test_ragflow_vector_store.py
deleted file mode 100644
index c0511ebacc6..00000000000
--- a/tests/vector_store_tests/test_ragflow_vector_store.py
+++ /dev/null
@@ -1,377 +0,0 @@
-"""
-Test RAGFlow Vector Store helper functions and transformation.
-"""
-
-import os
-import json
-import pytest
-from unittest.mock import Mock, patch, MagicMock
-import httpx
-
-import litellm
-
-from tests.vector_store_tests.base_vector_store_test import BaseVectorStoreTest
-from litellm.llms.ragflow.vector_stores.transformation import RAGFlowVectorStoreConfig
-from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
-from litellm.types.vector_stores import VectorStoreCreateOptionalRequestParams
-from litellm.llms.base_llm.chat.transformation import BaseLLMException
-
-
-class TestRAGFlowVectorStore(BaseVectorStoreTest):
- """
- Test the RAGFlow vector store transformation functionality.
- """
-
- def get_base_create_vector_store_args(self) -> dict:
- """Must return the base create vector store args"""
- return {
- "custom_llm_provider": "ragflow",
- "api_key": os.getenv("RAGFLOW_API_KEY", "test-api-key"),
- "api_base": os.getenv("RAGFLOW_API_BASE", "http://localhost:9380"),
- }
-
- def get_base_request_args(self):
- # RAGFlow doesn't support search, so we'll skip search tests
- return {
- "vector_store_id": "test-dataset-id",
- "custom_llm_provider": "ragflow",
- "query": "test query",
- }
-
- def test_get_auth_credentials(self):
- """Test that auth credentials are correctly extracted."""
- config = RAGFlowVectorStoreConfig()
-
- # Test with api_key in params
- litellm_params = {"api_key": "test-api-key-123"}
- credentials = config.get_auth_credentials(litellm_params)
- assert "headers" in credentials
- assert credentials["headers"]["Authorization"] == "Bearer test-api-key-123"
-
- # Test with missing api_key (should raise ValueError)
- with pytest.raises(ValueError, match="api_key is required"):
- config.get_auth_credentials({})
-
- def test_get_complete_url(self):
- """Test that complete URL is correctly constructed."""
- config = RAGFlowVectorStoreConfig()
-
- # Test with api_base in params
- litellm_params = {"api_base": "http://custom-host:9999"}
- url = config.get_complete_url(api_base=None, litellm_params=litellm_params)
- assert url == "http://custom-host:9999/api/v1/datasets"
-
- # Test with api_base parameter
- url = config.get_complete_url(
- api_base="http://test-host:8888", litellm_params={}
- )
- assert url == "http://test-host:8888/api/v1/datasets"
-
- # Test with default (no api_base provided)
- with patch.dict(os.environ, {}, clear=True):
- url = config.get_complete_url(api_base=None, litellm_params={})
- assert url == "http://localhost:9380/api/v1/datasets"
-
- # Test with trailing slash removal
- url = config.get_complete_url(
- api_base="http://test-host:8888/", litellm_params={}
- )
- assert url == "http://test-host:8888/api/v1/datasets"
-
- def test_validate_environment(self):
- """Test environment validation and header setting."""
- config = RAGFlowVectorStoreConfig()
- from litellm.types.router import GenericLiteLLMParams
-
- # Test with api_key in litellm_params
- litellm_params = GenericLiteLLMParams(api_key="test-key")
- headers = config.validate_environment({}, litellm_params)
- assert headers["Authorization"] == "Bearer test-key"
- assert headers["Content-Type"] == "application/json"
-
- # Test with missing api_key
- with pytest.raises(ValueError, match="RAGFLOW_API_KEY"):
- config.validate_environment({}, GenericLiteLLMParams())
-
- def test_get_vector_store_endpoints_by_type(self):
- """Test that endpoints are correctly configured (empty for management only)."""
- config = RAGFlowVectorStoreConfig()
- endpoints = config.get_vector_store_endpoints_by_type()
- assert endpoints["read"] == []
- assert endpoints["write"] == []
-
- def test_transform_create_vector_store_request_basic(self):
- """Test basic dataset creation request transformation."""
- config = RAGFlowVectorStoreConfig()
-
- params: VectorStoreCreateOptionalRequestParams = {"name": "test-dataset"}
-
- url, body = config.transform_create_vector_store_request(
- params, "http://localhost:9380/api/v1/datasets"
- )
-
- assert url == "http://localhost:9380/api/v1/datasets"
- assert body["name"] == "test-dataset"
- assert body["chunk_method"] == "naive" # Default chunk method
-
- def test_transform_create_vector_store_request_with_metadata(self):
- """Test dataset creation with RAGFlow-specific metadata."""
- config = RAGFlowVectorStoreConfig()
-
- params: VectorStoreCreateOptionalRequestParams = {
- "name": "test-dataset-advanced",
- "metadata": {
- "description": "Test dataset",
- "embedding_model": "BAAI/bge-large-zh-v1.5@BAAI",
- "permission": "me",
- "chunk_method": "naive",
- "parser_config": {"chunk_token_num": 512, "delimiter": "\n"},
- },
- }
-
- url, body = config.transform_create_vector_store_request(
- params, "http://localhost:9380/api/v1/datasets"
- )
-
- assert body["name"] == "test-dataset-advanced"
- assert body["description"] == "Test dataset"
- assert body["embedding_model"] == "BAAI/bge-large-zh-v1.5@BAAI"
- assert body["permission"] == "me"
- assert body["chunk_method"] == "naive"
- assert "parser_config" in body
- assert body["parser_config"]["chunk_token_num"] == 512
-
- def test_transform_create_vector_store_request_missing_name(self):
- """Test that missing name raises ValueError."""
- config = RAGFlowVectorStoreConfig()
-
- params: VectorStoreCreateOptionalRequestParams = {}
-
- with pytest.raises(ValueError, match="name is required"):
- config.transform_create_vector_store_request(
- params, "http://localhost:9380/api/v1/datasets"
- )
-
- def test_transform_create_vector_store_request_mutually_exclusive(self):
- """Test that chunk_method and pipeline_id are mutually exclusive."""
- config = RAGFlowVectorStoreConfig()
-
- params: VectorStoreCreateOptionalRequestParams = {
- "name": "test-dataset",
- "metadata": {
- "chunk_method": "naive",
- "pipeline_id": "d0bebe30ae2211f0970942010a8e0005",
- },
- }
-
- with pytest.raises(ValueError, match="mutually exclusive"):
- config.transform_create_vector_store_request(
- params, "http://localhost:9380/api/v1/datasets"
- )
-
- def test_transform_create_vector_store_request_with_pipeline(self):
- """Test dataset creation with ingestion pipeline."""
- config = RAGFlowVectorStoreConfig()
-
- params: VectorStoreCreateOptionalRequestParams = {
- "name": "test-pipeline-dataset",
- "metadata": {
- "parse_type": 2,
- "pipeline_id": "d0bebe30ae2211f0970942010a8e0005",
- },
- }
-
- url, body = config.transform_create_vector_store_request(
- params, "http://localhost:9380/api/v1/datasets"
- )
-
- assert body["name"] == "test-pipeline-dataset"
- assert body["parse_type"] == 2
- assert body["pipeline_id"] == "d0bebe30ae2211f0970942010a8e0005"
- assert "chunk_method" not in body
-
- def test_transform_create_vector_store_response_success(self):
- """Test successful response transformation."""
- config = RAGFlowVectorStoreConfig()
-
- # Mock RAGFlow response
- mock_response = Mock(spec=httpx.Response)
- mock_response.status_code = 200
- mock_response.headers = {}
- mock_response.json.return_value = {
- "code": 0,
- "data": {
- "id": "3b4de7d4241d11f0a6a79f24fc270c7f",
- "name": "test-dataset",
- "create_time": 1745836841611,
- "chunk_method": "naive",
- "embedding_model": "BAAI/bge-large-zh-v1.5@BAAI",
- },
- }
-
- response = config.transform_create_vector_store_response(mock_response)
-
- assert response["id"] == "3b4de7d4241d11f0a6a79f24fc270c7f"
- assert response["name"] == "test-dataset"
- assert response["object"] == "vector_store"
- assert response["status"] == "completed"
- assert response["created_at"] == 1745836841 # Converted from milliseconds
- assert response["bytes"] == 0
- assert "file_counts" in response
-
- def test_transform_create_vector_store_response_error(self):
- """Test error response transformation."""
- config = RAGFlowVectorStoreConfig()
-
- # Mock RAGFlow error response
- mock_response = Mock(spec=httpx.Response)
- mock_response.status_code = 400
- mock_response.headers = {}
- mock_response.json.return_value = {
- "code": 101,
- "message": "Dataset name 'test-dataset' already exists",
- }
-
- with pytest.raises(BaseLLMException):
- config.transform_create_vector_store_response(mock_response)
-
- def test_transform_create_vector_store_response_missing_id(self):
- """Test response with missing dataset ID."""
- config = RAGFlowVectorStoreConfig()
-
- mock_response = Mock(spec=httpx.Response)
- mock_response.status_code = 200
- mock_response.headers = {}
- mock_response.json.return_value = {
- "code": 0,
- "data": {
- "name": "test-dataset"
- # Missing "id"
- },
- }
-
- with pytest.raises(ValueError, match="missing dataset id"):
- config.transform_create_vector_store_response(mock_response)
-
- def test_transform_search_vector_store_request_not_implemented(self):
- """Test that search operations raise NotImplementedError."""
- config = RAGFlowVectorStoreConfig()
- logging_obj = MagicMock(spec=LiteLLMLoggingObj)
-
- with pytest.raises(NotImplementedError, match="management only"):
- config.transform_search_vector_store_request(
- vector_store_id="test-id",
- query="test query",
- vector_store_search_optional_params={},
- api_base="http://localhost:9380",
- litellm_logging_obj=logging_obj,
- litellm_params={},
- extra_body=None,
- )
-
- def test_transform_search_vector_store_response_not_implemented(self):
- """Test that search response transformation raises NotImplementedError."""
- config = RAGFlowVectorStoreConfig()
- logging_obj = MagicMock(spec=LiteLLMLoggingObj)
- mock_response = Mock(spec=httpx.Response)
-
- with pytest.raises(NotImplementedError, match="management only"):
- config.transform_search_vector_store_response(mock_response, logging_obj)
-
- def _validate_vector_store_create_response(self, response):
- """Override to handle RAGFlow-specific response format."""
- # RAGFlow IDs are hex strings (not OpenAI-style vs_* format)
- # So we override the base validation to not check for vs_ prefix
- assert isinstance(
- response, dict
- ), f"Response should be a dict, got {type(response)}"
- assert "id" in response, "Missing required field 'id' in create response"
- assert (
- "object" in response
- ), "Missing required field 'object' in create response"
- assert (
- "created_at" in response
- ), "Missing required field 'created_at' in create response"
-
- assert (
- response["object"] == "vector_store"
- ), f"Expected object to be 'vector_store', got '{response['object']}'"
-
- assert isinstance(
- response["id"], str
- ), f"id should be a string, got {type(response['id'])}"
- assert len(response["id"]) > 0, "id should not be empty"
- # RAGFlow IDs are hex strings, not OpenAI-style vs_* format
-
- assert isinstance(
- response["created_at"], int
- ), f"created_at should be an integer, got {type(response['created_at'])}"
- assert response["created_at"] > 0, "created_at should be a positive timestamp"
-
- print(
- f"✅ RAGFlow create response validation passed: Dataset '{response['id']}' created successfully"
- )
-
- @pytest.mark.parametrize("sync_mode", [True, False])
- @pytest.mark.asyncio
- async def test_basic_create_vector_store(self, sync_mode):
- """Override to handle RAGFlow-specific connection errors."""
- litellm.turn_on_debug()
- litellm.set_verbose = True
- base_request_args = self.get_base_create_vector_store_args()
-
- # Skip if no API key is set
- if not os.getenv("RAGFLOW_API_KEY") and not base_request_args.get("api_key"):
- pytest.skip("RAGFLOW_API_KEY not set, skipping integration test")
-
- # Extract custom_llm_provider from base args if present
- create_args = base_request_args
- try:
- if sync_mode:
- response = litellm.vector_stores.create(
- name=f"test-ragflow-{int(__import__('time').time())}", **create_args
- )
- else:
- response = await litellm.vector_stores.acreate(
- name=f"test-ragflow-{int(__import__('time').time())}", **create_args
- )
- except litellm.InternalServerError:
- pytest.skip("Skipping test due to litellm.InternalServerError")
- except Exception as e:
- error_str = str(e).lower()
- error_type = type(e).__name__
-
- # Check if it's a connection error
- if (
- isinstance(e, (ConnectionError, OSError))
- or "connection" in error_str
- or "connect" in error_str
- or "APIConnectionError" in error_type
- ):
- pytest.skip(
- f"Skipping test due to connection error (RAGFlow instance may not be running): {e}"
- )
-
- # If this is an authentication or permission error, skip the test
- if (
- "authentication" in error_str
- or "permission" in error_str
- or "unauthorized" in error_str
- ):
- pytest.skip(
- f"Skipping test due to authentication/permission error: {e}"
- )
-
- # Re-raise if it's not a handled error
- raise
-
- print("litellm create response=", json.dumps(response, indent=4, default=str))
-
- # Validate response structure
- self._validate_vector_store_create_response(response)
-
- @pytest.mark.parametrize("sync_mode", [True, False])
- @pytest.mark.asyncio
- async def test_basic_search_vector_store(self, sync_mode):
- """Override search test - RAGFlow doesn't support search."""
- pytest.skip("RAGFlow vector stores support dataset management only, not search")
diff --git a/tests/vector_store_tests/test_s3_vectors_vector_store.py b/tests/vector_store_tests/test_s3_vectors_vector_store.py
deleted file mode 100644
index e99af039d68..00000000000
--- a/tests/vector_store_tests/test_s3_vectors_vector_store.py
+++ /dev/null
@@ -1,44 +0,0 @@
-from base_vector_store_test import BaseVectorStoreTest
-import os
-import pytest
-
-
-class TestS3VectorsVectorStore(BaseVectorStoreTest):
- @pytest.fixture(autouse=True)
- def check_env_vars(self):
- """Check if required environment variables are set"""
- required_vars = ["AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY"]
- missing_vars = [var for var in required_vars if not os.getenv(var)]
- if missing_vars:
- pytest.skip(
- f"Missing required environment variables: {', '.join(missing_vars)}"
- )
-
- def get_base_request_args(self) -> dict:
- """
- Must return the base request args for searching.
- For S3 Vectors, vector_store_id should be in format: bucket_name:index_name
- """
- return {
- "custom_llm_provider": "s3_vectors",
- "vector_store_id": os.getenv(
- "S3_VECTORS_VECTOR_STORE_ID", "test-litellm-vectors:test-index"
- ),
- "query": "What is machine learning?",
- "aws_region_name": os.getenv("AWS_REGION_NAME", "us-west-2"),
- "aws_access_key_id": os.getenv("AWS_ACCESS_KEY_ID"),
- "aws_secret_access_key": os.getenv("AWS_SECRET_ACCESS_KEY"),
- }
-
- def get_base_create_vector_store_args(self) -> dict:
- """
- Vector store creation is not yet implemented for S3 Vectors.
- This test will be skipped.
- """
- return {}
-
- @pytest.mark.parametrize("sync_mode", [True, False])
- @pytest.mark.asyncio
- async def test_basic_create_vector_store(self, sync_mode):
- """S3 Vectors doesn't support vector store creation via this API yet"""
- pytest.skip("Vector store creation not yet implemented for S3 Vectors")
diff --git a/tests/vector_store_tests/test_vertex_ai_search_api_vector_store.py b/tests/vector_store_tests/test_vertex_ai_search_api_vector_store.py
deleted file mode 100644
index 7cace338616..00000000000
--- a/tests/vector_store_tests/test_vertex_ai_search_api_vector_store.py
+++ /dev/null
@@ -1,194 +0,0 @@
-"""
-Test for Vertex AI Search API Vector Store with mocked responses
-"""
-
-import json
-import pytest
-from unittest.mock import AsyncMock, MagicMock, patch
-import litellm
-
-
-# Mock response from actual Vertex AI Search API
-MOCK_VERTEX_SEARCH_RESPONSE = {
- "results": [
- {
- "id": "0",
- "document": {
- "name": "projects/648660250433/locations/global/collections/default_collection/dataStores/litellm-docs_1761094140318/branches/0/documents/0",
- "id": "0",
- "derivedStructData": {
- "htmlTitle": "<b>LiteLLM</b> - Getting Started | <b>liteLLM</b>",
- "snippets": [
- {
- "htmlSnippet": "https://github.com/BerriAI/<b>litellm</b>.",
- "snippet": "https://github.com/BerriAI/litellm.",
- }
- ],
- "title": "LiteLLM - Getting Started | liteLLM",
- "link": "https://docs.litellm.ai/docs/",
- "displayLink": "docs.litellm.ai",
- },
- },
- },
- {
- "id": "1",
- "document": {
- "name": "projects/648660250433/locations/global/collections/default_collection/dataStores/litellm-docs_1761094140318/branches/0/documents/1",
- "id": "1",
- "derivedStructData": {
- "title": "Using Vector Stores (Knowledge Bases) | liteLLM",
- "link": "https://docs.litellm.ai/docs/completion/knowledgebase",
- "snippets": [
- {
- "snippet": "LiteLLM integrates with vector stores, allowing your models to access your organization's data for more accurate and contextually relevant responses."
- }
- ],
- },
- },
- },
- ],
- "totalSize": 299,
- "attributionToken": "mock_token",
- "summary": {},
-}
-
-
-class TestVertexAISearchAPIVectorStore:
- """Test Vertex AI Search API Vector Store with mocked responses"""
-
- @pytest.mark.asyncio
- async def test_basic_search_with_mock(self):
- """Test basic vector search with mocked backend response"""
-
- # Mock the HTTP response
- mock_response = MagicMock()
- mock_response.status_code = 200
- mock_response.json.return_value = MOCK_VERTEX_SEARCH_RESPONSE
- mock_response.text = json.dumps(MOCK_VERTEX_SEARCH_RESPONSE)
-
- # Mock the access token method to avoid real authentication
- with patch(
- "litellm.llms.vertex_ai.vector_stores.search_api.transformation.VertexSearchAPIVectorStoreConfig._ensure_access_token"
- ) as mock_auth:
- mock_auth.return_value = ("mock_token", "test-vector-store-db")
-
- with patch(
- "litellm.llms.custom_httpx.http_handler.AsyncHTTPHandler.post",
- new_callable=AsyncMock,
- ) as mock_post:
- mock_post.return_value = mock_response
-
- # Make the search request
- response = await litellm.vector_stores.asearch(
- query="what is LiteLLM?",
- vector_store_id="test-litellm-app_1761094730750",
- custom_llm_provider="vertex_ai/search_api",
- vertex_project="test-vector-store-db",
- vertex_location="us-central1",
- )
-
- print("Response:", json.dumps(response, indent=2, default=str))
-
- # Validate the response structure (LiteLLM standard format)
- assert response is not None
- assert response["object"] == "vector_store.search_results.page"
- assert "data" in response
- assert len(response["data"]) > 0
- assert "search_query" in response
-
- # Validate first result
- first_result = response["data"][0]
- assert "score" in first_result
- assert "content" in first_result
- assert "file_id" in first_result
- assert "filename" in first_result
- assert "attributes" in first_result
-
- # Validate content structure
- assert len(first_result["content"]) > 0
- assert first_result["content"][0]["type"] == "text"
- assert "text" in first_result["content"][0]
-
- # Verify the API was called
- mock_post.assert_called_once()
-
- # Verify the URL format
- call_args = mock_post.call_args
- url = call_args[1]["url"] if "url" in call_args[1] else call_args[0][0]
- assert "discoveryengine.googleapis.com" in url
- assert "test-vector-store-db" in url
- assert "test-litellm-app_1761094730750" in url
-
- def test_basic_search_sync_with_mock(self):
- """Test basic vector search (sync) with mocked backend response"""
-
- # Mock the HTTP response
- mock_response = MagicMock()
- mock_response.status_code = 200
- mock_response.json.return_value = MOCK_VERTEX_SEARCH_RESPONSE
- mock_response.text = json.dumps(MOCK_VERTEX_SEARCH_RESPONSE)
-
- # Mock the access token method to avoid real authentication
- with patch(
- "litellm.llms.vertex_ai.vector_stores.search_api.transformation.VertexSearchAPIVectorStoreConfig._ensure_access_token"
- ) as mock_auth:
- mock_auth.return_value = ("mock_token", "test-vector-store-db")
-
- with patch(
- "litellm.llms.custom_httpx.http_handler.HTTPHandler.post"
- ) as mock_post:
- mock_post.return_value = mock_response
-
- # Make the search request
- response = litellm.vector_stores.search(
- query="what is LiteLLM?",
- vector_store_id="test-litellm-app_1761094730750",
- custom_llm_provider="vertex_ai/search_api",
- vertex_project="test-vector-store-db",
- vertex_location="us-central1",
- )
-
- print("Response:", json.dumps(response, indent=2, default=str))
-
- # Validate the response structure (LiteLLM standard format)
- assert response is not None
- assert response["object"] == "vector_store.search_results.page"
- assert "data" in response
- assert len(response["data"]) > 0
- assert "search_query" in response
-
- # Validate first result structure
- first_result = response["data"][0]
- assert "score" in first_result
- assert "content" in first_result
- assert "file_id" in first_result
- assert "filename" in first_result
- assert "attributes" in first_result
-
- # Validate content structure
- assert len(first_result["content"]) > 0
- assert first_result["content"][0]["type"] == "text"
- assert "text" in first_result["content"][0]
-
- # Validate attributes
- assert "document_id" in first_result["attributes"]
- assert "link" in first_result["attributes"]
- assert "title" in first_result["attributes"]
-
- # Verify the API was called
- mock_post.assert_called_once()
-
-
-if __name__ == "__main__":
- # Run tests
- import asyncio
-
- test = TestVertexAISearchAPIVectorStore()
-
- print("Running async test...")
- asyncio.run(test.test_basic_search_with_mock())
-
- print("\nRunning sync test...")
- test.test_basic_search_sync_with_mock()
-
- print("\n✅ All tests passed!")
diff --git a/tests/vector_store_tests/test_vertex_ai_vector_store.py b/tests/vector_store_tests/test_vertex_ai_vector_store.py
deleted file mode 100644
index 9dcbe4956a2..00000000000
--- a/tests/vector_store_tests/test_vertex_ai_vector_store.py
+++ /dev/null
@@ -1,27 +0,0 @@
-import os
-import pytest
-from unittest.mock import Mock, patch
-
-from litellm.llms.vertex_ai.vector_stores.transformation import VertexVectorStoreConfig
-from litellm.types.vector_stores import (
- VectorStoreCreateResponse,
- VectorStoreSearchResponse,
- VectorStoreSearchResult,
- VectorStoreResultContent,
-)
-from tests.vector_store_tests.base_vector_store_test import BaseVectorStoreTest
-
-
-class TestVertexAIVectorStore(BaseVectorStoreTest):
- def get_base_create_vector_store_args(self) -> dict:
- """Must return the base create vector store args"""
- return {}
-
- def get_base_request_args(self):
- return {
- "vector_store_id": "6917529027641081856",
- "custom_llm_provider": "vertex_ai",
- "vertex_project": "reliablekeys",
- "vertex_location": "us-central1",
- "query": "what happens after we add a model",
- }