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]

Merge main into feat/openai-like-responses-api

Chesars926a0df9b08f
diff --cc litellm/llms/perplexity/responses/transformation.py
index 4beba088e7c,b6feb4ae498..51e43f2cb69
--- a/litellm/llms/perplexity/responses/transformation.py
+++ b/litellm/llms/perplexity/responses/transformation.py
@@@ -60,19 -259,238 +60,23 @@@ class PerplexityResponsesConfig(OpenAIR
litellm_params: GenericLiteLLMParams,
headers: dict,
) -> Dict:
- """
- Transform request to Perplexity Responses API format
- """
- # Check if the model is a preset (format: preset/preset-name)
+ """Handle preset/ model prefix: send as {"preset": name} instead of {"model": name}."""
if model.startswith("preset/"):
- preset_name = model.replace("preset/", "")
- data = {
- "preset": preset_name,
- "input": self._format_input(input),
- }
- # Check if preset is explicitly provided in params
- elif response_api_optional_request_params.get("preset"):
- data = {
- "preset": response_api_optional_request_params.pop("preset"),
- "input": self._format_input(input),
+ input = self._validate_input_param(input)
+ data: Dict = {
+ "preset": model[len("preset/"):],
+ "input": input,
}
- else:
- # Full request format for third-party models
- data = {
- "model": model,
- "input": self._format_input(input),
- }
-
- # Add all optional parameters
- for key, value in response_api_optional_request_params.items():
- data[key] = value
-
- return data
-
- def _format_input(
- self, input: Union[str, ResponseInputParam]
- ) -> Union[str, List[Dict[str, Any]]]:
- """
- Format input for Perplexity Responses API
-
- The API accepts either:
- - A simple string for single-turn queries
- - An array of message objects for multi-turn conversations
- """
- if isinstance(input, str):
- return input
-
- # Handle ResponseInputParam format
- if isinstance(input, list):
- formatted_messages = []
- for item in input:
- if isinstance(item, dict):
- formatted_message = {
- "type": "message",
- "role": item.get("role"),
- "content": item.get("content", ""),
- }
- formatted_messages.append(formatted_message)
- return formatted_messages
-
- return str(input)
-
- def transform_response_api_response(
- self,
- model: str,
- raw_response: httpx.Response,
- logging_obj: LiteLLMLoggingObj,
- ) -> ResponsesAPIResponse:
- """
- Transform Perplexity Responses API response to OpenAI Responses API format
- """
- try:
- raw_response_json = raw_response.json()
- except Exception as e:
- raise BaseLLMException(
- status_code=raw_response.status_code,
- message=f"Failed to parse response: {str(e)}",
- )
-
- # Check for error status
- status = raw_response_json.get("status")
- if status == "failed":
- error = raw_response_json.get("error", {})
- error_message = error.get("message", "Unknown error")
- raise BaseLLMException(
- status_code=raw_response.status_code,
- message=error_message,
- )
-
- # Transform usage to handle Perplexity's cost structure
- usage_data = raw_response_json.get("usage", {})
- transformed_usage_dict = self._transform_usage(usage_data)
-
- # Convert usage dict to ResponseAPIUsage object
- usage_obj = (
- ResponseAPIUsage(**transformed_usage_dict)
- if transformed_usage_dict
- else None
- )
-
- # Map Perplexity response to OpenAI Responses API format
- response = ResponsesAPIResponse(
- id=raw_response_json.get("id", ""),
- object="response",
- created_at=raw_response_json.get("created_at", 0),
- status=raw_response_json.get("status", "completed"),
- model=raw_response_json.get("model", model),
- output=raw_response_json.get("output", []),
- usage=usage_obj,
+ data.update(response_api_optional_request_params)
+ return data
+ return super().transform_responses_api_request(
+ model=model,
+ input=input,
+ response_api_optional_request_params=response_api_optional_request_params,
+ litellm_params=litellm_params,
+ headers=headers,
)
+
- return response
-
- def _transform_usage(self, usage_data: Dict[str, Any]) -> Dict[str, Any]:
- """
- Transform Perplexity usage data to OpenAI format
-
- Perplexity returns:
- {
- "input_tokens": 100,
- "output_tokens": 200,
- "total_tokens": 300,
- "cost": {
- "currency": "USD",
- "input_cost": 0.0001,
- "output_cost": 0.0002,
- "total_cost": 0.0003
- }
- }
-
- OpenAI expects:
- {
- "input_tokens": 100,
- "output_tokens": 200,
- "total_tokens": 300,
- "cost": 0.0003
- }
- """
- transformed = {
- "input_tokens": usage_data.get("input_tokens", 0),
- "output_tokens": usage_data.get("output_tokens", 0),
- "total_tokens": usage_data.get("total_tokens", 0),
- }
-
- # Transform cost from Perplexity format (dict) to OpenAI format (float)
- cost_obj = usage_data.get("cost")
- if isinstance(cost_obj, dict) and "total_cost" in cost_obj:
- transformed["cost"] = cost_obj["total_cost"]
- verbose_logger.debug(
- "Transformed Perplexity cost object to float: %s -> %s",
- cost_obj,
- cost_obj["total_cost"],
- )
- elif cost_obj is not None:
- # If cost is already a float/number, use it as-is
- transformed["cost"] = cost_obj
-
- # Add input_tokens_details if present
- if "input_tokens_details" in usage_data:
- transformed["input_tokens_details"] = usage_data["input_tokens_details"]
-
- # Add output_tokens_details if present
- if "output_tokens_details" in usage_data:
- transformed["output_tokens_details"] = usage_data["output_tokens_details"]
-
- return transformed
-
- def transform_streaming_response(
- self,
- model: str,
- parsed_chunk: dict,
- logging_obj: LiteLLMLoggingObj,
- ) -> ResponsesAPIStreamingResponse:
- """
- Transform a parsed streaming response chunk into a ResponsesAPIStreamingResponse
- """
- # Get the event type from the chunk
- verbose_logger.debug("Raw Perplexity Chunk=%s", parsed_chunk)
- event_type = str(parsed_chunk.get("type"))
- event_pydantic_model = PerplexityResponsesConfig.get_event_model_class(
- event_type=event_type
- )
-
- # Transform Perplexity-specific fields to OpenAI format
- parsed_chunk = self._transform_perplexity_chunk(parsed_chunk)
-
- # Defensive: Handle error.code being null (similar to OpenAI implementation)
- try:
- error_obj = parsed_chunk.get("error")
- if isinstance(error_obj, dict) and error_obj.get("code") is None:
- # Preserve other fields, but ensure `code` is a non-null string
- parsed_chunk = dict(parsed_chunk)
- parsed_chunk["error"] = dict(error_obj)
- parsed_chunk["error"]["code"] = "unknown_error"
- except Exception:
- # If anything unexpected happens here, fall back to attempting
- # instantiation and let higher-level handlers manage errors.
- verbose_logger.debug("Failed to coalesce error.code in parsed_chunk")
-
- return event_pydantic_model(**parsed_chunk)
-
- def _transform_perplexity_chunk(self, chunk: dict) -> dict:
- """
- Transform Perplexity-specific fields in a streaming chunk to OpenAI format.
-
- This handles:
- - Converting Perplexity's cost object to a simple float
- """
- # Make a copy to avoid modifying the original
- chunk = dict(chunk)
-
- # Transform usage.cost from Perplexity format to OpenAI format
- # Perplexity: {"currency": "USD", "input_cost": 0.0001, "output_cost": 0.0002, "total_cost": 0.0003}
- # OpenAI: 0.0003 (just the total_cost as a float)
- try:
- response_obj = chunk.get("response")
- if isinstance(response_obj, dict):
- usage_obj = response_obj.get("usage")
- if isinstance(usage_obj, dict):
- cost_obj = usage_obj.get("cost")
- if isinstance(cost_obj, dict) and "total_cost" in cost_obj:
- # Replace the cost object with just the total_cost value
- chunk = dict(chunk)
- chunk["response"] = dict(response_obj)
- chunk["response"]["usage"] = dict(usage_obj)
- chunk["response"]["usage"]["cost"] = cost_obj["total_cost"]
- verbose_logger.debug(
- "Transformed Perplexity cost object to float: %s -> %s",
- cost_obj,
- cost_obj["total_cost"],
- )
- except Exception as e:
- # If transformation fails, log and continue with original chunk
- verbose_logger.debug("Failed to transform Perplexity cost object: %s", e)
-
- return chunk
-
+ def supports_native_websocket(self) -> bool:
+ """Perplexity does not support native WebSocket for Responses API"""
+ return False