The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
Revert "Update perplexity cost tracking (#15743)" (#16345)
Ishaan Jaffbd7d653bae4b
diff --git a/litellm/llms/perplexity/chat/__init__.py b/litellm/llms/perplexity/chat/__init__.pydeleted file mode 100644index f4f9edf38e5..00000000000--- a/litellm/llms/perplexity/chat/__init__.py+++ /dev/null@@ -1 +0,0 @@-"""Perplexity chat completion transformations."""diff --git a/litellm/llms/perplexity/chat/transformation.py b/litellm/llms/perplexity/chat/transformation.pyindex 831b009de7a..27e6415ff8b 100644--- a/litellm/llms/perplexity/chat/transformation.py+++ b/litellm/llms/perplexity/chat/transformation.py@@ -1,32 +1,25 @@-"""Translate from OpenAI's `/v1/chat/completions` to Perplexity's `/v1/chat/completions`."""+"""+Translate from OpenAI's `/v1/chat/completions` to Perplexity's `/v1/chat/completions`+"""-from __future__ import annotations--from typing import TYPE_CHECKING, Any, List, Optional, Tuple+from typing import Any, List, Optional, Tuple+import httpximport litellmfrom litellm._logging import verbose_logger-from litellm.llms.openai.chat.gpt_transformation import OpenAIGPTConfigfrom litellm.secret_managers.main import get_secret_str-from litellm.types.utils import ModelResponse, PromptTokensDetailsWrapper, Usage--if TYPE_CHECKING:- import httpx-- from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj- from litellm.types.llms.openai import (- AllMessageValues,- ChatCompletionAnnotation,- ChatCompletionAnnotationURLCitation,- )+from litellm.types.llms.openai import AllMessageValues+from litellm.types.utils import Usage, PromptTokensDetailsWrapper+from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj+from litellm.llms.openai.chat.gpt_transformation import OpenAIGPTConfig+from litellm.types.utils import ModelResponse+from litellm.types.llms.openai import ChatCompletionAnnotation+from litellm.types.llms.openai import ChatCompletionAnnotationURLCitationclass PerplexityChatConfig(OpenAIGPTConfig):- """Configuration for Perplexity chat completions."""-@property- def custom_llm_provider(self) -> str | None:- """Return the custom LLM provider name."""+ def custom_llm_provider(self) -> Optional[str]:return "perplexity"def _get_openai_compatible_provider_info(@@ -40,38 +33,6 @@ class PerplexityChatConfig(OpenAIGPTConfig):)return api_base, dynamic_api_key- def validate_environment(- self,- headers: dict,- model: str,- messages: list,- optional_params: dict,- litellm_params: dict,- api_key: Optional[str] = None,- api_base: Optional[str] = None,- ) -> dict:- """Validate Perplexity environment and set headers."""- # Get API key from environment if not provided- if api_key is None:- _, api_key = self._get_openai_compatible_provider_info(- api_base=api_base, api_key=api_key- )-- # Validate API key is present- if api_key is None:- raise ValueError(- "The api_key client option must be set either by passing api_key to the client or by setting the PERPLEXITY_API_KEY environment variable"- )-- # Set authorization header- headers["Authorization"] = f"Bearer {api_key}"-- # Ensure Content-Type is set to application/json- if "content-type" not in headers and "Content-Type" not in headers:- headers["Content-Type"] = "application/json"-- return headers-def get_supported_openai_params(self, model: str) -> list:"""Perplexity supports a subset of OpenAI params@@ -111,8 +72,7 @@ class PerplexityChatConfig(OpenAIGPTConfig):return base_openai_params-- def transform_response( # noqa: PLR0913+ def transform_response(self,model: str,raw_response: httpx.Response,@@ -122,11 +82,10 @@ class PerplexityChatConfig(OpenAIGPTConfig):messages: List[AllMessageValues],optional_params: dict,litellm_params: dict,- encoding: Any,+ encoding: Any,api_key: Optional[str] = None,- json_mode: Optional[bool] = None,+ json_mode: Optional[bool] = None,) -> ModelResponse:- """Transform Perplexity response to standard format."""# Call the parent transform_response first to handle the standard transformationmodel_response = super().transform_response(model=model,@@ -145,29 +104,28 @@ class PerplexityChatConfig(OpenAIGPTConfig):# Extract and enhance usage with Perplexity-specific fieldstry:raw_response_json = raw_response.json()- self.add_cost_to_usage(model_response, raw_response_json)self._enhance_usage_with_perplexity_fields(- model_response, raw_response_json,+ model_response, raw_response_json)self._add_citations_as_annotations(model_response, raw_response_json)- except (ValueError, TypeError, KeyError) as e:+ except Exception as e:verbose_logger.debug(f"Error extracting Perplexity-specific usage fields: {e}")return model_response- def _enhance_usage_with_perplexity_fields(- self, model_response: ModelResponse, raw_response_json: dict,+ def _enhance_usage_with_perplexity_fields(+ self, model_response: ModelResponse, raw_response_json: dict) -> None:- """Extract citation tokens and search queries from Perplexity API response.-- Add them to the usage object using standard LiteLLM fields.+ """+ Extract citation tokens and search queries from Perplexity API response+ and add them to the usage object using standard LiteLLM fields."""if not hasattr(model_response, "usage") or model_response.usage is None:# Create a usage object if it doesn't exist (when usage was None)model_response.usage = Usage( # type: ignore[attr-defined]prompt_tokens=0,completion_tokens=0,- total_tokens=0,+ total_tokens=0)usage = model_response.usage # type: ignore[attr-defined]@@ -188,7 +146,7 @@ class PerplexityChatConfig(OpenAIGPTConfig):# Extract search queries count from usage or response metadata# Perplexity might include this in the usage object or as separate metadataperplexity_usage = raw_response_json.get("usage", {})-+# Try to extract search queries from usage field first, then root levelnum_search_queries = perplexity_usage.get("num_search_queries")if num_search_queries is None:@@ -197,18 +155,18 @@ class PerplexityChatConfig(OpenAIGPTConfig):num_search_queries = perplexity_usage.get("search_queries")if num_search_queries is None:num_search_queries = raw_response_json.get("search_queries")-+# Create or update prompt_tokens_details to include web search requests and citation tokensif citation_tokens > 0 or (num_search_queries is not None and num_search_queries > 0):if usage.prompt_tokens_details is None:usage.prompt_tokens_details = PromptTokensDetailsWrapper()-+# Store citation tokens count for cost calculationif citation_tokens > 0:- usage.citation_tokens = citation_tokens-+ setattr(usage, "citation_tokens", citation_tokens)+# Store search queries count in the standard web_search_requests fieldif num_search_queries is not None and num_search_queries > 0:usage.prompt_tokens_details.web_search_requests = num_search_queries@@ -290,35 +248,4 @@ class PerplexityChatConfig(OpenAIGPTConfig):if citations:setattr(model_response, "citations", citations)if search_results:- setattr(model_response, "search_results", search_results)-- def add_cost_to_usage(self, model_response: ModelResponse, raw_response_json: dict) -> None:- """Add the cost to the usage object."""- try:- usage_data = raw_response_json.get("usage")- if usage_data:- # Try different possible cost field locations- response_cost = None-- # Check if cost is directly in usage (flat structure)- if "total_cost" in usage_data:- response_cost = usage_data["total_cost"]- # Check if cost is nested (cost.total_cost structure)- elif "cost" in usage_data and isinstance(usage_data["cost"], dict):- response_cost = usage_data["cost"].get("total_cost")- # Check if cost is a simple value- elif "cost" in usage_data:- response_cost = usage_data["cost"]-- if response_cost is not None:- # Store cost in hidden params for the cost calculator to use- if not hasattr(model_response, "_hidden_params"):- model_response._hidden_params = {}- if "additional_headers" not in model_response._hidden_params:- model_response._hidden_params["additional_headers"] = {}- model_response._hidden_params["additional_headers"][- "llm_provider-x-litellm-response-cost"- ] = float(response_cost)- except (ValueError, TypeError, KeyError) as e:- verbose_logger.debug(f"Error adding cost to usage: {e}")- # If we can't extract cost, continue without it - don't fail the response+ setattr(model_response, "search_results", search_results)\ No newline at end of filediff --git a/litellm/main.py b/litellm/main.pyindex 9cae34d1678..b7af4e8d39c 100644--- a/litellm/main.py+++ b/litellm/main.py@@ -2033,36 +2033,11 @@ def completion( # type: ignore # noqa: PLR0915logging.post_call(input=messages, api_key=api_key, original_response=response)- elif custom_llm_provider == "perplexity":- response = base_llm_http_handler.completion(- model=model,- messages=messages,- headers=headers,- model_response=model_response,- api_key=api_key,- api_base=api_base,- acompletion=acompletion,- logging_obj=logging,- optional_params=optional_params,- litellm_params=litellm_params,- shared_session=shared_session,- timeout=timeout,- client=client,- custom_llm_provider=custom_llm_provider,- encoding=encoding,- stream=stream,- provider_config=provider_config,- )-- ## LOGGING - Call after response has been processed by transform_response- logging.post_call(- input=messages, api_key=api_key, original_response=response- )-elif (model in litellm.open_ai_chat_completion_modelsor custom_llm_provider == "custom_openai"or custom_llm_provider == "deepinfra"+ or custom_llm_provider == "perplexity"or custom_llm_provider == "nvidia_nim"or custom_llm_provider == "cerebras"or custom_llm_provider == "baseten"diff --git a/tests/llm_translation/test_perplexity_reasoning.py b/tests/llm_translation/test_perplexity_reasoning.pyindex 7db99014e9d..70b665ea339 100644--- a/tests/llm_translation/test_perplexity_reasoning.py+++ b/tests/llm_translation/test_perplexity_reasoning.py@@ -62,12 +62,13 @@ class TestPerplexityReasoning:"""Test that reasoning_effort is correctly passed in actual completion call (mocked)"""- import httpx+ from openai import OpenAI+ from openai.types.chat.chat_completion import ChatCompletionlitellm.set_verbose = True# Mock successful response with reasoning content- response_json = {+ response_object = {"id": "cmpl-test","object": "chat.completion","created": 1677652288,@@ -93,37 +94,35 @@ class TestPerplexityReasoning:},}- def mock_post(*args, **kwargs):- # Create a mock response- mock_response = MagicMock(spec=httpx.Response)- mock_response.status_code = 200- mock_response.headers = {"content-type": "application/json"}- mock_response.json.return_value = response_json- mock_response.text = json.dumps(response_json)-- # Store the request data for verification- mock_post.last_request_data = kwargs.get("data")- if isinstance(mock_post.last_request_data, (str, bytes)):- mock_post.last_request_data = json.loads(mock_post.last_request_data)-- return mock_response+ pydantic_obj = ChatCompletion(**response_object)++ def _return_pydantic_obj(*args, **kwargs):+ new_response = MagicMock()+ new_response.headers = {"content-type": "application/json"}+ new_response.parse.return_value = pydantic_obj+ return new_response- # Mock at the HTTP handler level- with patch("litellm.llms.custom_httpx.http_handler.HTTPHandler.post", side_effect=mock_post) as mock_http:+ openai_client = OpenAI(api_key="fake-api-key")++ with patch.object(+ openai_client.chat.completions.with_raw_response, "create", side_effect=_return_pydantic_obj+ ) as mock_client:response = completion(model=model,messages=[{"role": "user", "content": "Hello, please think about this carefully."}],reasoning_effort="high",- api_key="fake-api-key",+ client=openai_client,)# Verify the call was made- assert mock_http.called+ assert mock_client.called++ # Get the request data from the mock call+ call_args = mock_client.call_args+ request_data = call_args.kwargs# Verify reasoning_effort was included in the request- request_data = mock_post.last_request_data- assert request_data is not Noneassert "reasoning_effort" in request_dataassert request_data["reasoning_effort"] == "high"diff --git a/tests/local_testing/test_completion.py b/tests/local_testing/test_completion.pyindex d8ebb059b9a..a3f3ba5729a 100644--- a/tests/local_testing/test_completion.py+++ b/tests/local_testing/test_completion.py@@ -1244,9 +1244,6 @@ def test_completion_fireworks_ai_dynamic_params(api_key, api_base):# @pytest.mark.skip(reason="this test is flaky")def test_completion_perplexity_api():try:- import httpx- import json-response_object = {"id": "a8f37485-026e-45da-81a9-cf0184896840","model": "llama-3-sonar-small-32k-online",@@ -1273,17 +1270,25 @@ def test_completion_perplexity_api():],}- def mock_post(*args, **kwargs):- # Create a mock response- mock_response = MagicMock(spec=httpx.Response)- mock_response.status_code = 200- mock_response.headers = {"content-type": "application/json"}- mock_response.json.return_value = response_object- mock_response.text = json.dumps(response_object)- return mock_response-- # Mock at the HTTP handler level- with patch("litellm.llms.custom_httpx.http_handler.HTTPHandler.post", side_effect=mock_post):+ from openai import OpenAI+ from openai.types.chat.chat_completion import ChatCompletion++ pydantic_obj = ChatCompletion(**response_object)++ def _return_pydantic_obj(*args, **kwargs):+ new_response = MagicMock()+ new_response.headers = {"hello": "world"}++ new_response.parse.return_value = pydantic_obj+ return new_response++ openai_client = OpenAI()++ with patch.object(+ openai_client.chat.completions.with_raw_response,+ "create",+ side_effect=_return_pydantic_obj,+ ) as mock_client:# litellm.set_verbose= Truemessages = [{"role": "system", "content": "You're a good bot"},@@ -1297,9 +1302,10 @@ def test_completion_perplexity_api():},]response = completion(- model="perplexity/llama-3-sonar-small-32k-online",+ model="mistral-7b-instruct",messages=messages,- api_key="fake-api-key",+ api_base="https://api.perplexity.ai",+ client=openai_client,)print(response)assert hasattr(response, "citations")diff --git a/tests/test_litellm/llms/perplexity/chat/test_perplexity_chat_transformation.py b/tests/test_litellm/llms/perplexity/chat/test_perplexity_chat_transformation.pyindex d83c1a9f659..784e6f6fe63 100644--- a/tests/test_litellm/llms/perplexity/chat/test_perplexity_chat_transformation.py+++ b/tests/test_litellm/llms/perplexity/chat/test_perplexity_chat_transformation.py@@ -7,7 +7,7 @@ from Perplexity API responses.import osimport sys-from unittest.mock import Mock, patch+from unittest.mock import Mockimport pytest@@ -707,152 +707,4 @@ class TestPerplexityChatTransformation:# Check that no annotations were created (message content is None)assert choice.message.content is None# No annotations should be created since content is None- assert not hasattr(choice.message, 'annotations') or choice.message.annotations is None-- # Tests for cost extraction functionality- def test_add_cost_to_usage_flat_structure(self):- """Test cost extraction from flat usage structure."""- config = PerplexityChatConfig()-- # Create a ModelResponse- model_response = ModelResponse()- model_response.usage = Usage(- prompt_tokens=100,- completion_tokens=50,- total_tokens=150- )-- # Mock raw response with flat cost structure- raw_response_json = {- "choices": [{"message": {"content": "Test response"}}],- "usage": {- "prompt_tokens": 100,- "completion_tokens": 50,- "total_tokens": 150,- "total_cost": 0.00015- }- }-- # Test cost extraction- config.add_cost_to_usage(model_response, raw_response_json)-- # Check that cost was stored in hidden params- assert hasattr(model_response, "_hidden_params")- assert "additional_headers" in model_response._hidden_params- assert "llm_provider-x-litellm-response-cost" in model_response._hidden_params["additional_headers"]-- cost = model_response._hidden_params["additional_headers"]["llm_provider-x-litellm-response-cost"]- assert cost == 0.00015-- def test_add_cost_to_usage_nested_structure(self):- """Test cost extraction from nested usage structure."""- config = PerplexityChatConfig()-- # Create a ModelResponse- model_response = ModelResponse()- model_response.usage = Usage(- prompt_tokens=100,- completion_tokens=50,- total_tokens=150- )-- # Mock raw response with nested cost structure- raw_response_json = {- "choices": [{"message": {"content": "Test response"}}],- "usage": {- "prompt_tokens": 100,- "completion_tokens": 50,- "total_tokens": 150,- "cost": {- "total_cost": 0.00025- }- }- }-- # Test cost extraction- config.add_cost_to_usage(model_response, raw_response_json)-- # Check that cost was stored in hidden params- assert hasattr(model_response, "_hidden_params")- assert "additional_headers" in model_response._hidden_params- assert "llm_provider-x-litellm-response-cost" in model_response._hidden_params["additional_headers"]-- cost = model_response._hidden_params["additional_headers"]["llm_provider-x-litellm-response-cost"]- assert cost == 0.00025-- def test_add_cost_to_usage_no_cost_data(self):- """Test handling when no cost data is present."""- config = PerplexityChatConfig()-- # Create a ModelResponse- model_response = ModelResponse()- model_response.usage = Usage(- prompt_tokens=100,- completion_tokens=50,- total_tokens=150- )-- # Mock raw response without cost- raw_response_json = {- "choices": [{"message": {"content": "Test response"}}],- "usage": {- "prompt_tokens": 100,- "completion_tokens": 50,- "total_tokens": 150- }- }-- # Test cost extraction - should not raise error- config.add_cost_to_usage(model_response, raw_response_json)-- # Should not have cost in hidden params- if hasattr(model_response, "_hidden_params"):- assert "llm_provider-x-litellm-response-cost" not in model_response._hidden_params.get("additional_headers", {})-- def test_transform_response_includes_cost_extraction(self):- """Test that transform_response includes cost extraction."""- config = PerplexityChatConfig()-- # Mock raw response- mock_response = Mock()- mock_response.json.return_value = {- "choices": [{"message": {"content": "Test response"}}],- "usage": {- "prompt_tokens": 100,- "completion_tokens": 50,- "total_tokens": 150,- "total_cost": 0.00015- }- }- mock_response.headers = {}-- # Create a ModelResponse- model_response = ModelResponse()- model_response.usage = Usage(- prompt_tokens=100,- completion_tokens=50,- total_tokens=150- )- model_response.model = "perplexity/sonar-pro"-- # Mock the parent transform_response to return our model_response- with patch.object(config.__class__.__bases__[0], 'transform_response', return_value=model_response):- result = config.transform_response(- model="perplexity/sonar-pro",- raw_response=mock_response,- model_response=model_response,- logging_obj=Mock(),- request_data={},- messages=[{"role": "user", "content": "Test"}],- optional_params={},- litellm_params={},- encoding=None,- )-- # Check that cost was extracted and stored- assert hasattr(result, "_hidden_params")- assert "additional_headers" in result._hidden_params- assert "llm_provider-x-litellm-response-cost" in result._hidden_params["additional_headers"]-- cost = result._hidden_params["additional_headers"]["llm_provider-x-litellm-response-cost"]- assert cost == 0.00015\ No newline at end of file+ assert not hasattr(choice.message, 'annotations') or choice.message.annotations is None\ No newline at end of filediff --git a/tests/test_litellm/llms/perplexity/test_perplexity_cost_calculator.py b/tests/test_litellm/llms/perplexity/test_perplexity_cost_calculator.pyindex 58b037269a7..f9a52100070 100644--- a/tests/test_litellm/llms/perplexity/test_perplexity_cost_calculator.py+++ b/tests/test_litellm/llms/perplexity/test_perplexity_cost_calculator.py@@ -17,8 +17,7 @@ import pytestsys.path.insert(0, os.path.abspath("../../../.."))import litellm-from litellm import ModelResponse-from litellm.cost_calculator import completion_cost, cost_per_token, response_cost_calculator+from litellm.cost_calculator import completion_cost, cost_per_tokenfrom litellm.llms.perplexity.cost_calculator import cost_per_token as perplexity_cost_per_tokenfrom litellm.types.utils import Usage, PromptTokensDetailsWrapperfrom litellm.utils import get_model_info@@ -371,116 +370,4 @@ class TestPerplexityCostCalculator:# Ensure costs are non-negativeassert prompt_cost >= 0- assert completion_cost >= 0-- def test_cost_extraction_priority_over_calculation(self):- """Test that extracted cost from API response takes priority over calculated cost."""- from litellm.cost_calculator import response_cost_calculator- from litellm.llms.perplexity.chat.transformation import PerplexityChatConfig-- config = PerplexityChatConfig()-- # Create a ModelResponse with extracted cost- model_response = ModelResponse()- model_response.usage = Usage(- prompt_tokens=100,- completion_tokens=50,- total_tokens=150- )- model_response.model = "perplexity/sonar-pro"-- # Mock raw response with cost- raw_response_json = {- "choices": [{"message": {"content": "Test response"}}],- "usage": {- "prompt_tokens": 100,- "completion_tokens": 50,- "total_tokens": 150,- "total_cost": 0.00015 # This should be used instead of calculated cost- }- }-- # Extract cost from API response- config.add_cost_to_usage(model_response, raw_response_json)-- # Test response cost calculator - should use extracted cost- cost = response_cost_calculator(- response_object=model_response,- model="perplexity/sonar-pro",- custom_llm_provider="perplexity",- call_type="completion",- optional_params={}- )-- # Should return the extracted cost, not calculated cost- assert cost == 0.00015-- def test_cost_extraction_from_nested_structure(self):- """Test cost extraction from nested usage structure."""- from litellm.llms.perplexity.chat.transformation import PerplexityChatConfig-- config = PerplexityChatConfig()-- # Create a ModelResponse- model_response = ModelResponse()- model_response.usage = Usage(- prompt_tokens=100,- completion_tokens=50,- total_tokens=150- )-- # Mock raw response with nested cost structure- raw_response_json = {- "choices": [{"message": {"content": "Test response"}}],- "usage": {- "prompt_tokens": 100,- "completion_tokens": 50,- "total_tokens": 150,- "cost": {- "total_cost": 0.00025- }- }- }-- # Test cost extraction- config.add_cost_to_usage(model_response, raw_response_json)-- # Check that cost was stored in hidden params- assert hasattr(model_response, "_hidden_params")- assert "additional_headers" in model_response._hidden_params- assert "llm_provider-x-litellm-response-cost" in model_response._hidden_params["additional_headers"]-- cost = model_response._hidden_params["additional_headers"]["llm_provider-x-litellm-response-cost"]- assert cost == 0.00025-- def test_cost_extraction_error_handling(self):- """Test error handling during cost extraction."""- from litellm.llms.perplexity.chat.transformation import PerplexityChatConfig-- config = PerplexityChatConfig()-- # Create a ModelResponse- model_response = ModelResponse()- model_response.usage = Usage(- prompt_tokens=100,- completion_tokens=50,- total_tokens=150- )-- # Mock raw response with invalid cost data- raw_response_json = {- "choices": [{"message": {"content": "Test response"}}],- "usage": {- "prompt_tokens": 100,- "completion_tokens": 50,- "total_tokens": 150,- "cost": "invalid_cost" # Invalid cost type- }- }-- # Test cost extraction - should not raise error- config.add_cost_to_usage(model_response, raw_response_json)-- # Should not have cost in hidden params due to error- if hasattr(model_response, "_hidden_params"):- assert "llm_provider-x-litellm-response-cost" not in model_response._hidden_params.get("additional_headers", {})\ No newline at end of file+ assert completion_cost >= 0\ No newline at end of filediff --git a/tests/test_litellm/llms/perplexity/test_perplexity_integration.py b/tests/test_litellm/llms/perplexity/test_perplexity_integration.pyindex b38e56ce8e8..a702e9ebc4c 100644--- a/tests/test_litellm/llms/perplexity/test_perplexity_integration.py+++ b/tests/test_litellm/llms/perplexity/test_perplexity_integration.py@@ -316,169 +316,4 @@ class TestPerplexityIntegration:expected_completion_cost = (50 * 8e-6) + (1 / 1000 * 0.005)assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-6)- assert math.isclose(completion_cost_val, expected_completion_cost, rel_tol=1e-6)-- def test_cost_extraction_from_api_response(self):- """Test cost extraction from Perplexity API response."""- config = PerplexityChatConfig()-- # Create a ModelResponse- model_response = ModelResponse()- model_response.usage = Usage(- prompt_tokens=100,- completion_tokens=50,- total_tokens=150- )- model_response.model = "perplexity/sonar-pro"-- # Mock raw response with cost- raw_response_json = {- "choices": [{"message": {"content": "Test response"}}],- "usage": {- "prompt_tokens": 100,- "completion_tokens": 50,- "total_tokens": 150,- "total_cost": 0.00015- }- }-- # Test cost extraction- config.add_cost_to_usage(model_response, raw_response_json)-- # Check that cost was stored in hidden params- assert hasattr(model_response, "_hidden_params")- assert "additional_headers" in model_response._hidden_params- assert "llm_provider-x-litellm-response-cost" in model_response._hidden_params["additional_headers"]-- cost = model_response._hidden_params["additional_headers"]["llm_provider-x-litellm-response-cost"]- assert cost == 0.00015-- def test_cost_extraction_integration_with_main_calculator(self):- """Test that extracted cost takes priority over calculated cost."""- config = PerplexityChatConfig()-- # Create a ModelResponse- model_response = ModelResponse()- model_response.usage = Usage(- prompt_tokens=100,- completion_tokens=50,- total_tokens=150- )- model_response.model = "perplexity/sonar-pro"-- # Mock raw response with cost- raw_response_json = {- "choices": [{"message": {"content": "Test response"}}],- "usage": {- "prompt_tokens": 100,- "completion_tokens": 50,- "total_tokens": 150,- "total_cost": 0.00015- }- }-- # Extract cost- config.add_cost_to_usage(model_response, raw_response_json)-- # Test main cost calculator - should use extracted cost- from litellm.cost_calculator import response_cost_calculator- cost = response_cost_calculator(- response_object=model_response,- model="perplexity/sonar-pro",- custom_llm_provider="perplexity",- call_type="completion",- optional_params={}- )-- # Should return the extracted cost, not calculated cost- assert cost == 0.00015-- def test_cost_extraction_nested_structure(self):- """Test cost extraction from nested usage structure."""- config = PerplexityChatConfig()-- # Create a ModelResponse- model_response = ModelResponse()- model_response.usage = Usage(- prompt_tokens=100,- completion_tokens=50,- total_tokens=150- )-- # Mock raw response with nested cost structure- raw_response_json = {- "choices": [{"message": {"content": "Test response"}}],- "usage": {- "prompt_tokens": 100,- "completion_tokens": 50,- "total_tokens": 150,- "cost": {- "total_cost": 0.00025- }- }- }-- # Test cost extraction- config.add_cost_to_usage(model_response, raw_response_json)-- # Check that cost was stored in hidden params- assert hasattr(model_response, "_hidden_params")- assert "additional_headers" in model_response._hidden_params- assert "llm_provider-x-litellm-response-cost" in model_response._hidden_params["additional_headers"]-- cost = model_response._hidden_params["additional_headers"]["llm_provider-x-litellm-response-cost"]- assert cost == 0.00025-- def test_cost_extraction_error_handling(self):- """Test error handling during cost extraction."""- config = PerplexityChatConfig()-- # Create a ModelResponse- model_response = ModelResponse()- model_response.usage = Usage(- prompt_tokens=100,- completion_tokens=50,- total_tokens=150- )-- # Mock raw response with invalid cost data- raw_response_json = {- "choices": [{"message": {"content": "Test response"}}],- "usage": {- "prompt_tokens": 100,- "completion_tokens": 50,- "total_tokens": 150,- "cost": "invalid_cost" # Invalid cost type- }- }-- # Test cost extraction - should not raise error- config.add_cost_to_usage(model_response, raw_response_json)-- # Should not have cost in hidden params due to error- if hasattr(model_response, "_hidden_params"):- assert "llm_provider-x-litellm-response-cost" not in model_response._hidden_params.get("additional_headers", {})-- def test_cost_extraction_no_usage_data(self):- """Test handling when no usage data is present."""- config = PerplexityChatConfig()-- # Create a ModelResponse- model_response = ModelResponse()- model_response.usage = Usage(- prompt_tokens=100,- completion_tokens=50,- total_tokens=150- )-- # Mock raw response without usage- raw_response_json = {- "choices": [{"message": {"content": "Test response"}}]- }-- # Test cost extraction - should not raise error- config.add_cost_to_usage(model_response, raw_response_json)-- # Should not have cost in hidden params- if hasattr(model_response, "_hidden_params"):- assert "llm_provider-x-litellm-response-cost" not in model_response._hidden_params.get("additional_headers", {})\ No newline at end of file+ assert math.isclose(completion_cost_val, expected_completion_cost, rel_tol=1e-6)\ No newline at end of file