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]

feat(voyage): add rerank API support (#17744)

Cesar Garcia63a97db66309
diff --git a/docs/my-website/docs/providers/voyage.md b/docs/my-website/docs/providers/voyage.md
index b1e4cf932e6..43369cd6ab7 100644
--- a/docs/my-website/docs/providers/voyage.md
+++ b/docs/my-website/docs/providers/voyage.md
@@ -150,3 +150,107 @@ print(f"Processed {len(response.data)} documents")
| voyage-finance-2 | Financial documents | 32K | $0.12 |
| voyage-law-2 | Legal documents | 16K | $0.12 |
| voyage-context-3 | Contextual document embeddings | 32K | $0.18 |
+
+## Rerank
+
+Voyage AI provides reranking models to improve search relevance by reordering documents based on their relevance to a query.
+
+### Quick Start
+
+```python
+from litellm import rerank
+import os
+
+os.environ["VOYAGE_API_KEY"] = "your-api-key"
+
+response = rerank(
+ model="voyage/rerank-2.5",
+ query="What is the capital of France?",
+ documents=[
+ "Paris is the capital of France.",
+ "London is the capital of England.",
+ "Berlin is the capital of Germany.",
+ ],
+ top_n=3,
+)
+
+print(response)
+```
+
+### Async Usage
+
+```python
+from litellm import arerank
+import os
+import asyncio
+
+os.environ["VOYAGE_API_KEY"] = "your-api-key"
+
+async def main():
+ response = await arerank(
+ model="voyage/rerank-2.5-lite",
+ query="Best programming language for beginners?",
+ documents=[
+ "Python is great for beginners due to simple syntax.",
+ "JavaScript runs in browsers and is versatile.",
+ "Rust has a steep learning curve but is very safe.",
+ ],
+ top_n=2,
+ )
+ print(response)
+
+asyncio.run(main())
+```
+
+### LiteLLM Proxy Usage
+
+Add to your `config.yaml`:
+
+```yaml
+model_list:
+ - model_name: rerank-2.5
+ litellm_params:
+ model: voyage/rerank-2.5
+ api_key: os.environ/VOYAGE_API_KEY
+ - model_name: rerank-2.5-lite
+ litellm_params:
+ model: voyage/rerank-2.5-lite
+ api_key: os.environ/VOYAGE_API_KEY
+```
+
+Test with curl:
+
+```bash
+curl http://localhost:4000/rerank \
+ -H "Authorization: Bearer sk-1234" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "model": "rerank-2.5",
+ "query": "What is the capital of France?",
+ "documents": [
+ "Paris is the capital of France.",
+ "London is the capital of England.",
+ "Berlin is the capital of Germany."
+ ],
+ "top_n": 3
+ }'
+```
+
+### Supported Rerank Models
+
+| Model | Context Length | Description | Price/M Tokens |
+|-------|----------------|-------------|----------------|
+| rerank-2.5 | 32K | Best quality, multilingual, instruction-following | $0.05 |
+| rerank-2.5-lite | 32K | Optimized for latency and cost | $0.02 |
+| rerank-2 | 16K | Legacy model | $0.05 |
+| rerank-2-lite | 8K | Legacy model, faster | $0.02 |
+
+### Supported Parameters
+
+| Parameter | Type | Description |
+|-----------|------|-------------|
+| `model` | string | Model name (e.g., `voyage/rerank-2.5`) |
+| `query` | string | The search query |
+| `documents` | list | List of documents to rerank |
+| `top_n` | int | Number of top results to return |
+| `return_documents` | bool | Whether to include document text in response |
diff --git a/docs/my-website/docs/rerank.md b/docs/my-website/docs/rerank.md
index a0433cb7a2a..90f685d2bbd 100644
--- a/docs/my-website/docs/rerank.md
+++ b/docs/my-website/docs/rerank.md
@@ -16,7 +16,7 @@ LiteLLM Follows the [cohere api request / response for the rerank api](https://c
| Fallbacks | ✅ | Works between supported models |
| Loadbalancing | ✅ | Works between supported models |
| Guardrails | ✅ | Applies to input query only (not documents) |
-| Supported Providers | Cohere, Together AI, Azure AI, DeepInfra, Nvidia NIM, Infinity, Fireworks AI | |
+| Supported Providers | Cohere, Together AI, Azure AI, DeepInfra, Nvidia NIM, Infinity, Fireworks AI, Voyage AI | |
## **LiteLLM Python SDK Usage**
### Quick Start
@@ -134,5 +134,6 @@ curl http://0.0.0.0:4000/rerank \
| Infinity| [Usage](../docs/providers/infinity) |
| vLLM| [Usage](../docs/providers/vllm#rerank-endpoint) |
| DeepInfra| [Usage](../docs/providers/deepinfra#rerank-endpoint) |
-| Vertex AI| [Usage](../docs/providers/vertex#rerank-api) |
-| Fireworks AI| [Usage](../docs/providers/fireworks_ai#rerank-endpoint) |
\ No newline at end of file
+| Vertex AI| [Usage](../docs/providers/vertex#rerank-api) |
+| Fireworks AI| [Usage](../docs/providers/fireworks_ai#rerank-endpoint) |
+| Voyage AI| [Usage](../docs/providers/voyage#rerank) |
\ No newline at end of file
diff --git a/litellm/__init__.py b/litellm/__init__.py
index 34bfc778982..e9bfed2ed1f 100644
--- a/litellm/__init__.py
+++ b/litellm/__init__.py
@@ -1114,6 +1114,7 @@ from .llms.nvidia_nim.rerank.transformation import NvidiaNimRerankConfig
from .llms.nvidia_nim.rerank.ranking_transformation import NvidiaNimRankingConfig
from .llms.vertex_ai.rerank.transformation import VertexAIRerankConfig
from .llms.fireworks_ai.rerank.transformation import FireworksAIRerankConfig
+from .llms.voyage.rerank.transformation import VoyageRerankConfig
from .llms.clarifai.chat.transformation import ClarifaiConfig
from .llms.ai21.chat.transformation import AI21ChatConfig, AI21ChatConfig as AI21Config
from .llms.meta_llama.chat.transformation import LlamaAPIConfig
diff --git a/litellm/llms/voyage/rerank/handler.py b/litellm/llms/voyage/rerank/handler.py
new file mode 100644
index 00000000000..c210bdc5436
--- /dev/null
+++ b/litellm/llms/voyage/rerank/handler.py
@@ -0,0 +1,5 @@
+"""
+Voyage AI Rerank Handler
+
+HTTP calling is handled by `litellm/llms/custom_httpx/llm_http_handler.py`
+"""
diff --git a/litellm/llms/voyage/rerank/transformation.py b/litellm/llms/voyage/rerank/transformation.py
new file mode 100644
index 00000000000..bb1af1e49e9
--- /dev/null
+++ b/litellm/llms/voyage/rerank/transformation.py
@@ -0,0 +1,168 @@
+"""
+Transformation logic for Voyage AI's /v1/rerank endpoint.
+
+Docs - https://docs.voyageai.com/docs/reranker
+"""
+
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+import httpx
+
+from litellm.llms.base_llm.chat.transformation import LiteLLMLoggingObj
+from litellm.llms.base_llm.rerank.transformation import BaseRerankConfig
+from litellm.secret_managers.main import get_secret_str
+from litellm.types.rerank import (
+ OptionalRerankParams,
+ RerankBilledUnits,
+ RerankResponse,
+ RerankResponseMeta,
+ RerankTokens,
+)
+from litellm.types.utils import ModelInfo
+
+from ..embedding.transformation import VoyageError
+
+
+class VoyageRerankConfig(BaseRerankConfig):
+
+ def get_supported_cohere_rerank_params(self, model: str) -> list:
+ return ["query", "documents", "top_n", "return_documents"]
+
+ def map_cohere_rerank_params(
+ self,
+ non_default_params: dict,
+ model: str,
+ drop_params: bool,
+ query: str,
+ documents: List[Union[str, Dict[str, Any]]],
+ custom_llm_provider: Optional[str] = None,
+ top_n: Optional[int] = None,
+ rank_fields: Optional[List[str]] = None,
+ return_documents: Optional[bool] = True,
+ max_chunks_per_doc: Optional[int] = None,
+ max_tokens_per_doc: Optional[int] = None,
+ ) -> Dict:
+ # Voyage AI uses 'top_k' instead of 'top_n'
+ optional_params: Dict[str, Any] = {"query": query, "documents": documents}
+ if top_n is not None:
+ optional_params["top_k"] = top_n
+ if return_documents is not None:
+ optional_params["return_documents"] = return_documents
+ return dict(OptionalRerankParams(**optional_params))
+
+ def get_complete_url(
+ self,
+ api_base: Optional[str],
+ model: str,
+ optional_params: Optional[dict] = None,
+ ) -> str:
+ if api_base is None:
+ return "https://api.voyageai.com/v1/rerank"
+ api_base = api_base.rstrip("/")
+ if not api_base.endswith("/v1/rerank"):
+ if api_base.endswith("/v1"):
+ api_base = f"{api_base}/rerank"
+ else:
+ api_base = f"{api_base}/v1/rerank"
+ return api_base
+
+ def transform_rerank_request(
+ self, model: str, optional_rerank_params: Dict, headers: Dict
+ ) -> Dict:
+ return {"model": model, **optional_rerank_params}
+
+ def transform_rerank_response(
+ self,
+ model: str,
+ raw_response: httpx.Response,
+ model_response: RerankResponse,
+ logging_obj: LiteLLMLoggingObj,
+ api_key: Optional[str] = None,
+ request_data: Dict = {},
+ optional_params: Dict = {},
+ litellm_params: Dict = {},
+ ) -> RerankResponse:
+ if raw_response.status_code != 200:
+ raise VoyageError(
+ message=raw_response.text, status_code=raw_response.status_code
+ )
+
+ logging_obj.post_call(original_response=raw_response.text)
+
+ try:
+ _json_response = raw_response.json()
+ except Exception:
+ raise VoyageError(
+ message=f"Failed to parse response: {raw_response.text}",
+ status_code=raw_response.status_code,
+ )
+
+ # Voyage AI returns results in "data" key, not "results"
+ _results: Optional[List[dict]] = _json_response.get("data")
+ if _results is None:
+ raise ValueError(f"No results found in the response={_json_response}")
+
+ # Transform to LiteLLM format
+ transformed_results = []
+ for result in _results:
+ transformed_result: Dict[str, Any] = {
+ "index": result["index"],
+ "relevance_score": result["relevance_score"],
+ }
+ if "document" in result:
+ if isinstance(result["document"], str):
+ transformed_result["document"] = {"text": result["document"]}
+ else:
+ transformed_result["document"] = result["document"]
+ transformed_results.append(transformed_result)
+
+ usage = _json_response.get("usage", {})
+ total_tokens = usage.get("total_tokens", 0)
+ _billed_units = RerankBilledUnits(total_tokens=total_tokens)
+ _tokens = RerankTokens(input_tokens=total_tokens, output_tokens=0)
+ rerank_meta = RerankResponseMeta(billed_units=_billed_units, tokens=_tokens)
+
+ return RerankResponse(
+ id=_json_response.get("id", f"voyage-rerank-{model}"),
+ results=transformed_results, # type: ignore
+ meta=rerank_meta,
+ )
+
+ def validate_environment(
+ self,
+ headers: Dict,
+ model: str,
+ api_key: Optional[str] = None,
+ optional_params: Optional[dict] = None,
+ ) -> Dict:
+ if api_key is None:
+ api_key = get_secret_str("VOYAGE_API_KEY") or get_secret_str("VOYAGE_AI_API_KEY")
+ if api_key is None:
+ raise ValueError(
+ "Voyage AI API key is required. Set via `api_key` parameter or `VOYAGE_API_KEY` env var."
+ )
+ return {"Authorization": f"Bearer {api_key}", "content-type": "application/json"}
+
+ def calculate_rerank_cost(
+ self,
+ model: str,
+ custom_llm_provider: Optional[str] = None,
+ billed_units: Optional[RerankBilledUnits] = None,
+ model_info: Optional[ModelInfo] = None,
+ ) -> Tuple[float, float]:
+ if (
+ model_info is None
+ or "input_cost_per_token" not in model_info
+ or model_info["input_cost_per_token"] is None
+ or billed_units is None
+ ):
+ return 0.0, 0.0
+ total_tokens = billed_units.get("total_tokens")
+ if total_tokens is None:
+ return 0.0, 0.0
+ return model_info["input_cost_per_token"] * total_tokens, 0.0
+
+ def get_error_class(
+ self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers]
+ ):
+ return VoyageError(message=error_message, status_code=status_code, headers=headers)
diff --git a/litellm/rerank_api/main.py b/litellm/rerank_api/main.py
index 80360d994e5..3a2b75e58da 100644
--- a/litellm/rerank_api/main.py
+++ b/litellm/rerank_api/main.py
@@ -29,7 +29,7 @@ async def arerank(
model: str,
query: str,
documents: List[Union[str, Dict[str, Any]]],
- custom_llm_provider: Optional[Literal["cohere", "together_ai", "deepinfra", "fireworks_ai"]] = None,
+ custom_llm_provider: Optional[Literal["cohere", "together_ai", "deepinfra", "fireworks_ai", "voyage"]] = None,
top_n: Optional[int] = None,
rank_fields: Optional[List[str]] = None,
return_documents: Optional[bool] = None,
@@ -84,6 +84,7 @@ def rerank( # noqa: PLR0915
"hosted_vllm",
"deepinfra",
"fireworks_ai",
+ "voyage",
]
] = None,
top_n: Optional[int] = None,
@@ -442,6 +443,34 @@ def rerank( # noqa: PLR0915
or get_secret_str("FIREWORKS_AI_API_BASE")
)
+ response = base_llm_http_handler.rerank(
+ model=model,
+ custom_llm_provider=_custom_llm_provider,
+ provider_config=rerank_provider_config,
+ optional_rerank_params=optional_rerank_params,
+ logging_obj=litellm_logging_obj,
+ timeout=optional_params.timeout,
+ api_key=api_key,
+ api_base=api_base,
+ _is_async=_is_async,
+ headers=headers or litellm.headers or {},
+ client=client,
+ model_response=model_response,
+ )
+ elif _custom_llm_provider == litellm.LlmProviders.VOYAGE:
+ api_key = (
+ dynamic_api_key
+ or optional_params.api_key
+ or get_secret_str("VOYAGE_API_KEY")
+ or get_secret_str("VOYAGE_AI_API_KEY")
+ )
+
+ api_base = (
+ dynamic_api_base
+ or optional_params.api_base
+ or get_secret_str("VOYAGE_API_BASE")
+ )
+
response = base_llm_http_handler.rerank(
model=model,
custom_llm_provider=_custom_llm_provider,
diff --git a/litellm/utils.py b/litellm/utils.py
index 9279703af1a..284007328ff 100644
--- a/litellm/utils.py
+++ b/litellm/utils.py
@@ -7375,6 +7375,8 @@ class ProviderConfigManager:
return litellm.VertexAIRerankConfig()
elif litellm.LlmProviders.FIREWORKS_AI == provider:
return litellm.FireworksAIRerankConfig()
+ elif litellm.LlmProviders.VOYAGE == provider:
+ return litellm.VoyageRerankConfig()
return litellm.CohereRerankConfig()
@staticmethod
diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.json
index 549c3d60018..86ff3cadd33 100644
--- a/model_prices_and_context_window.json
+++ b/model_prices_and_context_window.json
@@ -26749,7 +26749,6 @@
]
},
"voyage/rerank-2": {
- "input_cost_per_query": 5e-08,
"input_cost_per_token": 5e-08,
"litellm_provider": "voyage",
"max_input_tokens": 16000,
@@ -26760,7 +26759,6 @@
"output_cost_per_token": 0.0
},
"voyage/rerank-2-lite": {
- "input_cost_per_query": 2e-08,
"input_cost_per_token": 2e-08,
"litellm_provider": "voyage",
"max_input_tokens": 8000,
@@ -26770,6 +26768,26 @@
"mode": "rerank",
"output_cost_per_token": 0.0
},
+ "voyage/rerank-2.5": {
+ "input_cost_per_token": 5e-08,
+ "litellm_provider": "voyage",
+ "max_input_tokens": 32000,
+ "max_output_tokens": 32000,
+ "max_query_tokens": 32000,
+ "max_tokens": 32000,
+ "mode": "rerank",
+ "output_cost_per_token": 0.0
+ },
+ "voyage/rerank-2.5-lite": {
+ "input_cost_per_token": 2e-08,
+ "litellm_provider": "voyage",
+ "max_input_tokens": 32000,
+ "max_output_tokens": 32000,
+ "max_query_tokens": 32000,
+ "max_tokens": 32000,
+ "mode": "rerank",
+ "output_cost_per_token": 0.0
+ },
"voyage/voyage-2": {
"input_cost_per_token": 1e-07,
"litellm_provider": "voyage",
diff --git a/tests/test_litellm/llms/voyage/rerank/__init__.py b/tests/test_litellm/llms/voyage/rerank/__init__.py
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/tests/test_litellm/llms/voyage/rerank/test_voyage_rerank_transformation.py b/tests/test_litellm/llms/voyage/rerank/test_voyage_rerank_transformation.py
new file mode 100644
index 00000000000..6ea8095d690
--- /dev/null
+++ b/tests/test_litellm/llms/voyage/rerank/test_voyage_rerank_transformation.py
@@ -0,0 +1,312 @@
+"""
+Tests for Voyage AI rerank transformation functionality.
+"""
+
+import json
+from unittest.mock import MagicMock
+
+import httpx
+import pytest
+
+from litellm.llms.voyage.rerank.transformation import VoyageRerankConfig
+from litellm.types.rerank import RerankResponse
+
+
+class TestVoyageRerankTransform:
+ def setup_method(self):
+ self.config = VoyageRerankConfig()
+ self.model = "rerank-2.5"
+
+ def test_get_complete_url_default(self):
+ """Test URL generation with default api_base."""
+ url = self.config.get_complete_url(api_base=None, model=self.model)
+ assert url == "https://api.voyageai.com/v1/rerank"
+
+ def test_get_complete_url_custom_base(self):
+ """Test URL generation with custom api_base."""
+ api_base = "https://custom.api.com"
+ url = self.config.get_complete_url(api_base=api_base, model=self.model)
+ assert url == "https://custom.api.com/v1/rerank"
+
+ def test_get_complete_url_with_trailing_slash(self):
+ """Test URL generation with trailing slash in api_base."""
+ api_base = "https://custom.api.com/"
+ url = self.config.get_complete_url(api_base=api_base, model=self.model)
+ assert url == "https://custom.api.com/v1/rerank"
+
+ def test_get_complete_url_with_v1_suffix(self):
+ """Test URL generation when api_base already has /v1."""
+ api_base = "https://custom.api.com/v1"
+ url = self.config.get_complete_url(api_base=api_base, model=self.model)
+ assert url == "https://custom.api.com/v1/rerank"
+
+ def test_get_complete_url_already_complete(self):
+ """Test URL generation when api_base already has /v1/rerank."""
+ api_base = "https://custom.api.com/v1/rerank"
+ url = self.config.get_complete_url(api_base=api_base, model=self.model)
+ assert url == "https://custom.api.com/v1/rerank"
+
+ def test_map_cohere_rerank_params_basic(self):
+ """Test basic parameter mapping for Voyage AI rerank."""
+ params = self.config.map_cohere_rerank_params(
+ non_default_params={},
+ model=self.model,
+ drop_params=False,
+ query="test query",
+ documents=["doc1", "doc2"],
+ top_n=3,
+ return_documents=True,
+ )
+ assert params["query"] == "test query"
+ assert params["documents"] == ["doc1", "doc2"]
+ # Voyage uses top_k instead of top_n
+ assert params["top_k"] == 3
+ assert params["return_documents"] is True
+
+ def test_map_cohere_rerank_params_ignores_unsupported(self):
+ """Test that unsupported params are silently ignored."""
+ params = self.config.map_cohere_rerank_params(
+ non_default_params={},
+ model=self.model,
+ drop_params=False,
+ query="test query",
+ documents=["doc1", "doc2"],
+ rank_fields=["field1"], # Not supported by Voyage AI
+ max_chunks_per_doc=5, # Not supported by Voyage AI
+ max_tokens_per_doc=100, # Not supported by Voyage AI
+ )
+ assert params["query"] == "test query"
+ assert params["documents"] == ["doc1", "doc2"]
+ # Unsupported params should not be in the result
+ assert "rank_fields" not in params
+ assert "max_chunks_per_doc" not in params
+ assert "max_tokens_per_doc" not in params
+
+ def test_transform_rerank_request(self):
+ """Test request transformation for Voyage AI format."""
+ optional_params = {
+ "query": "What is the capital of France?",
+ "documents": [
+ "Paris is the capital of France.",
+ "France is a country in Europe.",
+ ],
+ "top_k": 2,
+ "return_documents": True,
+ }
+
+ request_body = self.config.transform_rerank_request(
+ model=self.model, optional_rerank_params=optional_params, headers={}
+ )
+
+ assert request_body["model"] == "rerank-2.5"
+ assert request_body["query"] == "What is the capital of France?"
+ assert request_body["documents"] == optional_params["documents"]
+ assert request_body["top_k"] == 2
+ assert request_body["return_documents"] is True
+
+ def test_transform_rerank_response_success(self):
+ """Test successful response transformation."""
+ # Mock Voyage AI response format
+ response_data = {
+ "object": "list",
+ "data": [
+ {"relevance_score": 0.88671875, "index": 0},
+ {"relevance_score": 0.353515625, "index": 2},
+ {"relevance_score": 0.33984375, "index": 1},
+ ],
+ "model": "rerank-2.5",
+ "usage": {"total_tokens": 30},
+ }
+
+ # Create mock httpx response
+ mock_response = MagicMock(spec=httpx.Response)
+ mock_response.json.return_value = response_data
+ mock_response.status_code = 200
+ mock_response.text = json.dumps(response_data)
+ mock_response.headers = {}
+
+ # Create mock logging object
+ mock_logging = MagicMock()
+
+ model_response = RerankResponse()
+
+ result = self.config.transform_rerank_response(
+ model=self.model,
+ raw_response=mock_response,
+ model_response=model_response,
+ logging_obj=mock_logging,
+ )
+
+ # Verify response structure
+ assert len(result.results) == 3
+ assert result.results[0]["index"] == 0
+ assert result.results[0]["relevance_score"] == 0.88671875
+ assert result.results[1]["index"] == 2
+ assert result.results[1]["relevance_score"] == 0.353515625
+ assert result.results[2]["index"] == 1
+ assert result.results[2]["relevance_score"] == 0.33984375
+
+ # Verify metadata
+ assert result.meta["tokens"]["input_tokens"] == 30
+ assert result.meta["billed_units"]["total_tokens"] == 30
+
+ def test_transform_rerank_response_with_documents(self):
+ """Test response transformation when return_documents is True."""
+ response_data = {
+ "object": "list",
+ "data": [
+ {
+ "relevance_score": 0.95,
+ "index": 0,
+ "document": "Paris is the capital of France.",
+ },
+ {
+ "relevance_score": 0.75,
+ "index": 1,
+ "document": "France is a country in Europe.",
+ },
+ ],
+ "model": "rerank-2.5",
+ "usage": {"total_tokens": 50},
+ }
+
+ mock_response = MagicMock(spec=httpx.Response)
+ mock_response.json.return_value = response_data
+ mock_response.status_code = 200
+ mock_response.text = json.dumps(response_data)
+ mock_response.headers = {}
+
+ mock_logging = MagicMock()
+ model_response = RerankResponse()
+
+ result = self.config.transform_rerank_response(
+ model=self.model,
+ raw_response=mock_response,
+ model_response=model_response,
+ logging_obj=mock_logging,
+ )
+
+ assert len(result.results) == 2
+ assert result.results[0]["document"]["text"] == "Paris is the capital of France."
+ assert result.results[1]["document"]["text"] == "France is a country in Europe."
+
+ def test_transform_rerank_response_missing_data(self):
+ """Test that missing data raises ValueError."""
+ response_data = {
+ "object": "list",
+ "model": "rerank-2.5",
+ "usage": {"total_tokens": 10},
+ }
+
+ mock_response = MagicMock(spec=httpx.Response)
+ mock_response.json.return_value = response_data
+ mock_response.status_code = 200
+ mock_response.text = json.dumps(response_data)
+ mock_response.headers = {}
+
+ mock_logging = MagicMock()
+ model_response = RerankResponse()
+
+ with pytest.raises(ValueError, match="No results found"):
+ self.config.transform_rerank_response(
+ model=self.model,
+ raw_response=mock_response,
+ model_response=model_response,
+ logging_obj=mock_logging,
+ )
+
+ def test_transform_rerank_response_error_status(self):
+ """Test error handling for non-200 status code."""
+ mock_response = MagicMock(spec=httpx.Response)
+ mock_response.status_code = 401
+ mock_response.text = "Unauthorized"
+ mock_response.headers = {}
+
+ mock_logging = MagicMock()
+ model_response = RerankResponse()
+
+ with pytest.raises(Exception) as exc_info:
+ self.config.transform_rerank_response(
+ model=self.model,
+ raw_response=mock_response,
+ model_response=model_response,
+ logging_obj=mock_logging,
+ )
+
+ assert "Unauthorized" in str(exc_info.value)
+
+ def test_transform_rerank_response_invalid_json(self):
+ """Test error handling for invalid JSON response."""
+ mock_response = MagicMock(spec=httpx.Response)
+ mock_response.json.side_effect = json.JSONDecodeError("Invalid JSON", "doc", 0)
+ mock_response.text = "Invalid JSON response"
+ mock_response.status_code = 200
+ mock_response.headers = {}
+
+ mock_logging = MagicMock()
+ model_response = RerankResponse()
+
+ with pytest.raises(Exception) as exc_info:
+ self.config.transform_rerank_response(
+ model=self.model,
+ raw_response=mock_response,
+ model_response=model_response,
+ logging_obj=mock_logging,
+ )
+
+ assert "Failed to parse response" in str(exc_info.value)
+
+ def test_get_supported_cohere_rerank_params(self):
+ """Test getting supported parameters for Voyage AI rerank."""
+ supported_params = self.config.get_supported_cohere_rerank_params(self.model)
+ assert "query" in supported_params
+ assert "documents" in supported_params
+ assert "top_n" in supported_params
+ assert "return_documents" in supported_params
+
+ def test_validate_environment_missing_api_key(self):
+ """Test that validate_environment raises error when API key is missing."""
+ with pytest.raises(ValueError, match="Voyage AI API key is required"):
+ self.config.validate_environment(
+ headers={},
+ model=self.model,
+ api_key=None,
+ )
+
+ def test_validate_environment_with_api_key(self):
+ """Test that validate_environment works with API key."""
+ headers = self.config.validate_environment(
+ headers={},
+ model=self.model,
+ api_key="test-api-key",
+ )
+
+ assert headers["Authorization"] == "Bearer test-api-key"
+ assert headers["content-type"] == "application/json"
+
+ def test_calculate_rerank_cost(self):
+ """Test cost calculation for Voyage AI rerank."""
+ from litellm.types.rerank import RerankBilledUnits
+
+ billed_units = RerankBilledUnits(total_tokens=1000)
+ model_info = {"input_cost_per_token": 0.00000005} # $0.05 per 1M tokens
+
+ prompt_cost, completion_cost = self.config.calculate_rerank_cost(
+ model=self.model,
+ billed_units=billed_units,
+ model_info=model_info,
+ )
+
+ assert abs(prompt_cost - 0.00005) < 1e-10 # 1000 * 0.00000005
+ assert completion_cost == 0.0
+
+ def test_calculate_rerank_cost_missing_info(self):
+ """Test cost calculation returns 0 when info is missing."""
+ prompt_cost, completion_cost = self.config.calculate_rerank_cost(
+ model=self.model,
+ billed_units=None,
+ model_info=None,
+ )
+
+ assert prompt_cost == 0.0
+ assert completion_cost == 0.0